gt stringclasses 1
value | context stringlengths 2.05k 161k |
|---|---|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.containers.containerregistry;
import com.azure.containers.containerregistry.implementation.UtilsImpl;
import com.azure.containers.containerregistry.models.ContainerRegistryAudience;
import com.azure.core.annotation.ServiceClientBuilder;
import com.azure.core.client.traits.ConfigurationTrait;
import com.azure.core.client.traits.EndpointTrait;
import com.azure.core.client.traits.HttpTrait;
import com.azure.core.client.traits.TokenCredentialTrait;
import com.azure.core.credential.TokenCredential;
import com.azure.core.http.HttpClient;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.HttpPipelinePosition;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.http.policy.HttpLogOptions;
import com.azure.core.http.policy.HttpPipelinePolicy;
import com.azure.core.http.policy.RetryOptions;
import com.azure.core.http.policy.RetryPolicy;
import com.azure.core.util.ClientOptions;
import com.azure.core.util.Configuration;
import com.azure.core.util.HttpClientOptions;
import com.azure.core.util.logging.ClientLogger;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* This class provides a fluent builder API to help aid the configuration and instantiation of {@link
* ContainerRegistryClient ContainerRegistryClients} and {@link ContainerRegistryAsyncClient ContainerRegistryAsyncClients}, call {@link
* #buildClient() buildClient} and {@link #buildAsyncClient() buildAsyncClient} respectively to construct an instance of
* the desired client.
*
* <p>The client needs the service endpoint of the Azure Container Registry, Audience for ACR that you want to target and Azure access credentials to use for authentication.
* <p><strong>Instantiating an asynchronous Container Registry client</strong></p>
* <!-- src_embed com.azure.containers.containerregistry.ContainerRegistryAsyncClient.instantiation -->
* <pre>
* ContainerRegistryAsyncClient registryAsyncClient = new ContainerRegistryClientBuilder()
* .endpoint(endpoint)
* .credential(credential)
* .audience(ContainerRegistryAudience.AZURE_RESOURCE_MANAGER_PUBLIC_CLOUD)
* .buildAsyncClient();
* </pre>
* <!-- end com.azure.containers.containerregistry.ContainerRegistryAsyncClient.instantiation -->
*
* <p><strong>Instantiating a synchronous Container Registry client</strong></p>
* <!-- src_embed com.azure.containers.containerregistry.ContainerRegistryClient.instantiation -->
* <pre>
* ContainerRegistryClient registryAsyncClient = new ContainerRegistryClientBuilder()
* .endpoint(endpoint)
* .audience(ContainerRegistryAudience.AZURE_RESOURCE_MANAGER_PUBLIC_CLOUD)
* .credential(credential)
* .buildClient();
* </pre>
* <!-- end com.azure.containers.containerregistry.ContainerRegistryClient.instantiation -->
*
* <p>Another way to construct the client is using a {@link HttpPipeline}. The pipeline gives the client an
* authenticated way to communicate with the service but it doesn't contain the service endpoint. Set the pipeline with
* {@link #pipeline(HttpPipeline) this} and set the service endpoint with {@link #endpoint(String) this}. Using a
* pipeline requires additional setup but allows for finer control on how the {@link ContainerRegistryClient} and {@link
* ContainerRegistryAsyncClient} is built.</p>
* <p>The service does not directly support AAD credentials and as a result the clients internally depend on a policy that converts
* the AAD credentials to the Azure Container Registry specific service credentials. In case you use your own pipeline, you
* would need to provide implementation for this policy as well.
* For more information please see <a href="https://github.com/Azure/acr/blob/main/docs/AAD-OAuth.md"> Azure Container Registry Authentication </a>.</p>
*
* <p><strong>Instantiating an asynchronous Container Registry client using a custom pipeline</strong></p>
* <!-- src_embed com.azure.containers.containerregistry.ContainerRegistryAsyncClient.pipeline.instantiation -->
* <pre>
* HttpPipeline pipeline = new HttpPipelineBuilder()
* .policies(/* add policies */)
* .build();
*
* ContainerRegistryAsyncClient registryAsyncClient = new ContainerRegistryClientBuilder()
* .pipeline(pipeline)
* .endpoint(endpoint)
* .audience(ContainerRegistryAudience.AZURE_RESOURCE_MANAGER_PUBLIC_CLOUD)
* .credential(credential)
* .buildAsyncClient();
* </pre>
* <!-- end com.azure.containers.containerregistry.ContainerRegistryAsyncClient.pipeline.instantiation -->
*
* <p><strong>Instantiating a synchronous Container Registry client with custom pipeline</strong></p>
* <!-- src_embed com.azure.containers.containerregistry.ContainerRegistryClient.pipeline.instantiation -->
* <pre>
* HttpPipeline pipeline = new HttpPipelineBuilder()
* .policies(/* add policies */)
* .build();
*
* ContainerRegistryClient registryAsyncClient = new ContainerRegistryClientBuilder()
* .pipeline(pipeline)
* .endpoint(endpoint)
* .audience(ContainerRegistryAudience.AZURE_RESOURCE_MANAGER_PUBLIC_CLOUD)
* .credential(credential)
* .buildClient();
* </pre>
* <!-- end com.azure.containers.containerregistry.ContainerRegistryClient.pipeline.instantiation -->
*
*
* @see ContainerRegistryAsyncClient
* @see ContainerRegistryClient
*/
@ServiceClientBuilder(
serviceClients = {
ContainerRegistryClient.class,
ContainerRegistryAsyncClient.class,
ContainerRepositoryAsync.class,
ContainerRepository.class,
RegistryArtifactAsync.class,
RegistryArtifact.class
})
public final class ContainerRegistryClientBuilder implements
ConfigurationTrait<ContainerRegistryClientBuilder>,
EndpointTrait<ContainerRegistryClientBuilder>,
HttpTrait<ContainerRegistryClientBuilder>,
TokenCredentialTrait<ContainerRegistryClientBuilder> {
private final ClientLogger logger = new ClientLogger(ContainerRegistryClientBuilder.class);
private final List<HttpPipelinePolicy> perCallPolicies = new ArrayList<>();
private final List<HttpPipelinePolicy> perRetryPolicies = new ArrayList<>();
private ClientOptions clientOptions;
private Configuration configuration;
private String endpoint;
private HttpClient httpClient;
private TokenCredential credential;
private HttpPipeline httpPipeline;
private HttpLogOptions httpLogOptions;
private RetryPolicy retryPolicy;
private RetryOptions retryOptions;
private ContainerRegistryServiceVersion version;
private ContainerRegistryAudience audience;
/**
* Sets the service endpoint for the Azure Container Registry instance.
*
* @param endpoint The URL of the Container Registry instance.
* @return The updated {@link ContainerRegistryClientBuilder} object.
* @throws IllegalArgumentException If {@code endpoint} is null or it cannot be parsed into a valid URL.
*/
@Override
public ContainerRegistryClientBuilder endpoint(String endpoint) {
try {
new URL(endpoint);
} catch (MalformedURLException ex) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL"));
}
this.endpoint = endpoint;
return this;
}
/**
* Sets the audience for the Azure Container Registry service.
*
* @param audience ARM management scope associated with the given registry.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder audience(ContainerRegistryAudience audience) {
this.audience = audience;
return this;
}
/**
* Sets the {@link TokenCredential} used to authorize requests sent to the service. Refer to the Azure SDK for Java
* <a href="https://aka.ms/azsdk/java/docs/identity">identity and authentication</a>
* documentation for more details on proper usage of the {@link TokenCredential} type.
*
* @param credential {@link TokenCredential} used to authorize requests sent to the service.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
@Override
public ContainerRegistryClientBuilder credential(TokenCredential credential) {
this.credential = credential;
return this;
}
/**
* Sets the {@link HttpPipeline} to use for the service client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* If {@code pipeline} is set, all settings other than {@link #endpoint(String) endpoint} are ignored
* to build {@link ContainerRegistryAsyncClient} or {@link ContainerRegistryClient}.<br>
* </p>
*
* This service takes dependency on an internal policy which converts Azure token credentials into Azure Container Registry specific service credentials.
* In case you use your own pipeline you will have to create your own credential policy.<br>
*
* {For more information please see <a href="https://github.com/Azure/acr/blob/main/docs/AAD-OAuth.md"> Azure Container Registry Authentication </a> }.
*
* @param httpPipeline {@link HttpPipeline} to use for sending service requests and receiving responses.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
@Override
public ContainerRegistryClientBuilder pipeline(HttpPipeline httpPipeline) {
if (this.httpPipeline != null && httpPipeline == null) {
logger.info("HttpPipeline is being set to 'null' when it was previously configured.");
}
this.httpPipeline = httpPipeline;
return this;
}
/**
* Sets the {@link ContainerRegistryServiceVersion} that is used when making API requests.
* <p>
* If a service version is not provided, the service version that will be used will be the latest known service version and so
* newer version of the client library may result in moving to a newer service version.
*
* @param version {@link ContainerRegistryServiceVersion} of the service to be used when making requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
public ContainerRegistryClientBuilder serviceVersion(ContainerRegistryServiceVersion version) {
this.version = version;
return this;
}
/**
* Sets the {@link HttpClient} to use for sending and receiving requests to and from the service.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param httpClient The {@link HttpClient} to use for requests.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
@Override
public ContainerRegistryClientBuilder httpClient(HttpClient httpClient) {
if (this.httpClient != null && httpClient == null) {
logger.info("HttpClient is being set to 'null' when it was previously configured.");
}
this.httpClient = httpClient;
return this;
}
/**
* Allows for setting common properties such as application ID, headers, proxy configuration, etc. Note that it is
* recommended that this method be called with an instance of the {@link HttpClientOptions}
* class (a subclass of the {@link ClientOptions} base class). The HttpClientOptions subclass provides more
* configuration options suitable for HTTP clients, which is applicable for any class that implements this HttpTrait
* interface.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param clientOptions A configured instance of {@link HttpClientOptions}.
*
* @return the updated {@link ContainerRegistryClientBuilder} object
* @see HttpClientOptions
*/
@Override
public ContainerRegistryClientBuilder clientOptions(ClientOptions clientOptions) {
this.clientOptions = clientOptions;
return this;
}
/**
* Sets the configuration store that is used during construction of the service client.
*
* <p>The default configuration store is a clone of the {@link Configuration#getGlobalConfiguration() global
* configuration store}, use {@link Configuration#NONE} to bypass using configuration settings during construction.</p>
*
* @param configuration The configuration store to be used.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
@Override
public ContainerRegistryClientBuilder configuration(Configuration configuration) {
this.configuration = configuration;
return this;
}
/**
* Sets the {@link HttpLogOptions logging configuration} to use when sending and receiving requests to and from
* the service. If a {@code logLevel} is not provided, default value of {@link HttpLogDetailLevel#NONE} is set.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param httpLogOptions The {@link HttpLogOptions logging configuration} to use when sending and receiving requests
* to and from the service.
* @return The updated {@link ContainerRegistryClientBuilder} object.
*/
@Override
public ContainerRegistryClientBuilder httpLogOptions(HttpLogOptions httpLogOptions) {
this.httpLogOptions = httpLogOptions;
return this;
}
/**
* Sets the {@link HttpPipelinePolicy} that is used to retry requests.
* <p>
* The default retry policy will be used if not provided {@link #buildAsyncClient()} to
* build {@link ContainerRegistryClient} or {@link ContainerRegistryAsyncClient}.
* <p>
* Setting this is mutually exclusive with using {@link #retryOptions(RetryOptions)}.
*
* @param retryPolicy The {@link HttpPipelinePolicy} that will be used to retry requests. For example,
* {@link RetryPolicy} can be used to retry requests.
*
* @return The updated ContainerRegistryClientBuilder object.
*/
public ContainerRegistryClientBuilder retryPolicy(RetryPolicy retryPolicy) {
this.retryPolicy = retryPolicy;
return this;
}
/**
* Sets the {@link RetryOptions} for all the requests made through the client.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
* <p>
* Setting this is mutually exclusive with using {@link #retryPolicy(RetryPolicy)}.
*
* @param retryOptions The {@link RetryOptions} to use for all the requests made through the client.
*
* @return The updated ContainerRegistryClientBuilder object.
*/
@Override
public ContainerRegistryClientBuilder retryOptions(RetryOptions retryOptions) {
this.retryOptions = retryOptions;
return this;
}
/**
* Adds a {@link HttpPipelinePolicy pipeline policy} to apply on each request sent.
*
* <p><strong>Note:</strong> It is important to understand the precedence order of the HttpTrait APIs. In
* particular, if a {@link HttpPipeline} is specified, this takes precedence over all other APIs in the trait, and
* they will be ignored. If no {@link HttpPipeline} is specified, a HTTP pipeline will be constructed internally
* based on the settings provided to this trait. Additionally, there may be other APIs in types that implement this
* trait that are also ignored if an {@link HttpPipeline} is specified, so please be sure to refer to the
* documentation of types that implement this trait to understand the full set of implications.</p>
*
* @param policy A {@link HttpPipelinePolicy pipeline policy}.
* @return The updated ContainerRegistryClientBuilder object.
* @throws NullPointerException If {@code policy} is null.
*/
@Override
public ContainerRegistryClientBuilder addPolicy(HttpPipelinePolicy policy) {
Objects.requireNonNull(policy, "'policy' cannot be null.");
if (policy.getPipelinePosition() == HttpPipelinePosition.PER_CALL) {
perCallPolicies.add(policy);
} else {
perRetryPolicies.add(policy);
}
return this;
}
/**
* Creates a {@link ContainerRegistryAsyncClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ContainerRegistryAsyncClient} is created.
* <p>
* If {@link #pipeline(HttpPipeline)} pipeline} is set, then the {@code pipeline} and {@link #endpoint(String) endpoint}
* are used to create the {@link ContainerRegistryAsyncClient client}. All other builder settings are ignored.
*
* @return A {@link ContainerRegistryAsyncClient} with the options set from the builder.
* @throws NullPointerException If {@code endpoint} is null.
* You can set the values by calling {@link #endpoint(String)} and {@link #audience(ContainerRegistryAudience)} respectively.
* @throws IllegalStateException If both {@link #retryOptions(RetryOptions)}
* and {@link #retryPolicy(RetryPolicy)} have been set.
*/
public ContainerRegistryAsyncClient buildAsyncClient() {
Objects.requireNonNull(endpoint, "'endpoint' can't be null");
// Service version
ContainerRegistryServiceVersion serviceVersion = (version != null)
? version
: ContainerRegistryServiceVersion.getLatest();
HttpPipeline pipeline = getHttpPipeline();
ContainerRegistryAsyncClient client = new ContainerRegistryAsyncClient(pipeline, endpoint, serviceVersion.getVersion());
return client;
}
private HttpPipeline getHttpPipeline() {
if (httpPipeline != null) {
return httpPipeline;
}
return UtilsImpl.buildHttpPipeline(
this.clientOptions,
this.httpLogOptions,
this.configuration,
this.retryPolicy,
this.retryOptions,
this.credential,
this.audience,
this.perCallPolicies,
this.perRetryPolicies,
this.httpClient,
this.endpoint,
this.version,
this.logger);
}
/**
* Creates a {@link ContainerRegistryClient} based on options set in the Builder. Every time {@code
* buildAsyncClient()} is called a new instance of {@link ContainerRegistryClient} is created.
* <p>
* If {@link #pipeline(HttpPipeline)} pipeline} is set, then the {@code pipeline}
* and {@link #endpoint(String) endpoint} are used to create the {@link ContainerRegistryClient client}.
* All other builder settings are ignored.
*
* @return A {@link ContainerRegistryClient} with the options set from the builder.
* @throws NullPointerException If {@code endpoint} has not been set. You can set it by calling {@link #endpoint(String)}.
* @throws NullPointerException If {@code audience} has not been set. You can set it by calling {@link #audience(ContainerRegistryAudience)}.
* @throws IllegalStateException If both {@link #retryOptions(RetryOptions)}
* and {@link #retryPolicy(RetryPolicy)} have been set.
*/
public ContainerRegistryClient buildClient() {
return new ContainerRegistryClient(buildAsyncClient());
}
}
| |
package hook;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* The master class of the hook architecture
*
* @author AJ Granowski
*
*/
public class Hook {
private static HashMap<Class, HashMap<String, Event>> eventHookTable = new HashMap<Class, HashMap<String, Event>>();
/**
* Enables hooking in an object. Hooks are declared my implementing
* interfaces that extend the interface hook
*
* @param hookedObject The object to be hooked. Must implement some sort of
* hook
*/
public static void add(final Event hookedObject) {
add(hookedObject.toString(), hookedObject);
}
/**
* Enables hooking in an object. Hooks are declared my implementing
* interfaces that extend the interface hook
*
* @param hookName What this hook will be called for debugging purposes
* and overwriting. If you make two hooks with the same
* uniqueName, the first will be overwritten
* @param hookedObject The object to be hooked. Must implement some sort of
* hook.
*/
public static void add(final String hookName, final Event hookedObject) {
final List<Class> interfaces = findAllInterfaces(hookedObject.getClass());
for (final Class implementedInterface : interfaces) {
// Is this interface a Hook?
if (Event.class.isAssignableFrom(implementedInterface) && !implementedInterface.equals(Event.class)) {
// If the HashMap is empty, we need to initialize it to prevent NullPointers
if (eventHookTable.get(implementedInterface) == null) {
eventHookTable.put(implementedInterface, new HashMap<String, Event>());
}
eventHookTable.get(implementedInterface).put(hookName, hookedObject);
}
}
}
/**
* Calls all the hooked objects using the specified hook
*
* @param hookName The name of the hook to be called. "RunOnTick" will run
* all methods listed the RunOnTick and Hook interfaces
* @return A list of objects returned from the called objects.
*/
public static Object call(final Class event, final Object... args) {
final HashMap<String, Event> hookMap = eventHookTable.get(event);
// The hook does not exist
if (hookMap == null) {
return null;
}
for (final String hookId : hookMap.keySet()) {
final Event hook = hookMap.get(hookId);
// Loop through all of the methods to be executed (all methods specified in the interface and superinterfaces)
for (final Method hookMethod : event.getMethods()) {
Object[] trimmedArgs = new Object[hookMethod.getParameterCount()];
for(int i = 0; i < Math.min(trimmedArgs.length, args.length); i++) {
trimmedArgs[i] = args[i];
}
try {
// Run the method
final Object methodReturn = hookMethod.invoke(hook, trimmedArgs);
if (!isNullLike(methodReturn)) {
return methodReturn;
}
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
// You messed up
System.out.println("ERROR CALLING HOOK. HOOK:(" + event.getSimpleName() + "), ID:(" + hookId + ")");
e.printStackTrace();
}
}
}
return null;
}
/**
* Find all of the interfaces used by a class and its super classes
*
* @param inputClass
* @return A list of classes representing interfaces
*/
private static List<Class> findAllInterfaces(final Class inputClass) {
final ArrayList<Class> interfaces = new ArrayList<Class>();
Class currentClass = inputClass;
// Loop through all of the superclasses of this class
while (currentClass != null) {
interfaces.addAll(recursiveInterfaceFlatten(currentClass));
currentClass = currentClass.getSuperclass();
}
return interfaces;
}
/**
* @return A copy of all hooked objects
*/
public static HashMap<Class, HashMap<String, Event>> getTable() {
return eventHookTable;
}
/**
* Expand the interfaces used by a class
*
* @param interfaceClass
* @return
*/
private static List<Class> recursiveInterfaceFlatten(
final Class interfaceClass) {
final ArrayList<Class> returnList = new ArrayList<Class>();
for (final Class implementedInterface : interfaceClass.getInterfaces()) {
returnList.add(implementedInterface);
returnList.addAll(recursiveInterfaceFlatten(implementedInterface));
}
return returnList;
}
/**
* Find whether an object is "null like". (false, 0, "")
*
* @param object
* @return
*/
private static boolean isNullLike(Object object) {
if (object instanceof Byte) {
return ((byte) object) == 0;
}
if (object instanceof Short) {
return ((short) object) == 0;
}
if (object instanceof Integer) {
return ((int) object) == 0;
}
if (object instanceof Long) {
return ((long) object) == 0;
}
if (object instanceof Float) {
return ((float) object) == 0;
}
if (object instanceof Double) {
return ((double) object) == 0;
}
if (object instanceof Boolean) {
return ((boolean) object) == false;
}
if (object instanceof Character) {
return ((char) object) == '\u0000';
}
if (object instanceof String) {
return ((String) object).equals("");
}
return object == null;
}
/**
* Removes an object from the hooking system
*
* @param hookedObject
*/
public static void remove(final Event hookedObject) {
for (final Class hookInterface : eventHookTable.keySet()) {
final HashMap<String, Event> hookGroup = eventHookTable.get(hookInterface);
for (final String hookId : hookGroup.keySet()) {
if (hookedObject.equals(hookGroup.get(hookId))) {
hookGroup.remove(hookId);
}
}
}
}
/**
* Removes an ENTIRE hook
*
* @param event The hook to be removed
*/
public static void remove(final Class event) {
eventHookTable.remove(event);
}
/**
*
* Removes an object from the hooking system based off of unique identifiers
*
* @param event The hook to be removing from
* @param hookName The unique ID of the specific object to be removed
*/
public static void remove(final Class event, final String hookName) {
eventHookTable.get(event).remove(hookName);
}
}
| |
/*
* 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/ecl1.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.kra.iacuc.protocol;
import org.kuali.kra.iacuc.IacucProtocol;
import org.kuali.kra.iacuc.IacucProtocolDocument;
import org.kuali.kra.iacuc.IacucProtocolForm;
import org.kuali.kra.iacuc.actions.IacucProtocolAction;
import org.kuali.kra.iacuc.actions.IacucProtocolActionType;
import org.kuali.kra.iacuc.auth.IacucProtocolTask;
import org.kuali.kra.iacuc.personnel.IacucProtocolPerson;
import org.kuali.kra.iacuc.personnel.IacucProtocolPersonnelService;
import org.kuali.kra.iacuc.personnel.IacucProtocolUnit;
import org.kuali.kra.iacuc.protocol.funding.IacucProtocolFundingSource;
import org.kuali.kra.iacuc.protocol.funding.IacucProtocolFundingSourceService;
import org.kuali.kra.iacuc.protocol.location.IacucProtocolLocation;
import org.kuali.kra.infrastructure.Constants;
import org.kuali.kra.infrastructure.KraServiceLocator;
import org.kuali.kra.infrastructure.TaskName;
import org.kuali.kra.protocol.ProtocolBase;
import org.kuali.kra.protocol.ProtocolDocumentBase;
import org.kuali.kra.protocol.actions.ProtocolActionBase;
import org.kuali.kra.protocol.auth.ProtocolTaskBase;
import org.kuali.kra.protocol.protocol.ProtocolHelperBase;
import org.kuali.kra.protocol.protocol.funding.ProtocolFundingSourceBase;
import org.kuali.kra.protocol.protocol.funding.ProtocolFundingSourceService;
import org.kuali.kra.protocol.protocol.location.ProtocolLocationBase;
import org.kuali.rice.kew.api.exception.WorkflowException;
public class IacucProtocolHelper extends ProtocolHelperBase {
private static final long serialVersionUID = -71094343536405026L;
public IacucProtocolHelper(IacucProtocolForm form) {
super(form);
}
@Override
// implementation of hook method
protected IacucProtocolPersonnelService getProtocolPersonnelService() {
return KraServiceLocator.getService(IacucProtocolPersonnelService.class);
}
@Override
// implementation of hook method
protected IacucProtocolNumberService getProtocolNumberService() {
return KraServiceLocator.getService(IacucProtocolNumberService.class);
}
@Override
// implementation of hook method
protected IacucProtocolUnit createNewProtocolUnitInstanceHook() {
return new IacucProtocolUnit();
}
@Override
// implementation of hook method
protected IacucProtocolPerson createNewProtocolPersonInstanceHook() {
return new IacucProtocolPerson();
}
@Override
protected Class<? extends ProtocolDocumentBase> getProtocolDocumentClassHook() {
return IacucProtocolDocument.class;
}
@Override
protected ProtocolTaskBase getNewInstanceModifyProtocolGeneralInfoTaskHook(ProtocolBase protocol) {
return new IacucProtocolTask(TaskName.MODIFY_IACUC_PROTOCOL_GENERAL_INFO, (IacucProtocol)protocol);
}
@Override
protected ProtocolTaskBase getNewInstanceModifyProtocolResearchAreasTaskHook(ProtocolBase protocol) {
return new IacucProtocolTask(TaskName.MODIFY_IACUC_PROTOCOL_RESEARCH_AREAS, (IacucProtocol)protocol);
}
@Override
protected ProtocolTaskBase getNewInstanceModifyProtocolTaskHook(ProtocolBase protocol) {
return new IacucProtocolTask(TaskName.MODIFY_IACUC_PROTOCOL, (IacucProtocol) protocol);
}
@Override
protected ProtocolTaskBase getNewInstanceModifyProtocolReferencesTaskHook(ProtocolBase protocol) {
return new IacucProtocolTask(TaskName.MODIFY_IACUC_PROTOCOL_REFERENCES, (IacucProtocol) protocol);
}
@Override
protected ProtocolTaskBase getNewInstanceModifyProtocolOrganizationsTaskHook(ProtocolBase protocol) {
return new IacucProtocolTask(TaskName.MODIFY_IACUC_PROTOCOL_ORGANIZATIONS, (IacucProtocol) protocol);
}
@Override
protected ProtocolTaskBase getNewInstanceCreateProposalDevelopmentTaskHook(ProtocolBase protocol)
{
return new IacucProtocolTask(IacucProtocolTask.CREATE_PROPOSAL_FOR_IACUC_PROTOCOL, (IacucProtocol) protocol);
}
@Override
protected boolean getProtocolProposalDevelopmentLinkingHook()
{
return getParameterService().getParameterValueAsBoolean(Constants.MODULE_NAMESPACE_IACUC,
Constants.PARAMETER_COMPONENT_DOCUMENT, Constants.IACUC_PROTOCOL_PROPOSAL_DEVELOPMENT_LINKING_ENABLED_PARAMETER);
}
protected ProtocolActionBase createProtocolCreatedTypeProtocolActionInstanceHook(ProtocolBase protocol) {
return new IacucProtocolAction((IacucProtocol) protocol, null, IacucProtocolActionType.IACUC_PROTOCOL_CREATED);
}
@Override
protected ProtocolLocationBase getNewProtocolLocationInstanceHook() {
return new IacucProtocolLocation();
}
@Override
protected String getReferenceID1ParameterNameHook() {
return Constants.PARAMETER_MODULE_IACUC_PROTOCOL_REFERENCEID1;
}
@Override
protected String getReferenceID2ParameterNameHook() {
return Constants.PARAMETER_MODULE_IACUC_PROTOCOL_REFERENCEID2;
}
@Override
protected ProtocolTaskBase getNewInstanceModifyProtocolFundingSourceTaskHook(ProtocolBase protocol) {
return new IacucProtocolTask(TaskName.MODIFY_IACUC_PROTOCOL_FUNDING_SOURCE, (IacucProtocol) protocol);
}
@Override
protected ProtocolFundingSourceBase getNewProtocolFundingSourceInstanceHook() {
return new IacucProtocolFundingSource();
}
@Override
protected Class<? extends ProtocolFundingSourceService> getProtocolFundingSourceServiceClassHook() {
return IacucProtocolFundingSourceService.class;
}
@Override
public ProtocolTaskBase getNewInstanceModifyProtocolBillableTaskNewHook(ProtocolBase protocol) {
return new IacucProtocolTask(getModifyProtocolBillableTask(), (IacucProtocol) protocol);
}
public String getModifyProtocolBillableTask() {
return TaskName.MODIFY_IACUC_PROTOCOL_BILLABLE;
}
@Override
protected String getBillableParameterHook() {
return Constants.PARAMETER_MODULE_IACUC_PROTOCOL_BILLABLE;
}
@Override
public void prepareView() {
super.prepareView();
}
/**
* This method initializes permission related to form.
* Note: Billable permission is only set if displayBillable is true.
* Reason: For Institution who does not bill.
* @param protocol
*/
@Override
protected void initializePermissions(ProtocolBase protocol) {
super.initializePermissions((IacucProtocol) protocol);
}
@Override
public void syncSpecialReviewsWithFundingSources() throws WorkflowException {
getDeletedProtocolFundingSources().clear();
}
}
| |
/*
* 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/contactcenterinsights/v1/resources.proto
package com.google.cloud.contactcenterinsights.v1;
/**
*
*
* <pre>
* Agent Assist Article Suggestion data.
* </pre>
*
* Protobuf type {@code google.cloud.contactcenterinsights.v1.ArticleSuggestionData}
*/
public final class ArticleSuggestionData extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.contactcenterinsights.v1.ArticleSuggestionData)
ArticleSuggestionDataOrBuilder {
private static final long serialVersionUID = 0L;
// Use ArticleSuggestionData.newBuilder() to construct.
private ArticleSuggestionData(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ArticleSuggestionData() {
title_ = "";
uri_ = "";
queryRecord_ = "";
source_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ArticleSuggestionData();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private ArticleSuggestionData(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
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 10:
{
java.lang.String s = input.readStringRequireUtf8();
title_ = s;
break;
}
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
uri_ = s;
break;
}
case 29:
{
confidenceScore_ = input.readFloat();
break;
}
case 34:
{
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
metadata_ =
com.google.protobuf.MapField.newMapField(
MetadataDefaultEntryHolder.defaultEntry);
mutable_bitField0_ |= 0x00000001;
}
com.google.protobuf.MapEntry<java.lang.String, java.lang.String> metadata__ =
input.readMessage(
MetadataDefaultEntryHolder.defaultEntry.getParserForType(),
extensionRegistry);
metadata_.getMutableMap().put(metadata__.getKey(), metadata__.getValue());
break;
}
case 42:
{
java.lang.String s = input.readStringRequireUtf8();
queryRecord_ = s;
break;
}
case 50:
{
java.lang.String s = input.readStringRequireUtf8();
source_ = s;
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.contactcenterinsights.v1.ResourcesProto
.internal_static_google_cloud_contactcenterinsights_v1_ArticleSuggestionData_descriptor;
}
@SuppressWarnings({"rawtypes"})
@java.lang.Override
protected com.google.protobuf.MapField internalGetMapField(int number) {
switch (number) {
case 4:
return internalGetMetadata();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.contactcenterinsights.v1.ResourcesProto
.internal_static_google_cloud_contactcenterinsights_v1_ArticleSuggestionData_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData.class,
com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData.Builder.class);
}
public static final int TITLE_FIELD_NUMBER = 1;
private volatile java.lang.Object title_;
/**
*
*
* <pre>
* Article title.
* </pre>
*
* <code>string title = 1;</code>
*
* @return The title.
*/
@java.lang.Override
public java.lang.String getTitle() {
java.lang.Object ref = title_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
title_ = s;
return s;
}
}
/**
*
*
* <pre>
* Article title.
* </pre>
*
* <code>string title = 1;</code>
*
* @return The bytes for title.
*/
@java.lang.Override
public com.google.protobuf.ByteString getTitleBytes() {
java.lang.Object ref = title_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
title_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int URI_FIELD_NUMBER = 2;
private volatile java.lang.Object uri_;
/**
*
*
* <pre>
* Article URI.
* </pre>
*
* <code>string uri = 2;</code>
*
* @return The uri.
*/
@java.lang.Override
public java.lang.String getUri() {
java.lang.Object ref = uri_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
uri_ = s;
return s;
}
}
/**
*
*
* <pre>
* Article URI.
* </pre>
*
* <code>string uri = 2;</code>
*
* @return The bytes for uri.
*/
@java.lang.Override
public com.google.protobuf.ByteString getUriBytes() {
java.lang.Object ref = uri_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
uri_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int CONFIDENCE_SCORE_FIELD_NUMBER = 3;
private float confidenceScore_;
/**
*
*
* <pre>
* The system's confidence score that this article is a good match for this
* conversation, ranging from 0.0 (completely uncertain) to 1.0 (completely
* certain).
* </pre>
*
* <code>float confidence_score = 3;</code>
*
* @return The confidenceScore.
*/
@java.lang.Override
public float getConfidenceScore() {
return confidenceScore_;
}
public static final int METADATA_FIELD_NUMBER = 4;
private static final class MetadataDefaultEntryHolder {
static final com.google.protobuf.MapEntry<java.lang.String, java.lang.String> defaultEntry =
com.google.protobuf.MapEntry.<java.lang.String, java.lang.String>newDefaultInstance(
com.google.cloud.contactcenterinsights.v1.ResourcesProto
.internal_static_google_cloud_contactcenterinsights_v1_ArticleSuggestionData_MetadataEntry_descriptor,
com.google.protobuf.WireFormat.FieldType.STRING,
"",
com.google.protobuf.WireFormat.FieldType.STRING,
"");
}
private com.google.protobuf.MapField<java.lang.String, java.lang.String> metadata_;
private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetMetadata() {
if (metadata_ == null) {
return com.google.protobuf.MapField.emptyMapField(MetadataDefaultEntryHolder.defaultEntry);
}
return metadata_;
}
public int getMetadataCount() {
return internalGetMetadata().getMap().size();
}
/**
*
*
* <pre>
* Map that contains metadata about the Article Suggestion and the document
* that it originates from.
* </pre>
*
* <code>map<string, string> metadata = 4;</code>
*/
@java.lang.Override
public boolean containsMetadata(java.lang.String key) {
if (key == null) {
throw new java.lang.NullPointerException();
}
return internalGetMetadata().getMap().containsKey(key);
}
/** Use {@link #getMetadataMap()} instead. */
@java.lang.Override
@java.lang.Deprecated
public java.util.Map<java.lang.String, java.lang.String> getMetadata() {
return getMetadataMap();
}
/**
*
*
* <pre>
* Map that contains metadata about the Article Suggestion and the document
* that it originates from.
* </pre>
*
* <code>map<string, string> metadata = 4;</code>
*/
@java.lang.Override
public java.util.Map<java.lang.String, java.lang.String> getMetadataMap() {
return internalGetMetadata().getMap();
}
/**
*
*
* <pre>
* Map that contains metadata about the Article Suggestion and the document
* that it originates from.
* </pre>
*
* <code>map<string, string> metadata = 4;</code>
*/
@java.lang.Override
public java.lang.String getMetadataOrDefault(
java.lang.String key, java.lang.String defaultValue) {
if (key == null) {
throw new java.lang.NullPointerException();
}
java.util.Map<java.lang.String, java.lang.String> map = internalGetMetadata().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
*
*
* <pre>
* Map that contains metadata about the Article Suggestion and the document
* that it originates from.
* </pre>
*
* <code>map<string, string> metadata = 4;</code>
*/
@java.lang.Override
public java.lang.String getMetadataOrThrow(java.lang.String key) {
if (key == null) {
throw new java.lang.NullPointerException();
}
java.util.Map<java.lang.String, java.lang.String> map = internalGetMetadata().getMap();
if (!map.containsKey(key)) {
throw new java.lang.IllegalArgumentException();
}
return map.get(key);
}
public static final int QUERY_RECORD_FIELD_NUMBER = 5;
private volatile java.lang.Object queryRecord_;
/**
*
*
* <pre>
* Name of the query record.
* Format:
* projects/{project}/locations/{location}/queryRecords/{query_record}
* </pre>
*
* <code>string query_record = 5;</code>
*
* @return The queryRecord.
*/
@java.lang.Override
public java.lang.String getQueryRecord() {
java.lang.Object ref = queryRecord_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
queryRecord_ = s;
return s;
}
}
/**
*
*
* <pre>
* Name of the query record.
* Format:
* projects/{project}/locations/{location}/queryRecords/{query_record}
* </pre>
*
* <code>string query_record = 5;</code>
*
* @return The bytes for queryRecord.
*/
@java.lang.Override
public com.google.protobuf.ByteString getQueryRecordBytes() {
java.lang.Object ref = queryRecord_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
queryRecord_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int SOURCE_FIELD_NUMBER = 6;
private volatile java.lang.Object source_;
/**
*
*
* <pre>
* The knowledge document that this answer was extracted from.
* Format:
* projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}
* </pre>
*
* <code>string source = 6;</code>
*
* @return The source.
*/
@java.lang.Override
public java.lang.String getSource() {
java.lang.Object ref = source_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
source_ = s;
return s;
}
}
/**
*
*
* <pre>
* The knowledge document that this answer was extracted from.
* Format:
* projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}
* </pre>
*
* <code>string source = 6;</code>
*
* @return The bytes for source.
*/
@java.lang.Override
public com.google.protobuf.ByteString getSourceBytes() {
java.lang.Object ref = source_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
source_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
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 (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(title_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, title_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(uri_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, uri_);
}
if (confidenceScore_ != 0F) {
output.writeFloat(3, confidenceScore_);
}
com.google.protobuf.GeneratedMessageV3.serializeStringMapTo(
output, internalGetMetadata(), MetadataDefaultEntryHolder.defaultEntry, 4);
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(queryRecord_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, queryRecord_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(source_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 6, source_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(title_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, title_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(uri_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, uri_);
}
if (confidenceScore_ != 0F) {
size += com.google.protobuf.CodedOutputStream.computeFloatSize(3, confidenceScore_);
}
for (java.util.Map.Entry<java.lang.String, java.lang.String> entry :
internalGetMetadata().getMap().entrySet()) {
com.google.protobuf.MapEntry<java.lang.String, java.lang.String> metadata__ =
MetadataDefaultEntryHolder.defaultEntry
.newBuilderForType()
.setKey(entry.getKey())
.setValue(entry.getValue())
.build();
size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, metadata__);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(queryRecord_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, queryRecord_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(source_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, source_);
}
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.contactcenterinsights.v1.ArticleSuggestionData)) {
return super.equals(obj);
}
com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData other =
(com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData) obj;
if (!getTitle().equals(other.getTitle())) return false;
if (!getUri().equals(other.getUri())) return false;
if (java.lang.Float.floatToIntBits(getConfidenceScore())
!= java.lang.Float.floatToIntBits(other.getConfidenceScore())) return false;
if (!internalGetMetadata().equals(other.internalGetMetadata())) return false;
if (!getQueryRecord().equals(other.getQueryRecord())) return false;
if (!getSource().equals(other.getSource())) 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) + TITLE_FIELD_NUMBER;
hash = (53 * hash) + getTitle().hashCode();
hash = (37 * hash) + URI_FIELD_NUMBER;
hash = (53 * hash) + getUri().hashCode();
hash = (37 * hash) + CONFIDENCE_SCORE_FIELD_NUMBER;
hash = (53 * hash) + java.lang.Float.floatToIntBits(getConfidenceScore());
if (!internalGetMetadata().getMap().isEmpty()) {
hash = (37 * hash) + METADATA_FIELD_NUMBER;
hash = (53 * hash) + internalGetMetadata().hashCode();
}
hash = (37 * hash) + QUERY_RECORD_FIELD_NUMBER;
hash = (53 * hash) + getQueryRecord().hashCode();
hash = (37 * hash) + SOURCE_FIELD_NUMBER;
hash = (53 * hash) + getSource().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData 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.contactcenterinsights.v1.ArticleSuggestionData parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData 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.contactcenterinsights.v1.ArticleSuggestionData parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData 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.contactcenterinsights.v1.ArticleSuggestionData parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData 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.contactcenterinsights.v1.ArticleSuggestionData parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData 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.contactcenterinsights.v1.ArticleSuggestionData 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>
* Agent Assist Article Suggestion data.
* </pre>
*
* Protobuf type {@code google.cloud.contactcenterinsights.v1.ArticleSuggestionData}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.contactcenterinsights.v1.ArticleSuggestionData)
com.google.cloud.contactcenterinsights.v1.ArticleSuggestionDataOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.contactcenterinsights.v1.ResourcesProto
.internal_static_google_cloud_contactcenterinsights_v1_ArticleSuggestionData_descriptor;
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapField internalGetMapField(int number) {
switch (number) {
case 4:
return internalGetMetadata();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapField internalGetMutableMapField(int number) {
switch (number) {
case 4:
return internalGetMutableMetadata();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.contactcenterinsights.v1.ResourcesProto
.internal_static_google_cloud_contactcenterinsights_v1_ArticleSuggestionData_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData.class,
com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData.Builder.class);
}
// Construct using com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData.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();
title_ = "";
uri_ = "";
confidenceScore_ = 0F;
internalGetMutableMetadata().clear();
queryRecord_ = "";
source_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.contactcenterinsights.v1.ResourcesProto
.internal_static_google_cloud_contactcenterinsights_v1_ArticleSuggestionData_descriptor;
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData
getDefaultInstanceForType() {
return com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData build() {
com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData buildPartial() {
com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData result =
new com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData(this);
int from_bitField0_ = bitField0_;
result.title_ = title_;
result.uri_ = uri_;
result.confidenceScore_ = confidenceScore_;
result.metadata_ = internalGetMetadata();
result.metadata_.makeImmutable();
result.queryRecord_ = queryRecord_;
result.source_ = source_;
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.contactcenterinsights.v1.ArticleSuggestionData) {
return mergeFrom((com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData other) {
if (other
== com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData.getDefaultInstance())
return this;
if (!other.getTitle().isEmpty()) {
title_ = other.title_;
onChanged();
}
if (!other.getUri().isEmpty()) {
uri_ = other.uri_;
onChanged();
}
if (other.getConfidenceScore() != 0F) {
setConfidenceScore(other.getConfidenceScore());
}
internalGetMutableMetadata().mergeFrom(other.internalGetMetadata());
if (!other.getQueryRecord().isEmpty()) {
queryRecord_ = other.queryRecord_;
onChanged();
}
if (!other.getSource().isEmpty()) {
source_ = other.source_;
onChanged();
}
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.contactcenterinsights.v1.ArticleSuggestionData parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData)
e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.lang.Object title_ = "";
/**
*
*
* <pre>
* Article title.
* </pre>
*
* <code>string title = 1;</code>
*
* @return The title.
*/
public java.lang.String getTitle() {
java.lang.Object ref = title_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
title_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Article title.
* </pre>
*
* <code>string title = 1;</code>
*
* @return The bytes for title.
*/
public com.google.protobuf.ByteString getTitleBytes() {
java.lang.Object ref = title_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
title_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Article title.
* </pre>
*
* <code>string title = 1;</code>
*
* @param value The title to set.
* @return This builder for chaining.
*/
public Builder setTitle(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
title_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Article title.
* </pre>
*
* <code>string title = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearTitle() {
title_ = getDefaultInstance().getTitle();
onChanged();
return this;
}
/**
*
*
* <pre>
* Article title.
* </pre>
*
* <code>string title = 1;</code>
*
* @param value The bytes for title to set.
* @return This builder for chaining.
*/
public Builder setTitleBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
title_ = value;
onChanged();
return this;
}
private java.lang.Object uri_ = "";
/**
*
*
* <pre>
* Article URI.
* </pre>
*
* <code>string uri = 2;</code>
*
* @return The uri.
*/
public java.lang.String getUri() {
java.lang.Object ref = uri_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
uri_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Article URI.
* </pre>
*
* <code>string uri = 2;</code>
*
* @return The bytes for uri.
*/
public com.google.protobuf.ByteString getUriBytes() {
java.lang.Object ref = uri_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
uri_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Article URI.
* </pre>
*
* <code>string uri = 2;</code>
*
* @param value The uri to set.
* @return This builder for chaining.
*/
public Builder setUri(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
uri_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Article URI.
* </pre>
*
* <code>string uri = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearUri() {
uri_ = getDefaultInstance().getUri();
onChanged();
return this;
}
/**
*
*
* <pre>
* Article URI.
* </pre>
*
* <code>string uri = 2;</code>
*
* @param value The bytes for uri to set.
* @return This builder for chaining.
*/
public Builder setUriBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
uri_ = value;
onChanged();
return this;
}
private float confidenceScore_;
/**
*
*
* <pre>
* The system's confidence score that this article is a good match for this
* conversation, ranging from 0.0 (completely uncertain) to 1.0 (completely
* certain).
* </pre>
*
* <code>float confidence_score = 3;</code>
*
* @return The confidenceScore.
*/
@java.lang.Override
public float getConfidenceScore() {
return confidenceScore_;
}
/**
*
*
* <pre>
* The system's confidence score that this article is a good match for this
* conversation, ranging from 0.0 (completely uncertain) to 1.0 (completely
* certain).
* </pre>
*
* <code>float confidence_score = 3;</code>
*
* @param value The confidenceScore to set.
* @return This builder for chaining.
*/
public Builder setConfidenceScore(float value) {
confidenceScore_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The system's confidence score that this article is a good match for this
* conversation, ranging from 0.0 (completely uncertain) to 1.0 (completely
* certain).
* </pre>
*
* <code>float confidence_score = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearConfidenceScore() {
confidenceScore_ = 0F;
onChanged();
return this;
}
private com.google.protobuf.MapField<java.lang.String, java.lang.String> metadata_;
private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetMetadata() {
if (metadata_ == null) {
return com.google.protobuf.MapField.emptyMapField(MetadataDefaultEntryHolder.defaultEntry);
}
return metadata_;
}
private com.google.protobuf.MapField<java.lang.String, java.lang.String>
internalGetMutableMetadata() {
onChanged();
;
if (metadata_ == null) {
metadata_ =
com.google.protobuf.MapField.newMapField(MetadataDefaultEntryHolder.defaultEntry);
}
if (!metadata_.isMutable()) {
metadata_ = metadata_.copy();
}
return metadata_;
}
public int getMetadataCount() {
return internalGetMetadata().getMap().size();
}
/**
*
*
* <pre>
* Map that contains metadata about the Article Suggestion and the document
* that it originates from.
* </pre>
*
* <code>map<string, string> metadata = 4;</code>
*/
@java.lang.Override
public boolean containsMetadata(java.lang.String key) {
if (key == null) {
throw new java.lang.NullPointerException();
}
return internalGetMetadata().getMap().containsKey(key);
}
/** Use {@link #getMetadataMap()} instead. */
@java.lang.Override
@java.lang.Deprecated
public java.util.Map<java.lang.String, java.lang.String> getMetadata() {
return getMetadataMap();
}
/**
*
*
* <pre>
* Map that contains metadata about the Article Suggestion and the document
* that it originates from.
* </pre>
*
* <code>map<string, string> metadata = 4;</code>
*/
@java.lang.Override
public java.util.Map<java.lang.String, java.lang.String> getMetadataMap() {
return internalGetMetadata().getMap();
}
/**
*
*
* <pre>
* Map that contains metadata about the Article Suggestion and the document
* that it originates from.
* </pre>
*
* <code>map<string, string> metadata = 4;</code>
*/
@java.lang.Override
public java.lang.String getMetadataOrDefault(
java.lang.String key, java.lang.String defaultValue) {
if (key == null) {
throw new java.lang.NullPointerException();
}
java.util.Map<java.lang.String, java.lang.String> map = internalGetMetadata().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
*
*
* <pre>
* Map that contains metadata about the Article Suggestion and the document
* that it originates from.
* </pre>
*
* <code>map<string, string> metadata = 4;</code>
*/
@java.lang.Override
public java.lang.String getMetadataOrThrow(java.lang.String key) {
if (key == null) {
throw new java.lang.NullPointerException();
}
java.util.Map<java.lang.String, java.lang.String> map = internalGetMetadata().getMap();
if (!map.containsKey(key)) {
throw new java.lang.IllegalArgumentException();
}
return map.get(key);
}
public Builder clearMetadata() {
internalGetMutableMetadata().getMutableMap().clear();
return this;
}
/**
*
*
* <pre>
* Map that contains metadata about the Article Suggestion and the document
* that it originates from.
* </pre>
*
* <code>map<string, string> metadata = 4;</code>
*/
public Builder removeMetadata(java.lang.String key) {
if (key == null) {
throw new java.lang.NullPointerException();
}
internalGetMutableMetadata().getMutableMap().remove(key);
return this;
}
/** Use alternate mutation accessors instead. */
@java.lang.Deprecated
public java.util.Map<java.lang.String, java.lang.String> getMutableMetadata() {
return internalGetMutableMetadata().getMutableMap();
}
/**
*
*
* <pre>
* Map that contains metadata about the Article Suggestion and the document
* that it originates from.
* </pre>
*
* <code>map<string, string> metadata = 4;</code>
*/
public Builder putMetadata(java.lang.String key, java.lang.String value) {
if (key == null) {
throw new java.lang.NullPointerException();
}
if (value == null) {
throw new java.lang.NullPointerException();
}
internalGetMutableMetadata().getMutableMap().put(key, value);
return this;
}
/**
*
*
* <pre>
* Map that contains metadata about the Article Suggestion and the document
* that it originates from.
* </pre>
*
* <code>map<string, string> metadata = 4;</code>
*/
public Builder putAllMetadata(java.util.Map<java.lang.String, java.lang.String> values) {
internalGetMutableMetadata().getMutableMap().putAll(values);
return this;
}
private java.lang.Object queryRecord_ = "";
/**
*
*
* <pre>
* Name of the query record.
* Format:
* projects/{project}/locations/{location}/queryRecords/{query_record}
* </pre>
*
* <code>string query_record = 5;</code>
*
* @return The queryRecord.
*/
public java.lang.String getQueryRecord() {
java.lang.Object ref = queryRecord_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
queryRecord_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Name of the query record.
* Format:
* projects/{project}/locations/{location}/queryRecords/{query_record}
* </pre>
*
* <code>string query_record = 5;</code>
*
* @return The bytes for queryRecord.
*/
public com.google.protobuf.ByteString getQueryRecordBytes() {
java.lang.Object ref = queryRecord_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
queryRecord_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Name of the query record.
* Format:
* projects/{project}/locations/{location}/queryRecords/{query_record}
* </pre>
*
* <code>string query_record = 5;</code>
*
* @param value The queryRecord to set.
* @return This builder for chaining.
*/
public Builder setQueryRecord(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
queryRecord_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the query record.
* Format:
* projects/{project}/locations/{location}/queryRecords/{query_record}
* </pre>
*
* <code>string query_record = 5;</code>
*
* @return This builder for chaining.
*/
public Builder clearQueryRecord() {
queryRecord_ = getDefaultInstance().getQueryRecord();
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the query record.
* Format:
* projects/{project}/locations/{location}/queryRecords/{query_record}
* </pre>
*
* <code>string query_record = 5;</code>
*
* @param value The bytes for queryRecord to set.
* @return This builder for chaining.
*/
public Builder setQueryRecordBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
queryRecord_ = value;
onChanged();
return this;
}
private java.lang.Object source_ = "";
/**
*
*
* <pre>
* The knowledge document that this answer was extracted from.
* Format:
* projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}
* </pre>
*
* <code>string source = 6;</code>
*
* @return The source.
*/
public java.lang.String getSource() {
java.lang.Object ref = source_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
source_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The knowledge document that this answer was extracted from.
* Format:
* projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}
* </pre>
*
* <code>string source = 6;</code>
*
* @return The bytes for source.
*/
public com.google.protobuf.ByteString getSourceBytes() {
java.lang.Object ref = source_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
source_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The knowledge document that this answer was extracted from.
* Format:
* projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}
* </pre>
*
* <code>string source = 6;</code>
*
* @param value The source to set.
* @return This builder for chaining.
*/
public Builder setSource(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
source_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The knowledge document that this answer was extracted from.
* Format:
* projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}
* </pre>
*
* <code>string source = 6;</code>
*
* @return This builder for chaining.
*/
public Builder clearSource() {
source_ = getDefaultInstance().getSource();
onChanged();
return this;
}
/**
*
*
* <pre>
* The knowledge document that this answer was extracted from.
* Format:
* projects/{project}/knowledgeBases/{knowledge_base}/documents/{document}
* </pre>
*
* <code>string source = 6;</code>
*
* @param value The bytes for source to set.
* @return This builder for chaining.
*/
public Builder setSourceBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
source_ = value;
onChanged();
return this;
}
@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.contactcenterinsights.v1.ArticleSuggestionData)
}
// @@protoc_insertion_point(class_scope:google.cloud.contactcenterinsights.v1.ArticleSuggestionData)
private static final com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData();
}
public static com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ArticleSuggestionData> PARSER =
new com.google.protobuf.AbstractParser<ArticleSuggestionData>() {
@java.lang.Override
public ArticleSuggestionData parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ArticleSuggestionData(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ArticleSuggestionData> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ArticleSuggestionData> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.ArticleSuggestionData
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
/*
* Copyright 2003-2005 the original author or authors.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.jdon.jivejdon.service.imp.message;
import java.util.Collection;
import org.apache.log4j.Logger;
import com.jdon.container.visitor.data.SessionContext;
import com.jdon.container.visitor.data.SessionContextAcceptable;
import com.jdon.controller.events.EventModel;
import com.jdon.controller.pool.Poolable;
import com.jdon.jivejdon.Constants;
import com.jdon.jivejdon.auth.NoPermissionException;
import com.jdon.jivejdon.auth.ResourceAuthorization;
import com.jdon.jivejdon.model.ForumMessage;
import com.jdon.jivejdon.model.ForumThread;
import com.jdon.jivejdon.model.message.output.RenderingFilterManager;
import com.jdon.jivejdon.service.ForumMessageService;
import com.jdon.jivejdon.service.UploadService;
import com.jdon.jivejdon.service.util.SessionContextUtil;
import com.jdon.util.UtilValidate;
/**
* ForumMessageShell is the shell of ForumMessage core implementions.
*
* invoking order:
* ForumMessageShell --> MessageContentFilter ---> ForumMessageServiceImp
*
* @author <a href="mailto:banqiao@jdon.com">banq</a>
*
*/
public class ForumMessageShell implements SessionContextAcceptable, Poolable,ForumMessageService {
private final static Logger logger = Logger.getLogger(ForumMessageShell.class);
protected SessionContext sessionContext;
protected SessionContextUtil sessionContextUtil;
protected ResourceAuthorization resourceAuthorization;
protected MessageRenderingFilter messageRenderingFilter;
protected MessageKernel messageKernel;
protected UploadService uploadService;
public ForumMessageShell(SessionContextUtil sessionContextUtil,
ResourceAuthorization messageServiceAuth,
MessageRenderingFilter messageRenderingFilter,
MessageKernel messageKernel,
UploadService uploadService) {
this.sessionContextUtil = sessionContextUtil;
this.resourceAuthorization = messageServiceAuth;
this.messageRenderingFilter = messageRenderingFilter;
this.messageKernel = messageKernel;
this.uploadService = uploadService;
}
/**
* find a Message for modify
*/
public ForumMessage findMessage(Long messageId) {
logger.debug("enter ForumMessageShell's findMessage");
ForumMessage forumMessage = messageKernel.getMessage(messageId);
if (forumMessage == null)
return null;
try {
com.jdon.jivejdon.model.Account account = sessionContextUtil.getLoginAccount(sessionContext);
resourceAuthorization.verifyAuthenticated(forumMessage, account);
} catch (NoPermissionException e) {
logger.error("No Permission to operate it");
} catch (Exception e) {
logger.error(e);
return null;
}
return forumMessage;
}
public boolean isAuthenticated(ForumMessage forumMessage){
boolean authenticated = false;
try {
com.jdon.jivejdon.model.Account account = sessionContextUtil.getLoginAccount(sessionContext);
authenticated = resourceAuthorization.isAuthenticated(forumMessage, account);
} catch (Exception e) { }
return authenticated;
}
/**
* create Topic Message
*/
public void createTopicMessage(EventModel em) throws Exception{
ForumMessage forumMessage = (ForumMessage)em.getModelIF();
try {
Long mIDInt = messageKernel.getNextId(Constants.MESSAGE);
forumMessage.setMessageId(mIDInt);
prepareUpdate(forumMessage);
messageRenderingFilter.createTopicMessage(em);
if (!UtilValidate.isEmpty(forumMessage.getBody())){
messageKernel.createTopicMessage(em);
}
} catch (Exception e) {
logger.error(e);
em.setErrors(Constants.ERRORS);
}
}
/**
* set the login account into the domain model
*/
public void createReplyMessage(EventModel em) throws Exception{
ForumMessage forumMessage = (ForumMessage)em.getModelIF();
try {
Long mIDInt = messageKernel.getNextId(Constants.MESSAGE);
forumMessage.setMessageId(mIDInt);
prepareUpdate(forumMessage);
messageRenderingFilter.createReplyMessage(em);
if(!UtilValidate.isEmpty(forumMessage.getBody())){
messageKernel.createReplyMessage(em);
}
} catch (Exception e) {
logger.error(e);
em.setErrors(Constants.ERRORS);
}
}
private void prepareUpdate(ForumMessage forumMessage) throws Exception{
try {
//the poster
com.jdon.jivejdon.model.Account account = sessionContextUtil.getLoginAccount(sessionContext);
forumMessage.setAccount(account);
//upload
Collection uploads = uploadService.loadNewUploadFiles(this.sessionContext);
forumMessage.setUploadFiles(uploads);
} catch (Exception e) {
logger.error(e);
throw new Exception(e);
}
}
/**
* 1. auth check: amdin and the owner can modify this nessage.
* 2. if the message has childern, only admin can update it.
* before business logic, we must get a true message from persistence layer,
* now the ForumMessage packed in EventModel object is not full, it is
* a DTO from prensentation layer.
*
*
*/
public void updateMessage(EventModel em) throws Exception{
ForumMessage modForumMessage = (ForumMessage)em.getModelIF();
ForumMessage forumMessage = getMessage(modForumMessage.getMessageId());
if (forumMessage == null) return;
try {
com.jdon.jivejdon.model.Account account = sessionContextUtil.getLoginAccount(sessionContext);
resourceAuthorization.verifyAuthenticated(forumMessage, account);
//upload
// modForumMessage.setUploadFiles(loadUploadFiles());
prepareUpdate(modForumMessage);
Collection uploads = uploadService.loadNewUploadFiles(this.sessionContext);
forumMessage.setUploadFiles(uploads);
messageRenderingFilter.updateMessage(em);
messageKernel.updateMessage(em);
} catch (NoPermissionException e) {
em.setErrors(e.getMessage());
} catch (Exception e) {
logger.error(e);
}
}
/**
* delete a message
* the auth is same as to the updateMessage
*
*
*/
public void deleteMessage(EventModel em) throws Exception {
ForumMessage forumMessage = (ForumMessage) em.getModelIF();
forumMessage = getMessage(forumMessage.getMessageId());
if (forumMessage == null)
return;
try {
com.jdon.jivejdon.model.Account account = sessionContextUtil.getLoginAccount(sessionContext);
resourceAuthorization.verifyAuthenticated(forumMessage, account);
messageKernel.deleteMessage(em);
} catch (NoPermissionException e) {
em.setErrors(e.getMessage());
} catch (Exception e) {
logger.error(e);
}
}
/**
* only admin can deletedeleteRecursiveMessage, so we only setup it in jivejdon_permisiion.xml
*/
public void deleteRecursiveMessage(EventModel em) throws Exception{
ForumMessage forumMessage = (ForumMessage)em.getModelIF();
forumMessage = getMessage(forumMessage.getMessageId());
if (forumMessage == null) return;
try {
com.jdon.jivejdon.model.Account account = sessionContextUtil.getLoginAccount(sessionContext);
resourceAuthorization.verifyAuthenticated(forumMessage, account);
messageKernel.deleteRecursiveMessage(em);
} catch (NoPermissionException e) {
em.setErrors(e.getMessage());
} catch (Exception e) {
logger.error(e);
}
}
public void deleteUserMessages(String username) throws Exception {
try {
com.jdon.jivejdon.model.Account account = sessionContextUtil.getLoginAccount(sessionContext);
if (resourceAuthorization.isAdmin(account))
messageKernel.deleteUserMessages(username);
} catch (Exception e) {
logger.error(e);
}
}
public ForumMessage findFilteredMessage(Long messageId) {
return messageRenderingFilter.findFilteredMessage(messageId);
}
public RenderingFilterManager getFilterManager(){
return messageRenderingFilter.getFilterManager();
}
/**
* get the full forum in forumMessage, and return it.
*/
public ForumMessage initMessage(EventModel em) {
return messageKernel.initMessage(em);
}
public ForumMessage initReplyMessage(EventModel em) {
return messageKernel.initReplyMessage(em);
}
/*
* return a full ForumMessage need solve the relations with Forum
* ForumThread parentMessage
*/
public ForumMessage getMessage(Long messageId) {
return messageKernel.getMessage(messageId);
}
public ForumMessage getMessageWithPropterty(Long messageId){
return messageKernel.getMessageWithPropterty(messageId);
}
/**
* return a full ForumThread
* one ForumThread has one rootMessage
* need solve the realtion with Forum rootForumMessage lastPost
*
* @param threadId
* @return
*/
public ForumThread getThread(Long threadId) {
return messageKernel.getThread(threadId);
/**see SpamFilter replace below:
String clientIP = sessionContextUtil.getClientIP(sessionContext);
if (messageRenderingFilter.threadIsFiltered(threadId, clientIP)){
return messageKernel.getThread(threadId);
}else
return null;**/
}
/**
* @return Returns the sessionContext.
*/
public SessionContext getSessionContext() {
return sessionContext;
}
/**
* @param sessionContext The sessionContext to set.
*/
public void setSessionContext(SessionContext sessionContext) {
this.sessionContext = sessionContext;
}
}
| |
/**
* 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.falcon.security;
import org.apache.falcon.cluster.util.EntityBuilderTestUtil;
import org.apache.falcon.entity.store.ConfigurationStore;
import org.apache.falcon.entity.v0.EntityType;
import org.apache.falcon.entity.v0.cluster.Cluster;
import org.apache.falcon.util.FalconTestUtil;
import org.apache.falcon.util.StartupProperties;
import org.apache.hadoop.security.UserGroupInformation;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.HttpMethod;
import java.io.IOException;
/**
* Test for FalconAuthorizationFilter using mock objects.
*/
public class FalconAuthorizationFilterTest {
public static final String CLUSTER_ENTITY_NAME = "primary-cluster";
public static final String PROCESS_ENTITY_NAME = "sample-process";
@Mock
private HttpServletRequest mockRequest;
@Mock
private HttpServletResponse mockResponse;
@Mock
private FilterChain mockChain;
@Mock
private FilterConfig mockConfig;
@Mock
private UserGroupInformation mockUgi;
private ConfigurationStore configStore;
private Cluster clusterEntity;
private org.apache.falcon.entity.v0.process.Process processEntity;
@BeforeClass
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
CurrentUser.authenticate(EntityBuilderTestUtil.USER);
Assert.assertEquals(CurrentUser.getUser(), EntityBuilderTestUtil.USER);
configStore = ConfigurationStore.get();
addClusterEntity();
addProcessEntity();
Assert.assertNotNull(processEntity);
}
@DataProvider(name = "resourceWithNoEntity")
private Object[][] createOptions() {
return new Object[][] {
{"/admin/version"},
{"/entities/list/feed"},
{"/entities/list/process"},
{"/entities/list/cluster"},
{"/metadata/lineage/vertices/all"},
{"/metadata/lineage/vertices/_1"},
{"/metadata/lineage/vertices/properties/_1"},
{"/metadata/discovery/process_entity/sample-process/relations"},
{"/metadata/discovery/process_entity/list?cluster=primary-cluster"},
};
}
@Test (dataProvider = "resourceWithNoEntity")
public void testDoFilter(String resource) throws Exception {
boolean[] enabledFlags = {false, true};
for (boolean enabled : enabledFlags) {
StartupProperties.get().setProperty(
"falcon.security.authorization.enabled", String.valueOf(enabled));
Filter filter = new FalconAuthorizationFilter();
synchronized (StartupProperties.get()) {
filter.init(mockConfig);
}
StringBuffer requestUrl = new StringBuffer("http://localhost" + resource);
Mockito.when(mockRequest.getRequestURL()).thenReturn(requestUrl);
Mockito.when(mockRequest.getRequestURI()).thenReturn("/api" + resource);
Mockito.when(mockRequest.getPathInfo()).thenReturn(resource);
try {
filter.doFilter(mockRequest, mockResponse, mockChain);
} finally {
filter.destroy();
}
}
}
@DataProvider(name = "invalidResource")
private Object[][] createBadOptions() {
return new Object[][] {
{"/admin1/version"},
{"/entities1/list/feed"},
{"/metadata1/lineage/vertices/all"},
{"/foo/bar"},
};
}
@Test (dataProvider = "invalidResource")
public void testDoFilterBadResource(String resource) throws Exception {
boolean[] enabledFlags = {false, true};
for (boolean enabled : enabledFlags) {
StartupProperties.get().setProperty(
"falcon.security.authorization.enabled", String.valueOf(enabled));
Filter filter = new FalconAuthorizationFilter();
synchronized (StartupProperties.get()) {
filter.init(mockConfig);
}
StringBuffer requestUrl = new StringBuffer("http://localhost" + resource);
Mockito.when(mockRequest.getRequestURL()).thenReturn(requestUrl);
Mockito.when(mockRequest.getRequestURI()).thenReturn("/api" + resource);
Mockito.when(mockRequest.getPathInfo()).thenReturn(resource);
Mockito.when(mockResponse.getOutputStream()).thenReturn(
new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
System.out.print(b);
}
});
try {
filter.doFilter(mockRequest, mockResponse, mockChain);
// todo: verify the response error code to 400
} finally {
filter.destroy();
}
}
}
@DataProvider(name = "resourceWithEntity")
private Object[][] createOptionsForResourceWithEntity() {
return new Object[][] {
{"/entities/status/process/"},
{"/entities/suspend/process/"},
{"/instance/running/process/"},
};
}
@Test (dataProvider = "resourceWithEntity")
public void testDoFilterForEntity(String resource) throws Exception {
boolean[] enabledFlags = {false, true};
for (boolean enabled : enabledFlags) {
StartupProperties.get().setProperty(
"falcon.security.authorization.enabled", String.valueOf(enabled));
Filter filter = new FalconAuthorizationFilter();
synchronized (StartupProperties.get()) {
filter.init(mockConfig);
}
String uri = resource + processEntity.getName();
StringBuffer requestUrl = new StringBuffer("http://localhost" + uri);
Mockito.when(mockRequest.getRequestURL()).thenReturn(requestUrl);
Mockito.when(mockRequest.getRequestURI()).thenReturn("/api" + uri);
Mockito.when(mockRequest.getPathInfo()).thenReturn(uri);
try {
filter.doFilter(mockRequest, mockResponse, mockChain);
} finally {
filter.destroy();
}
}
}
@Test
public void testDoFilterForEntityWithInvalidEntity() throws Exception {
CurrentUser.authenticate(FalconTestUtil.TEST_USER_1);
StartupProperties.get().setProperty("falcon.security.authorization.enabled", "true");
Filter filter = new FalconAuthorizationFilter();
synchronized (StartupProperties.get()) {
filter.init(mockConfig);
}
String uri = "/entities/suspend/process/bad-entity";
StringBuffer requestUrl = new StringBuffer("http://localhost" + uri);
Mockito.when(mockRequest.getRequestURL()).thenReturn(requestUrl);
Mockito.when(mockRequest.getRequestURI()).thenReturn("/api" + uri);
Mockito.when(mockRequest.getPathInfo()).thenReturn(uri);
Mockito.when(mockRequest.getMethod()).thenReturn(HttpMethod.GET);
try {
filter.doFilter(mockRequest, mockResponse, mockChain);
// todo: verify the response error code to 403
} finally {
filter.destroy();
}
}
@Test
public void testDoFilterForDeleteEntityInvalidEntity() throws Exception {
CurrentUser.authenticate(FalconTestUtil.TEST_USER_1);
StartupProperties.get().setProperty("falcon.security.authorization.enabled", "true");
Filter filter = new FalconAuthorizationFilter();
synchronized (StartupProperties.get()) {
filter.init(mockConfig);
}
String uri = "/entities/suspend/process/bad-entity";
StringBuffer requestUrl = new StringBuffer("http://localhost" + uri);
Mockito.when(mockRequest.getRequestURL()).thenReturn(requestUrl);
Mockito.when(mockRequest.getRequestURI()).thenReturn("/api" + uri);
Mockito.when(mockRequest.getPathInfo()).thenReturn(uri);
Mockito.when(mockRequest.getMethod()).thenReturn(HttpMethod.DELETE);
try {
filter.doFilter(mockRequest, mockResponse, mockChain);
} finally {
filter.destroy();
}
}
public void addClusterEntity() throws Exception {
clusterEntity = EntityBuilderTestUtil.buildCluster(CLUSTER_ENTITY_NAME);
configStore.publish(EntityType.CLUSTER, clusterEntity);
}
public void addProcessEntity() throws Exception {
processEntity = EntityBuilderTestUtil.buildProcess(PROCESS_ENTITY_NAME,
clusterEntity, "classified-as=Critical");
EntityBuilderTestUtil.addProcessWorkflow(processEntity);
EntityBuilderTestUtil.addProcessACL(processEntity);
configStore.publish(EntityType.PROCESS, processEntity);
}
}
| |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.eventLog;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.KeyboardShortcut;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import static java.awt.event.KeyEvent.*;
@ApiStatus.Internal
public final class ShortcutDataProvider {
/**
* Modifiers that can be used as a separate double click shortcut (Shift+Shift as example)
*/
private static final Collection<Integer> DOUBLE_CLICK_MODIFIER_KEYS = Arrays.asList(VK_CONTROL, VK_SHIFT);
@Nullable
public static String getActionEventText(@Nullable AnActionEvent event) {
return event != null ? getInputEventText(event.getInputEvent(), event.getPlace()) : null;
}
@Nullable
public static String getInputEventText(@Nullable InputEvent inputEvent, @Nullable String place) {
if (inputEvent instanceof KeyEvent) {
// touchbar uses KeyEvent to perform an action
if (ActionPlaces.TOUCHBAR_GENERAL.equals(place)) {
return "Touchbar";
}
return getKeyEventText((KeyEvent)inputEvent);
}
else if (inputEvent instanceof MouseEvent) {
return getMouseEventText((MouseEvent)inputEvent);
}
return null;
}
@Nullable
static String getKeyEventText(@Nullable KeyEvent key) {
if (key == null) return null;
final KeyStroke keystroke = KeyStroke.getKeyStrokeForEvent(key);
return keystroke != null ? getShortcutText(new KeyboardShortcut(keystroke, null)) : "Unknown";
}
@Nullable
static String getMouseEventText(@Nullable MouseEvent event) {
if (event == null) return null;
String res = getMouseButtonText(event.getButton());
if (event.getID() == MouseEvent.MOUSE_DRAGGED) res += "Drag";
int clickCount = event.getClickCount();
if (clickCount > 1) {
res += "(" + roundClickCount(clickCount) + "x)";
}
int modifiers = event.getModifiersEx() & ~BUTTON1_DOWN_MASK & ~BUTTON3_DOWN_MASK & ~BUTTON2_DOWN_MASK;
if (modifiers > 0) {
String modifiersText = getLocaleUnawareKeyModifiersText(modifiers);
if (!modifiersText.isEmpty()) {
res = modifiersText + "+" + res;
}
}
return res;
}
@NotNull
private static String roundClickCount(int clickCount) {
if (clickCount < 3) return String.valueOf(clickCount);
if (clickCount < 5) return "3-5";
if (clickCount < 25) return "5-25";
if (clickCount < 100) return "25-100";
return "100+";
}
private static String getMouseButtonText(int buttonNum) {
switch (buttonNum) {
case MouseEvent.BUTTON1:
return "MouseLeft";
case MouseEvent.BUTTON2:
return "MouseMiddle";
case MouseEvent.BUTTON3:
return "MouseRight";
default:
return "NoMouseButton";
}
}
private static String getShortcutText(KeyboardShortcut shortcut) {
int modifiers = shortcut.getFirstKeyStroke().getModifiers();
int code = shortcut.getFirstKeyStroke().getKeyCode();
// Handling shortcuts that looks like [double <modifier_key>] (to avoid FUS-551)
if (modifiers == 0 && DOUBLE_CLICK_MODIFIER_KEYS.contains(code)) {
String strCode = getLocaleUnawareKeyText(code);
return strCode + "+" + strCode;
}
String results = "";
if (modifiers > 0) {
final String keyModifiersText = getLocaleUnawareKeyModifiersText(modifiers);
if (!keyModifiersText.isEmpty()) {
results = keyModifiersText + "+";
}
}
results += getLocaleUnawareKeyText(code);
return results;
}
private static String getLocaleUnawareKeyText(int keyCode) {
if (keyCode >= VK_0 && keyCode <= VK_9 ||
keyCode >= VK_A && keyCode <= VK_Z) {
return String.valueOf((char)keyCode);
}
String knownKeyCode = ourKeyCodes.get(keyCode);
if (knownKeyCode != null) return knownKeyCode;
if (keyCode >= VK_NUMPAD0 && keyCode <= VK_NUMPAD9) {
char c = (char)(keyCode - VK_NUMPAD0 + '0');
return "NumPad-" + c;
}
if ((keyCode & 0x01000000) != 0) {
return String.valueOf((char)(keyCode ^ 0x01000000));
}
return "Unknown keyCode: 0x" + Integer.toString(keyCode, 16);
}
private static final List<Pair<Integer, String>> ourModifiers = new ArrayList<>(6);
static {
ourModifiers.add(Pair.create(BUTTON1_DOWN_MASK, "Button1"));
ourModifiers.add(Pair.create(BUTTON2_DOWN_MASK, "Button2"));
ourModifiers.add(Pair.create(BUTTON3_DOWN_MASK, "Button3"));
ourModifiers.add(Pair.create(META_DOWN_MASK, "Meta"));
ourModifiers.add(Pair.create(CTRL_DOWN_MASK, "Ctrl"));
ourModifiers.add(Pair.create(ALT_DOWN_MASK, "Alt"));
ourModifiers.add(Pair.create(SHIFT_DOWN_MASK, "Shift"));
ourModifiers.add(Pair.create(ALT_GRAPH_DOWN_MASK, "Alt Graph"));
}
private static String getLocaleUnawareKeyModifiersText(int modifiers) {
List<String> pressed = ourModifiers.stream()
.filter(p -> (p.first & modifiers) != 0)
.map(p -> p.second).collect(Collectors.toList());
return StringUtil.join(pressed, "+");
}
private static final Int2ObjectMap<String> ourKeyCodes = new Int2ObjectOpenHashMap<>();
static {
ourKeyCodes.put(VK_ENTER, "Enter");
ourKeyCodes.put(VK_BACK_SPACE, "Backspace");
ourKeyCodes.put(VK_TAB, "Tab");
ourKeyCodes.put(VK_CANCEL, "Cancel");
ourKeyCodes.put(VK_CLEAR, "Clear");
ourKeyCodes.put(VK_COMPOSE, "Compose");
ourKeyCodes.put(VK_PAUSE, "Pause");
ourKeyCodes.put(VK_CAPS_LOCK, "Caps Lock");
ourKeyCodes.put(VK_ESCAPE, "Escape");
ourKeyCodes.put(VK_SPACE, "Space");
ourKeyCodes.put(VK_PAGE_UP, "Page Up");
ourKeyCodes.put(VK_PAGE_DOWN, "Page Down");
ourKeyCodes.put(VK_END, "End");
ourKeyCodes.put(VK_HOME, "Home");
ourKeyCodes.put(VK_LEFT, "Left");
ourKeyCodes.put(VK_UP, "Up");
ourKeyCodes.put(VK_RIGHT, "Right");
ourKeyCodes.put(VK_DOWN, "Down");
ourKeyCodes.put(VK_BEGIN, "Begin");
// modifiers
ourKeyCodes.put(VK_SHIFT, "Shift");
ourKeyCodes.put(VK_CONTROL, "Control");
ourKeyCodes.put(VK_ALT, "Alt");
ourKeyCodes.put(VK_META, "Meta");
ourKeyCodes.put(VK_ALT_GRAPH, "Alt Graph");
// punctuation
ourKeyCodes.put(VK_COMMA, "Comma");
ourKeyCodes.put(VK_PERIOD, "Period");
ourKeyCodes.put(VK_SLASH, "Slash");
ourKeyCodes.put(VK_SEMICOLON, "Semicolon");
ourKeyCodes.put(VK_EQUALS, "Equals");
ourKeyCodes.put(VK_OPEN_BRACKET, "Open Bracket");
ourKeyCodes.put(VK_BACK_SLASH, "Back Slash");
ourKeyCodes.put(VK_CLOSE_BRACKET, "Close Bracket");
// numpad numeric keys handled below
ourKeyCodes.put(VK_MULTIPLY, "NumPad *");
ourKeyCodes.put(VK_ADD, "NumPad +");
ourKeyCodes.put(VK_SEPARATOR, "NumPad ,");
ourKeyCodes.put(VK_SUBTRACT, "NumPad -");
ourKeyCodes.put(VK_DECIMAL, "NumPad .");
ourKeyCodes.put(VK_DIVIDE, "NumPad /");
ourKeyCodes.put(VK_DELETE, "Delete");
ourKeyCodes.put(VK_NUM_LOCK, "Num Lock");
ourKeyCodes.put(VK_SCROLL_LOCK, "Scroll Lock");
ourKeyCodes.put(VK_WINDOWS, "Windows");
ourKeyCodes.put(VK_CONTEXT_MENU, "Context Menu");
ourKeyCodes.put(VK_F1, "F1");
ourKeyCodes.put(VK_F2, "F2");
ourKeyCodes.put(VK_F3, "F3");
ourKeyCodes.put(VK_F4, "F4");
ourKeyCodes.put(VK_F5, "F5");
ourKeyCodes.put(VK_F6, "F6");
ourKeyCodes.put(VK_F7, "F7");
ourKeyCodes.put(VK_F8, "F8");
ourKeyCodes.put(VK_F9, "F9");
ourKeyCodes.put(VK_F10, "F10");
ourKeyCodes.put(VK_F11, "F11");
ourKeyCodes.put(VK_F12, "F12");
ourKeyCodes.put(VK_F13, "F13");
ourKeyCodes.put(VK_F14, "F14");
ourKeyCodes.put(VK_F15, "F15");
ourKeyCodes.put(VK_F16, "F16");
ourKeyCodes.put(VK_F17, "F17");
ourKeyCodes.put(VK_F18, "F18");
ourKeyCodes.put(VK_F19, "F19");
ourKeyCodes.put(VK_F20, "F20");
ourKeyCodes.put(VK_F21, "F21");
ourKeyCodes.put(VK_F22, "F22");
ourKeyCodes.put(VK_F23, "F23");
ourKeyCodes.put(VK_F24, "F24");
ourKeyCodes.put(VK_PRINTSCREEN, "Print Screen");
ourKeyCodes.put(VK_INSERT, "Insert");
ourKeyCodes.put(VK_HELP, "Help");
ourKeyCodes.put(VK_BACK_QUOTE, "Back Quote");
ourKeyCodes.put(VK_QUOTE, "Quote");
ourKeyCodes.put(VK_KP_UP, "Up");
ourKeyCodes.put(VK_KP_DOWN, "Down");
ourKeyCodes.put(VK_KP_LEFT, "Left");
ourKeyCodes.put(VK_KP_RIGHT, "Right");
ourKeyCodes.put(VK_DEAD_GRAVE, "Dead Grave");
ourKeyCodes.put(VK_DEAD_ACUTE, "Dead Acute");
ourKeyCodes.put(VK_DEAD_CIRCUMFLEX, "Dead Circumflex");
ourKeyCodes.put(VK_DEAD_TILDE, "Dead Tilde");
ourKeyCodes.put(VK_DEAD_MACRON, "Dead Macron");
ourKeyCodes.put(VK_DEAD_BREVE, "Dead Breve");
ourKeyCodes.put(VK_DEAD_ABOVEDOT, "Dead Above Dot");
ourKeyCodes.put(VK_DEAD_DIAERESIS, "Dead Diaeresis");
ourKeyCodes.put(VK_DEAD_ABOVERING, "Dead Above Ring");
ourKeyCodes.put(VK_DEAD_DOUBLEACUTE, "Dead Double Acute");
ourKeyCodes.put(VK_DEAD_CARON, "Dead Caron");
ourKeyCodes.put(VK_DEAD_CEDILLA, "Dead Cedilla");
ourKeyCodes.put(VK_DEAD_OGONEK, "Dead Ogonek");
ourKeyCodes.put(VK_DEAD_IOTA, "Dead Iota");
ourKeyCodes.put(VK_DEAD_VOICED_SOUND, "Dead Voiced Sound");
ourKeyCodes.put(VK_DEAD_SEMIVOICED_SOUND, "Dead Semivoiced Sound");
ourKeyCodes.put(VK_AMPERSAND, "Ampersand");
ourKeyCodes.put(VK_ASTERISK, "Asterisk");
ourKeyCodes.put(VK_QUOTEDBL, "Double Quote");
ourKeyCodes.put(VK_LESS, "Less");
ourKeyCodes.put(VK_GREATER, "Greater");
ourKeyCodes.put(VK_BRACELEFT, "Left Brace");
ourKeyCodes.put(VK_BRACERIGHT, "Right Brace");
ourKeyCodes.put(VK_AT, "At");
ourKeyCodes.put(VK_COLON, "Colon");
ourKeyCodes.put(VK_CIRCUMFLEX, "Circumflex");
ourKeyCodes.put(VK_DOLLAR, "Dollar");
ourKeyCodes.put(VK_EURO_SIGN, "Euro");
ourKeyCodes.put(VK_EXCLAMATION_MARK, "Exclamation Mark");
ourKeyCodes.put(VK_INVERTED_EXCLAMATION_MARK, "Inverted Exclamation Mark");
ourKeyCodes.put(VK_LEFT_PARENTHESIS, "Left Parenthesis");
ourKeyCodes.put(VK_NUMBER_SIGN, "Number Sign");
ourKeyCodes.put(VK_MINUS, "Minus");
ourKeyCodes.put(VK_PLUS, "Plus");
ourKeyCodes.put(VK_RIGHT_PARENTHESIS, "Right Parenthesis");
ourKeyCodes.put(VK_UNDERSCORE, "Underscore");
ourKeyCodes.put(VK_FINAL, "Final");
ourKeyCodes.put(VK_CONVERT, "Convert");
ourKeyCodes.put(VK_NONCONVERT, "No Convert");
ourKeyCodes.put(VK_ACCEPT, "Accept");
ourKeyCodes.put(VK_MODECHANGE, "Mode Change");
ourKeyCodes.put(VK_KANA, "Kana");
ourKeyCodes.put(VK_KANJI, "Kanji");
ourKeyCodes.put(VK_ALPHANUMERIC, "Alphanumeric");
ourKeyCodes.put(VK_KATAKANA, "Katakana");
ourKeyCodes.put(VK_HIRAGANA, "Hiragana");
ourKeyCodes.put(VK_FULL_WIDTH, "Full-Width");
ourKeyCodes.put(VK_HALF_WIDTH, "Half-Width");
ourKeyCodes.put(VK_ROMAN_CHARACTERS, "Roman Characters");
ourKeyCodes.put(VK_ALL_CANDIDATES, "All Candidates");
ourKeyCodes.put(VK_PREVIOUS_CANDIDATE, "Previous Candidate");
ourKeyCodes.put(VK_CODE_INPUT, "Code Input");
ourKeyCodes.put(VK_JAPANESE_KATAKANA, "Japanese Katakana");
ourKeyCodes.put(VK_JAPANESE_HIRAGANA, "Japanese Hiragana");
ourKeyCodes.put(VK_JAPANESE_ROMAN, "Japanese Roman");
ourKeyCodes.put(VK_KANA_LOCK, "Kana Lock");
ourKeyCodes.put(VK_INPUT_METHOD_ON_OFF, "Input Method On/Off");
ourKeyCodes.put(VK_AGAIN, "Again");
ourKeyCodes.put(VK_UNDO, "Undo");
ourKeyCodes.put(VK_COPY, "Copy");
ourKeyCodes.put(VK_PASTE, "Paste");
ourKeyCodes.put(VK_CUT, "Cut");
ourKeyCodes.put(VK_FIND, "Find");
ourKeyCodes.put(VK_PROPS, "Props");
ourKeyCodes.put(VK_STOP, "Stop");
ourKeyCodes.put(VK_UNDEFINED, "Undefined");
}
}
| |
package org.hmhb.csv;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import org.hmhb.county.County;
import org.hmhb.organization.Organization;
import org.hmhb.program.Program;
import org.hmhb.programarea.ProgramArea;
import org.hmhb.user.HmhbUser;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Unit tests for {@link DefaultCsvService}.
*/
public class DefaultCsvServiceTest {
private static final String PROGRAM_HEADER = "org_name,org_email,org_phone,org_facebook,org_website,"
+ "prog_name,prog_year,prog_street,prog_city,prog_state,prog_zip,prog_coordinates,"
+ "prog_goal1,prog_goal2,prog_goal3,prog_outcome1,prog_outcome2,prog_outcome3,"
+ "prog_areas,prog_area_explanation,prog_counties\n";
private static final String USER_HEADER = "email,super_admin,admin,display_name,"
+ "first_name,middle_name,last_name,prefix,suffix,"
+ "image_url,profile_url\n";
private DefaultCsvService toTest;
private Program program1;
private Program program2;
private HmhbUser user1;
private HmhbUser user2;
@Before
public void setUp() {
toTest = new DefaultCsvService();
program1 = createFilledProgram("first-");
program2 = createFilledProgram("second-");
program2.setStartYear(2001);
user1 = createdFilledUser("first-");
user2 = createdFilledUser("second-");
user2.setSuperAdmin(false);
user2.setAdmin(false);
}
private HmhbUser createdFilledUser(String prefix) {
HmhbUser user = new HmhbUser();
user.setEmail(prefix + "email");
user.setSuperAdmin(true);
user.setAdmin(true);
user.setDisplayName(prefix + "display-name");
user.setFirstName(prefix + "first-name");
user.setLastName(prefix + "last-name");
user.setImageUrl(prefix + "image-url");
return user;
}
private Program createFilledProgram(String prefix) {
Program program = new Program();
program.setCity(prefix + "prog-city");
program.setCoordinates(prefix + "prog-coords");
County county1 = new County();
county1.setName(prefix + "county1");
County county2 = new County();
county2.setName(prefix + "county2");
Set<County> counties = new LinkedHashSet<>();
counties.add(county1);
counties.add(county2);
program.setCountiesServed(counties);
program.setMeasurableOutcome1(prefix + "outcome1");
program.setMeasurableOutcome2(prefix + "outcome2");
program.setMeasurableOutcome3(prefix + "outcome3");
program.setName(prefix + "prog-name");
Organization org = new Organization();
org.setName(prefix + "org-name");
org.setContactEmail(prefix + "org-email");
org.setContactPhone(prefix + "org-phone");
org.setFacebookUrl(prefix + "org-facebook");
org.setWebsiteUrl(prefix + "org-website");
program.setOrganization(org);
program.setOtherProgramAreaExplanation(prefix + "other");
program.setPrimaryGoal1(prefix + "goal1");
program.setPrimaryGoal2(prefix + "goal2");
program.setPrimaryGoal3(prefix + "goal3");
ProgramArea progArea1 = new ProgramArea();
progArea1.setName(prefix + "prog-area1");
ProgramArea progArea2 = new ProgramArea();
progArea2.setName(prefix + "prog-area2");
Set<ProgramArea> progAreas = new LinkedHashSet<>();
progAreas.add(progArea1);
progAreas.add(progArea2);
program.setProgramAreas(progAreas);
program.setOtherProgramAreaExplanation(prefix + "prog-area-other");
program.setServesAllCounties(false);
program.setStartYear(1999);
program.setState("GA");
program.setStreetAddress(prefix + "prog-street");
program.setZipCode(prefix + "prog-zip");
return program;
}
@Test(expected = NullPointerException.class)
public void testGenerateFromPrograms_Null() throws Exception {
/* Make the call. */
toTest.generateFromPrograms(null, true, true);
}
@Test
public void testGenerateFromPrograms_EmptyList() throws Exception {
/* Make the call. */
String actual = toTest.generateFromPrograms(Collections.<Program>emptyList(), null, null);
/* Verify the results. */
assertEquals(
PROGRAM_HEADER,
actual
);
}
@Test
public void testGenerateFromPrograms_OneProgram() throws Exception {
/* Make the call. */
String actual = toTest.generateFromPrograms(Collections.singletonList(program1), null, null);
/* Verify the results. */
assertEquals(
PROGRAM_HEADER
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "first-prog-name,1999,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,first-goal2,first-goal3,first-outcome1,first-outcome2,first-outcome3,"
+ "\"first-prog-area1,first-prog-area2\",first-prog-area-other,\"first-county1,first-county2\"\n",
actual
);
}
@Test
public void testGenerateFromPrograms_TwoPrograms() throws Exception {
/* Make the call. */
String actual = toTest.generateFromPrograms(Arrays.asList(program1, program2), null, null);
/* Verify the results. */
assertEquals(
PROGRAM_HEADER
/* first */
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "first-prog-name,1999,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,first-goal2,first-goal3,first-outcome1,first-outcome2,first-outcome3,"
+ "\"first-prog-area1,first-prog-area2\",first-prog-area-other,\"first-county1,first-county2\"\n"
/* second */
+ "second-org-name,second-org-email,second-org-phone,second-org-facebook,second-org-website,"
+ "second-prog-name,2001,second-prog-street,second-prog-city,GA,second-prog-zip,second-prog-coords,"
+ "second-goal1,second-goal2,second-goal3,second-outcome1,second-outcome2,second-outcome3,"
+ "\"second-prog-area1,second-prog-area2\",second-prog-area-other,\"second-county1,second-county2\"\n",
actual
);
}
@Test
public void testGenerateFromPrograms_CommaInNameField() throws Exception {
program1.setName("Has a , in it");
/* Make the call. */
String actual = toTest.generateFromPrograms(Collections.singletonList(program1), null, null);
/* Verify the results. */
assertEquals(
PROGRAM_HEADER
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "\"Has a , in it\",1999,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,first-goal2,first-goal3,first-outcome1,first-outcome2,first-outcome3,"
+ "\"first-prog-area1,first-prog-area2\",first-prog-area-other,\"first-county1,first-county2\"\n",
actual
);
}
@Test
public void testGenerateFromPrograms_DoubleQuoteInNameField() throws Exception {
program1.setName("Has a \" in it");
/* Make the call. */
String actual = toTest.generateFromPrograms(Collections.singletonList(program1), null, null);
/* Verify the results. */
assertEquals(
PROGRAM_HEADER
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "\"Has a \"\" in it\",1999,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,first-goal2,first-goal3,first-outcome1,first-outcome2,first-outcome3,"
+ "\"first-prog-area1,first-prog-area2\",first-prog-area-other,\"first-county1,first-county2\"\n",
actual
);
}
@Test
public void testGenerateFromPrograms_NullStartYear() throws Exception {
program1.setStartYear(null);
/* Make the call. */
String actual = toTest.generateFromPrograms(Collections.singletonList(program1), null, null);
/* Verify the results. */
assertEquals(
PROGRAM_HEADER
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "first-prog-name,,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,first-goal2,first-goal3,first-outcome1,first-outcome2,first-outcome3,"
+ "\"first-prog-area1,first-prog-area2\",first-prog-area-other,\"first-county1,first-county2\"\n",
actual
);
}
@Test
public void testGenerateFromPrograms_SomeNullFields() throws Exception {
program1.setPrimaryGoal2(null);
program1.setPrimaryGoal3(null);
program1.setMeasurableOutcome2(null);
program1.setMeasurableOutcome3(null);
/* Make the call. */
String actual = toTest.generateFromPrograms(Collections.singletonList(program1), null, null);
/* Verify the results. */
assertEquals(
PROGRAM_HEADER
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "first-prog-name,1999,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,,,first-outcome1,,,"
+ "\"first-prog-area1,first-prog-area2\",first-prog-area-other,\"first-county1,first-county2\"\n",
actual
);
}
@Test
public void testGenerateFromPrograms_ServesAllCounties() throws Exception {
program1.setServesAllCounties(true);
/* Make the call. */
String actual = toTest.generateFromPrograms(Collections.singletonList(program1), null, null);
/* Verify the results. */
assertEquals(
PROGRAM_HEADER
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "first-prog-name,1999,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,first-goal2,first-goal3,first-outcome1,first-outcome2,first-outcome3,"
+ "\"first-prog-area1,first-prog-area2\",first-prog-area-other,ALL\n",
actual
);
}
@Test
public void testGenerateFromPrograms_ServesNoCounties() throws Exception {
program1.getCountiesServed().clear();
/* Make the call. */
String actual = toTest.generateFromPrograms(Collections.singletonList(program1), null, null);
/* Verify the results. */
assertEquals(
PROGRAM_HEADER
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "first-prog-name,1999,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,first-goal2,first-goal3,first-outcome1,first-outcome2,first-outcome3,"
+ "\"first-prog-area1,first-prog-area2\",first-prog-area-other,\n",
actual
);
}
@Test
public void testGenerateFromPrograms_NoProgramAreas() throws Exception {
program1.getProgramAreas().clear();
/* Make the call. */
String actual = toTest.generateFromPrograms(Collections.singletonList(program1), null, null);
/* Verify the results. */
assertEquals(
PROGRAM_HEADER
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "first-prog-name,1999,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,first-goal2,first-goal3,first-outcome1,first-outcome2,first-outcome3,"
+ ",first-prog-area-other,\"first-county1,first-county2\"\n",
actual
);
}
@Ignore
@Test
public void testGenerateFromPrograms_TwoPrograms_ExpandCounties() throws Exception {
/* Make the call. */
String actual = toTest.generateFromPrograms(Arrays.asList(program1, program2), true, false);
/* Verify the results. */
assertEquals(
PROGRAM_HEADER
/* first: county1 */
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "first-prog-name,1999,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,first-goal2,first-goal3,first-outcome1,first-outcome2,first-outcome3,"
+ "\"first-prog-area1,first-prog-area2\",first-prog-area-other,first-county1\n"
/* first: county2 */
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "first-prog-name,1999,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,first-goal2,first-goal3,first-outcome1,first-outcome2,first-outcome3,"
+ "\"first-prog-area1,first-prog-area2\",first-prog-area-other,first-county2\n"
/* second: county1 */
+ "second-org-name,second-org-email,second-org-phone,second-org-facebook,second-org-website,"
+ "second-prog-name,2001,second-prog-street,second-prog-city,GA,second-prog-zip,second-prog-coords,"
+ "second-goal1,second-goal2,second-goal3,second-outcome1,second-outcome2,second-outcome3,"
+ "\"second-prog-area1,second-prog-area2\",second-prog-area-other,second-county1\n"
/* second: county2 */
+ "second-org-name,second-org-email,second-org-phone,second-org-facebook,second-org-website,"
+ "second-prog-name,2001,second-prog-street,second-prog-city,GA,second-prog-zip,second-prog-coords,"
+ "second-goal1,second-goal2,second-goal3,second-outcome1,second-outcome2,second-outcome3,"
+ "\"second-prog-area1,second-prog-area2\",second-prog-area-other,second-county2\n",
actual
);
}
@Ignore
@Test
public void testGenerateFromPrograms_TwoPrograms_ExpandProgramAreas() throws Exception {
/* Make the call. */
String actual = toTest.generateFromPrograms(Arrays.asList(program1, program2), false, true);
/* Verify the results. */
assertEquals(
PROGRAM_HEADER
/* first: progArea1 */
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "first-prog-name,1999,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,first-goal2,first-goal3,first-outcome1,first-outcome2,first-outcome3,"
+ "first-prog-area1,first-prog-area-other,\"first-county1,first-county2\"\n"
/* first: progArea2 */
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "first-prog-name,1999,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,first-goal2,first-goal3,first-outcome1,first-outcome2,first-outcome3,"
+ "first-prog-area2,first-prog-area-other,\"first-county1,first-county2\"\n"
/* second: progArea1 */
+ "second-org-name,second-org-email,second-org-phone,second-org-facebook,second-org-website,"
+ "second-prog-name,2001,second-prog-street,second-prog-city,GA,second-prog-zip,second-prog-coords,"
+ "second-goal1,second-goal2,second-goal3,second-outcome1,second-outcome2,second-outcome3,"
+ "second-prog-area1,second-prog-area-other,\"second-county1,second-county2\"\n"
/* second: progArea2 */
+ "second-org-name,second-org-email,second-org-phone,second-org-facebook,second-org-website,"
+ "second-prog-name,2001,second-prog-street,second-prog-city,GA,second-prog-zip,second-prog-coords,"
+ "second-goal1,second-goal2,second-goal3,second-outcome1,second-outcome2,second-outcome3,"
+ "second-prog-area2,second-prog-area-other,\"second-county1,second-county2\"\n",
actual
);
}
@Ignore
@Test
public void testGenerateFromPrograms_TwoPrograms_ExpandCountiesAndProgramAreas() throws Exception {
/* Make the call. */
String actual = toTest.generateFromPrograms(Arrays.asList(program1, program2), true, true);
/* Verify the results. */
assertEquals(
PROGRAM_HEADER
/* first: progArea1, county1 */
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "first-prog-name,1999,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,first-goal2,first-goal3,first-outcome1,first-outcome2,first-outcome3,"
+ "first-prog-area1,first-prog-area-other,first-county1\n"
/* first: progArea1, county2 */
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "first-prog-name,1999,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,first-goal2,first-goal3,first-outcome1,first-outcome2,first-outcome3,"
+ "first-prog-area1,first-prog-area-other,first-county2\n"
/* first: progArea2, county1 */
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "first-prog-name,1999,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,first-goal2,first-goal3,first-outcome1,first-outcome2,first-outcome3,"
+ "first-prog-area2,first-prog-area-other,first-county1\n"
/* first: progArea2, county2 */
+ "first-org-name,first-org-email,first-org-phone,first-org-facebook,first-org-website,"
+ "first-prog-name,1999,first-prog-street,first-prog-city,GA,first-prog-zip,first-prog-coords,"
+ "first-goal1,first-goal2,first-goal3,first-outcome1,first-outcome2,first-outcome3,"
+ "first-prog-area2,first-prog-area-other,first-county2\n"
/* second: progArea1, county1 */
+ "second-org-name,second-org-email,second-org-phone,second-org-facebook,second-org-website,"
+ "second-prog-name,1999,second-prog-street,second-prog-city,GA,second-prog-zip,second-prog-coords,"
+ "second-goal1,second-goal2,second-goal3,second-outcome1,second-outcome2,second-outcome3,"
+ "second-prog-area1,second-prog-area-other,second-county1\n"
/* second: progArea1, county2 */
+ "second-org-name,second-org-email,second-org-phone,second-org-facebook,second-org-website,"
+ "second-prog-name,1999,second-prog-street,second-prog-city,GA,second-prog-zip,second-prog-coords,"
+ "second-goal1,second-goal2,second-goal3,second-outcome1,second-outcome2,second-outcome3,"
+ "second-prog-area1,second-prog-area-other,second-county2\n"
/* second: progArea2, county1 */
+ "second-org-name,second-org-email,second-org-phone,second-org-facebook,second-org-website,"
+ "second-prog-name,1999,second-prog-street,second-prog-city,GA,second-prog-zip,second-prog-coords,"
+ "second-goal1,second-goal2,second-goal3,second-outcome1,second-outcome2,second-outcome3,"
+ "second-prog-area2,second-prog-area-other,second-county1\n"
/* second: progArea2, county2 */
+ "second-org-name,second-org-email,second-org-phone,second-org-facebook,second-org-website,"
+ "second-prog-name,1999,second-prog-street,second-prog-city,GA,second-prog-zip,second-prog-coords,"
+ "second-goal1,second-goal2,second-goal3,second-outcome1,second-outcome2,second-outcome3,"
+ "second-prog-area2,second-prog-area-other,second-county2\n",
actual
);
}
@Test(expected = NullPointerException.class)
public void testGenerateFromUsers_Null() throws Exception {
/* Make the call. */
toTest.generateFromUsers(null);
}
@Test
public void testGenerateFromUsers_EmptyList() throws Exception {
/* Make the call. */
String actual = toTest.generateFromUsers(Collections.<HmhbUser>emptyList());
/* Verify the results. */
assertEquals(
USER_HEADER,
actual
);
}
@Test
public void testGenerateFromUsers_OneUser() throws Exception {
/* Make the call. */
String actual = toTest.generateFromUsers(Collections.singletonList(user1));
/* Verify the results. */
assertEquals(
USER_HEADER
+ "first-email,true,true,first-display-name,"
+ "first-first-name,,first-last-name,,,"
+ "first-image-url,\n",
actual
);
}
@Test
public void testGenerateFromUsers_TwoUsers() throws Exception {
/* Make the call. */
String actual = toTest.generateFromUsers(Arrays.asList(user1, user2));
/* Verify the results. */
assertEquals(
USER_HEADER
/* first */
+ "first-email,true,true,first-display-name,"
+ "first-first-name,,first-last-name,,,"
+ "first-image-url,\n"
/* second */
+ "second-email,false,false,second-display-name,"
+ "second-first-name,,second-last-name,,,"
+ "second-image-url,\n",
actual
);
}
}
| |
/* The contents of this file are subject to the license and copyright terms
* detailed in the license directory at the root of the source tree (also
* available online at http://fedora-commons.org/license/).
*/
package org.fcrepo.server.journal.readerwriter.multifile;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.fcrepo.common.Constants;
import org.fcrepo.server.Context;
import org.fcrepo.server.errors.ServerException;
import org.fcrepo.server.journal.JournalConstants;
import org.fcrepo.server.journal.JournalConsumer;
import org.fcrepo.server.journal.MockJournalRecoveryLog;
import org.fcrepo.server.journal.MockServerForJournalTesting;
import org.fcrepo.server.journal.ServerInterface;
import org.fcrepo.server.journal.readerwriter.multifile.MultiFileJournalConstants;
import org.fcrepo.server.journal.readerwriter.multifile.MultiFileJournalHelper;
import org.fcrepo.server.management.MockManagementDelegate;
import junit.framework.TestCase;
public class TestLockingFollowingJournalReader
extends TestCase
implements Constants, JournalConstants, MultiFileJournalConstants {
private static final int WAIT_INTERVAL = 5;
private static final String JOURNAL_FILENAME_PREFIX = "unit";
private static final String DUMMY_HASH_VALUE = "Dummy Hash";
private File journalDirectory;
private File archiveDirectory;
private File lockRequestFile;
private File lockAcceptedFile;
private Map<String, String> parameters;
private ServerInterface server;
private final String role = "DumbGrunt";
private MyMockManagementDelegate delegate;
private int initialNumberOfThreads;
public TestLockingFollowingJournalReader(String name) {
super(name);
}
@Override
protected void setUp() throws Exception {
super.setUp();
journalDirectory = createTempDirectory("fedoraTestingJournalFiles");
archiveDirectory = createTempDirectory("fedoraTestingArchiveFiles");
lockRequestFile =
new File(journalDirectory.getPath() + File.separator
+ "lockRequested");
lockRequestFile.delete();
lockAcceptedFile =
new File(journalDirectory.getPath() + File.separator
+ "lockAccepted");
lockAcceptedFile.delete();
delegate = new MyMockManagementDelegate();
server = new MockServerForJournalTesting(delegate, DUMMY_HASH_VALUE);
parameters = new HashMap<String, String>();
parameters.put(PARAMETER_JOURNAL_RECOVERY_LOG_CLASSNAME,
MockJournalRecoveryLog.class.getName());
parameters.put(PARAMETER_JOURNAL_READER_CLASSNAME,
"org.fcrepo.server.journal.readerwriter.multifile."
+ "LockingFollowingJournalReader");
parameters.put(PARAMETER_JOURNAL_DIRECTORY, journalDirectory.getPath());
parameters.put(PARAMETER_ARCHIVE_DIRECTORY, archiveDirectory.getPath());
parameters.put(PARAMETER_FOLLOW_POLLING_INTERVAL, "1");
parameters.put(PARAMETER_JOURNAL_FILENAME_PREFIX,
JOURNAL_FILENAME_PREFIX);
parameters.put(PARAMETER_LOCK_REQUESTED_FILENAME, lockRequestFile
.getPath());
parameters.put(PARAMETER_LOCK_ACCEPTED_FILENAME, lockAcceptedFile
.getPath());
initialNumberOfThreads = getNumberOfCurrentThreads();
}
/**
* Create 3 files and watch it process all of them
*/
public void testSimpleNoLocking() {
try {
// create 3 files, each with an ingest
createJournalFileFromString(getSimpleIngestString());
createJournalFileFromString(getSimpleIngestString());
createJournalFileFromString(getSimpleIngestString());
// create the JournalConsumer and run it.
JournalConsumer consumer =
new JournalConsumer(parameters, role, server);
startConsumerThread(consumer);
waitWhileThreadRuns(WAIT_INTERVAL);
consumer.shutdown();
assertEquals("Expected to see 3 ingests", 3, delegate
.getCallCount());
assertEquals("Journal files not all gone",
0,
howManyFilesInDirectory(journalDirectory));
assertEquals("Wrong number of archive files",
3,
howManyFilesInDirectory(archiveDirectory));
} catch (Throwable e) {
processException(e);
}
}
/**
* A lock request created before startup will prevent processing. When the
* request is removed, processing will occur.
*/
public void disabledtestLockBeforeStartingAndResume() {
try {
// create 3 files, each with an ingest, and create a lock request.
createJournalFileFromString(getSimpleIngestString());
createJournalFileFromString(getSimpleIngestString());
createJournalFileFromString(getSimpleIngestString());
createLockRequest();
// create the JournalConsumer and run it.
JournalConsumer consumer =
new JournalConsumer(parameters, role, server);
startConsumerThread(consumer);
// we should see the lock accepted and no processing going on.
waitForLockAccepted();
waitWhileThreadRuns(WAIT_INTERVAL);
assertEquals("Journal files should not be processed", 0, delegate
.getCallCount());
assertEquals("Journal files should not be processed",
3,
howManyFilesInDirectory(journalDirectory));
assertEquals("Journal files should not be processed",
0,
howManyFilesInDirectory(archiveDirectory));
int lockMessageIndex = assertLockMessageInLog();
// remove the request. We should see the lock released and
// processing should run to completion.
removeLockRequest();
waitForLockReleased();
waitWhileThreadRuns(WAIT_INTERVAL);
consumer.shutdown();
assertEquals("Expected to see 3 ingests", 3, delegate
.getCallCount());
assertEquals("Journal files not all gone",
0,
howManyFilesInDirectory(journalDirectory));
assertEquals("Wrong number of archive files",
3,
howManyFilesInDirectory(archiveDirectory));
assertUnlockMessageInLog(lockMessageIndex);
} catch (Throwable e) {
processException(e);
}
}
/**
* A lock request created while a file is in progress, which should prevent
* further processing until it is removed.
*/
public void testLockWhileProcessingAndResume() {
try {
// create 3 files, each with an ingest
createJournalFileFromString(getSimpleIngestString());
createJournalFileFromString(getSimpleIngestString());
createJournalFileFromString(getSimpleIngestString());
// a lock request will be created while the second file is being
// processed.
delegate.setIngestOperation(new LockAfterSecondIngest());
// create the JournalConsumer and run it.
JournalConsumer consumer =
new JournalConsumer(parameters, role, server);
startConsumerThread(consumer);
// we should see the lock accepted and processing stop after the
// second file.
waitForLockAccepted();
waitWhileThreadRuns(WAIT_INTERVAL);
assertEquals("We should stop after the second ingest", 2, delegate
.getCallCount());
assertEquals("One Journal file should not be processed",
1,
howManyFilesInDirectory(journalDirectory));
assertEquals("Only two Journal files should be processed",
2,
howManyFilesInDirectory(archiveDirectory));
int lockMessageIndex = assertLockMessageInLog();
// remove the request. We should see the lock released and
// processing should run to completion.
removeLockRequest();
waitForLockReleased();
waitWhileThreadRuns(WAIT_INTERVAL);
consumer.shutdown();
assertEquals("Expected to see 3 ingests", 3, delegate
.getCallCount());
assertEquals("Journal files not all gone",
0,
howManyFilesInDirectory(journalDirectory));
assertEquals("Wrong number of archive files",
3,
howManyFilesInDirectory(archiveDirectory));
assertUnlockMessageInLog(lockMessageIndex);
} catch (Throwable e) {
processException(e);
}
}
/**
* A lock request created while the system if polling, which should prevent
* further processing until it is removed. Create 1 files and watch it
* process all of them. Create a lock and wait for the ack. Create a 2nd
* file, and it will not be processed. Remove the lock; ack is removed and
* last file is processed.
*/
public void disabledtestLockWhilePollingAndResume() {
try {
// create 1 file, with an ingest
createJournalFileFromString(getSimpleIngestString());
// create the JournalConsumer and run it.
JournalConsumer consumer =
new JournalConsumer(parameters, role, server);
startConsumerThread(consumer);
// the file should be processed and we being polling.
waitWhileThreadRuns(WAIT_INTERVAL);
assertEquals("The first file should have been processed.",
1,
delegate.getCallCount());
assertEquals("The first file should have been processed.",
0,
howManyFilesInDirectory(journalDirectory));
assertEquals("The first file should have been processed.",
1,
howManyFilesInDirectory(archiveDirectory));
// create a lock request and wait for the acceptance.
createLockRequest();
waitForLockAccepted();
// create another Journal file, but it won't be processed.
createJournalFileFromString(getSimpleIngestString());
waitWhileThreadRuns(WAIT_INTERVAL);
assertEquals("The second file should not have been processed.",
1,
delegate.getCallCount());
assertEquals("The second file should not have been processed.",
1,
howManyFilesInDirectory(journalDirectory));
assertEquals("The second file should not have been processed.",
1,
howManyFilesInDirectory(archiveDirectory));
int lockMessageIndex = assertLockMessageInLog();
// remove the lock and the file is processed.
removeLockRequest();
waitForLockReleased();
waitWhileThreadRuns(WAIT_INTERVAL);
consumer.shutdown();
assertEquals("Expected to see 2 ingests", 2, delegate
.getCallCount());
assertEquals("Journal files not all gone",
0,
howManyFilesInDirectory(journalDirectory));
assertEquals("Wrong number of archive files",
2,
howManyFilesInDirectory(archiveDirectory));
assertUnlockMessageInLog(lockMessageIndex);
} catch (Throwable e) {
processException(e);
}
}
private void createLockRequest() throws IOException {
lockRequestFile.createNewFile();
}
private void removeLockRequest() {
lockRequestFile.delete();
}
private int howManyFilesInDirectory(File directory) {
return MultiFileJournalHelper
.getSortedArrayOfJournalFiles(directory,
JOURNAL_FILENAME_PREFIX).length;
}
/**
* Wait until the JournalConsumerThread stops, or until the time limit
* expires, whichever comes first.
*/
private void waitWhileThreadRuns(int maxSecondsToWait) {
for (int i = 0; i < maxSecondsToWait; i++) {
if (getNumberOfCurrentThreads() == initialNumberOfThreads) {
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Wait until the lock is accepted, or until the time runs out. If the
* latter, complain.
*/
private void waitForLockAccepted() {
int maxWait = 3;
for (int i = 0; i < maxWait; i++) {
if (lockAcceptedFile.exists()) {
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
fail("Lock was not accepted after " + maxWait + " seconds.");
}
/**
* Wait until the lock is released, or until the time runs out. If the
* latter, complain.
*/
private void waitForLockReleased() {
int maxWait = 3;
for (int i = 0; i < maxWait; i++) {
if (!lockAcceptedFile.exists()) {
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
fail("Lock was not released after " + maxWait + " seconds.");
}
/**
* Set the ManagementDelegate into the JournalConsumer, which will create
* the JournalConsumerThread.
*/
private void startConsumerThread(JournalConsumer consumer) {
consumer.setManagementDelegate(delegate);
}
private int getNumberOfCurrentThreads() {
int i =
Thread.currentThread().getThreadGroup()
.enumerate(new Thread[500]);
return i;
}
private void createJournalFileFromString(String text) throws IOException {
File journal =
File.createTempFile(JOURNAL_FILENAME_PREFIX,
null,
journalDirectory);
journal.deleteOnExit();
FileWriter writer = new FileWriter(journal);
writer.write(text);
writer.close();
}
/**
* Confirm that the last message in the log is a lock message, and return
* its position in the logger.
*/
private int assertLockMessageInLog() {
List<String> messages = MockJournalRecoveryLog.getMessages();
int lastMessageIndex = messages.size() - 1;
String lastMessage = messages.get(lastMessageIndex);
assertStringStartsWith(lastMessage, "Lock request detected:");
return lastMessageIndex;
}
/**
* Confirm that the log message following the lock message is in fact an
* unlock message.
*/
private void assertUnlockMessageInLog(int lockMessageIndex) {
List<String> messages = MockJournalRecoveryLog.getMessages();
int unlockMessageIndex = lockMessageIndex + 1;
assertTrue(messages.size() > unlockMessageIndex);
String unlockMessage = messages.get(unlockMessageIndex);
assertStringStartsWith(unlockMessage, "Lock request removed");
}
private void assertStringStartsWith(String string, String prefix) {
if (!string.startsWith(prefix)) {
fail("String does not start as expected: string='" + string
+ "', prefix='" + prefix + "'");
}
}
private void processException(Throwable e) {
if (e instanceof ServerException) {
System.err.println("ServerException: code='"
+ ((ServerException) e).getCode() + "', class='"
+ e.getClass().getName() + "'");
StackTraceElement[] traces = e.getStackTrace();
for (StackTraceElement element : traces) {
System.err.println(element);
}
Throwable cause = e.getCause();
if (cause != null) {
cause.printStackTrace();
}
fail("Threw a ServerException");
} else {
e.printStackTrace();
fail("Threw an exception");
}
}
private File createTempDirectory(String name) {
File directory = new File(System.getProperty("java.io.tmpdir"), name);
directory.mkdir();
cleanOutDirectory(directory);
directory.deleteOnExit();
return directory;
}
private void cleanOutDirectory(File directory) {
File[] files = directory.listFiles();
for (File element : files) {
element.delete();
}
}
private String getSimpleIngestString() {
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<FedoraJournal repositoryHash=\""
+ DUMMY_HASH_VALUE
+ "\" timestamp=\"2006-08-11T11:14:43.011-0400\">\n"
+ " <JournalEntry method=\"ingest\" timestamp=\"2006-08-11T11:14:42.690-0400\" clientIpAddress=\"128.84.103.30\" loginId=\"fedoraAdmin\">\n"
+ " <context>\n"
+ " <password>junk</password>\n"
+ " <noOp>false</noOp>\n"
+ " <now>2006-08-11T11:14:42.690-0400</now>\n"
+ " <multimap name=\"environment\">\n"
+ " <multimapkey name=\"urn:fedora:names:fedora:2.1:environment:httpRequest:authType\">\n"
+ " <multimapvalue>BASIC</multimapvalue>\n"
+ " </multimapkey>\n"
+ " </multimap>\n"
+ " <multimap name=\"subject\"></multimap>\n"
+ " <multimap name=\"action\"> </multimap>\n"
+ " <multimap name=\"resource\"></multimap>\n"
+ " <multimap name=\"recovery\"></multimap>\n"
+ " </context>\n"
+ " <argument name=\"serialization\" type=\"stream\">PD94</argument>\n"
+ " <argument name=\"message\" type=\"string\">Minimal Ingest sample</argument>\n"
+ " <argument name=\"format\" type=\"string\">"
+ FOXML1_1.uri
+ "</argument>\n"
+ " <argument name=\"encoding\" type=\"string\">UTF-8</argument>\n"
+ " <argument name=\"pid\" type=\"string\">new</argument>\n"
+ " </JournalEntry>\n" + "</FedoraJournal>\n";
}
/**
* Set one of these as the ingest object on the ManagementDelegate. When the
* second ingest operation begins, a Lock Request will be created.
*/
private final class LockAfterSecondIngest
implements Runnable {
public void run() {
if (delegate.getCallCount() == 2) {
try {
createLockRequest();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* This sub-class of {@link MockManagementDelegate} allows us to insert a
* {@link Runnable} that will be executed in the middle of an ingest call.
*
* @author Firstname Lastname
*/
private static class MyMockManagementDelegate
extends MockManagementDelegate {
private Runnable ingestOperation;
public void setIngestOperation(Runnable ingestOperation) {
this.ingestOperation = ingestOperation;
}
@Override
public String ingest(Context context,
InputStream serialization,
String logMessage,
String format,
String encoding,
String pid) throws ServerException {
String result =
super.ingest(context,
serialization,
logMessage,
format,
encoding,
pid);
if (ingestOperation != null) {
ingestOperation.run();
}
return result;
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.datatorrent.contrib.cassandra;
import java.math.BigDecimal;
import java.util.*;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.apache.hadoop.classification.InterfaceStability.Evolving;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.ColumnDefinitions;
import com.datastax.driver.core.DataType;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datatorrent.api.Context;
import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.api.DefaultOutputPort;
import com.datatorrent.api.Operator;
import com.datatorrent.api.annotation.OutputPortFieldAnnotation;
import com.datatorrent.lib.util.FieldInfo;
import com.datatorrent.lib.util.PojoUtils;
import com.datatorrent.lib.util.PojoUtils.*;
/**
* <p>
* CassandraPOJOInputOperator</p>
* A generic implementation of AbstractCassandraInputOperator that fetches rows of data from Cassandra and emits them as POJOs.
* Each row is converted to a POJO by mapping the columns in the row to fields of the POJO based on a user specified mapping.
* User should also provide a query to fetch the rows from database. This query is run continuously to fetch new data and
* hence should be parameterized. The parameters that can be used are %t for table name, %p for primary key, %s for start value
* and %l for limit. The start value is continuously updated with the value of a primary key column of the last row from
* the result of the previous run of the query. The primary key column is also identified by the user using a property.
*
* @displayName Cassandra Input Operator
* @category Input
* @tags database, nosql, pojo, cassandra
* @since 3.0.0
*/
@Evolving
public class CassandraPOJOInputOperator extends AbstractCassandraInputOperator<Object> implements Operator.ActivationListener<OperatorContext>
{
@NotNull
private List<FieldInfo> fieldInfos;
private Number startRow;
private Long startRowToken = Long.MIN_VALUE;
@NotNull
private String tablename;
@NotNull
private String query;
@NotNull
private String primaryKeyColumn;
@Min(1)
private int limit = 10;
private String TOKEN_QUERY;
private transient DataType primaryKeyColumnType;
private transient Row lastRowInBatch;
private transient BoundStatement fetchKeyStatement;
protected final transient List<Object> setters;
protected final transient List<DataType> columnDataTypes;
protected transient Class<?> pojoClass;
@OutputPortFieldAnnotation(schemaRequired = true)
public final transient DefaultOutputPort<Object> outputPort = new DefaultOutputPort<Object>()
{
@Override
public void setup(Context.PortContext context)
{
pojoClass = context.getValue(Context.PortContext.TUPLE_CLASS);
}
};
/*
* Number of records to be fetched in one time from cassandra table.
*/
public int getLimit()
{
return limit;
}
public void setLimit(int limit)
{
this.limit = limit;
}
/*
* Primary Key Column of table.
* Gets the primary key column of Cassandra table.
*/
public String getPrimaryKeyColumn()
{
return primaryKeyColumn;
}
public void setPrimaryKeyColumn(String primaryKeyColumn)
{
this.primaryKeyColumn = primaryKeyColumn;
}
/*
* User has the option to specify the starting row of the range of data they desire.
*/
public Number getStartRow()
{
return startRow;
}
public void setStartRow(Number startRow)
{
this.startRow = startRow;
}
/*
* Parameterized query with parameters such as %t for table name , %p for primary key, %s for start value and %l for limit.
* Example of retrieveQuery:
* select * from %t where token(%p) > %s limit %l;
*/
public String getQuery()
{
return query;
}
public void setQuery(String query)
{
this.query = query;
}
/**
* A list of {@link FieldInfo}s where each item maps a column name to a pojo field name.
*/
public List<FieldInfo> getFieldInfos()
{
return fieldInfos;
}
/**
* Sets the {@link FieldInfo}s. A {@link FieldInfo} maps a store column to a pojo field name.<br/>
* The value from fieldInfo.column is assigned to fieldInfo.pojoFieldExpression.
*
* @description $[].columnName name of the database column name
* @description $[].pojoFieldExpression pojo field name or expression
* @useSchema $[].pojoFieldExpression outputPort.fields[].name
*/
public void setFieldInfos(List<FieldInfo> fieldInfos)
{
this.fieldInfos = fieldInfos;
}
/*
* Tablename in cassandra.
*/
public String getTablename()
{
return tablename;
}
public void setTablename(String tablename)
{
this.tablename = tablename;
}
public CassandraPOJOInputOperator()
{
super();
columnDataTypes = new ArrayList<DataType>();
setters = new ArrayList<Object>();
this.store = new CassandraStore();
}
@Override
public void setup(OperatorContext context)
{
super.setup(context);
Long keyToken;
TOKEN_QUERY = "select token(" + primaryKeyColumn + ") from " + store.keyspace + "." + tablename + " where " + primaryKeyColumn + " = ?";
PreparedStatement statement = store.getSession().prepare(TOKEN_QUERY);
fetchKeyStatement = new BoundStatement(statement);
if (startRow != null && (keyToken = fetchKeyTokenFromDB(startRow)) != null) {
startRowToken = keyToken;
}
}
@Override
public void activate(OperatorContext context)
{
com.datastax.driver.core.ResultSet rs = store.getSession().execute("select * from " + store.keyspace + "." + tablename + " LIMIT " + 1);
ColumnDefinitions rsMetaData = rs.getColumnDefinitions();
primaryKeyColumnType = rsMetaData.getType(primaryKeyColumn);
if (query.contains("%t")) {
query = query.replace("%t", tablename);
}
if (query.contains("%p")) {
query = query.replace("%p", primaryKeyColumn);
}
if (query.contains("%l")) {
query = query.replace("%l", limit + "");
}
LOG.debug("query is {}", query);
for (FieldInfo fieldInfo : fieldInfos) {
// Get the designated column's data type.
DataType type = rsMetaData.getType(fieldInfo.getColumnName());
columnDataTypes.add(type);
Object setter;
final String setterExpr = fieldInfo.getPojoFieldExpression();
switch (type.getName()) {
case ASCII:
case TEXT:
case VARCHAR:
setter = PojoUtils.createSetter(pojoClass, setterExpr, String.class);
break;
case BOOLEAN:
setter = PojoUtils.createSetterBoolean(pojoClass, setterExpr);
break;
case INT:
setter = PojoUtils.createSetterInt(pojoClass, setterExpr);
break;
case BIGINT:
case COUNTER:
setter = PojoUtils.createSetterLong(pojoClass, setterExpr);
break;
case FLOAT:
setter = PojoUtils.createSetterFloat(pojoClass, setterExpr);
break;
case DOUBLE:
setter = PojoUtils.createSetterDouble(pojoClass, setterExpr);
break;
case DECIMAL:
setter = PojoUtils.createSetter(pojoClass, setterExpr, BigDecimal.class);
break;
case SET:
setter = PojoUtils.createSetter(pojoClass, setterExpr, Set.class);
break;
case MAP:
setter = PojoUtils.createSetter(pojoClass, setterExpr, Map.class);
break;
case LIST:
setter = PojoUtils.createSetter(pojoClass, setterExpr, List.class);
break;
case TIMESTAMP:
setter = PojoUtils.createSetter(pojoClass, setterExpr, Date.class);
break;
case UUID:
setter = PojoUtils.createSetter(pojoClass, setterExpr, UUID.class);
break;
default:
setter = PojoUtils.createSetter(pojoClass, setterExpr, Object.class);
break;
}
setters.add(setter);
}
}
@Override
@SuppressWarnings("unchecked")
public Object getTuple(Row row)
{
lastRowInBatch = row;
Object obj;
try {
// This code will be replaced after integration of creating POJOs on the fly utility.
obj = pojoClass.newInstance();
}
catch (InstantiationException | IllegalAccessException ex) {
throw new RuntimeException(ex);
}
for (int i = 0; i < columnDataTypes.size(); i++) {
DataType type = columnDataTypes.get(i);
String columnName = fieldInfos.get(i).getColumnName();
switch (type.getName()) {
case UUID:
final UUID id = row.getUUID(columnName);
((Setter<Object, UUID>)setters.get(i)).set(obj, id);
break;
case ASCII:
case VARCHAR:
case TEXT:
final String ascii = row.getString(columnName);
((Setter<Object, String>)setters.get(i)).set(obj, ascii);
break;
case BOOLEAN:
final boolean bool = row.getBool(columnName);
((SetterBoolean)setters.get(i)).set(obj, bool);
break;
case INT:
final int intValue = row.getInt(columnName);
((SetterInt)setters.get(i)).set(obj, intValue);
break;
case BIGINT:
case COUNTER:
final long longValue = row.getLong(columnName);
((SetterLong)setters.get(i)).set(obj, longValue);
break;
case FLOAT:
final float floatValue = row.getFloat(columnName);
((SetterFloat)setters.get(i)).set(obj, floatValue);
break;
case DOUBLE:
final double doubleValue = row.getDouble(columnName);
((SetterDouble)setters.get(i)).set(obj, doubleValue);
break;
case DECIMAL:
final BigDecimal decimal = row.getDecimal(columnName);
((Setter<Object, BigDecimal>)setters.get(i)).set(obj, decimal);
break;
case SET:
Set<?> set = row.getSet(columnName, Object.class);
((Setter<Object, Set<?>>)setters.get(i)).set(obj, set);
break;
case MAP:
final Map<?, ?> map = row.getMap(columnName, Object.class, Object.class);
((Setter<Object, Map<?, ?>>)setters.get(i)).set(obj, map);
break;
case LIST:
final List<?> list = row.getList(columnName, Object.class);
((Setter<Object, List<?>>)setters.get(i)).set(obj, list);
break;
case TIMESTAMP:
final Date date = row.getDate(columnName);
((Setter<Object, Date>)setters.get(i)).set(obj, date);
break;
default:
throw new RuntimeException("unsupported data type " + type.getName());
}
}
return obj;
}
/*
* This method replaces the parameters in Query with actual values given by user.
* Example of retrieveQuery:
* select * from %t where token(%p) > %v limit %l;
*/
@Override
public String queryToRetrieveData()
{
if (query.contains("%v")) {
return query.replace("%v", startRowToken + "");
}
return query;
}
/*
* Overriding emitTupes to save primarykey column value from last row in batch.
*/
@Override
public void emitTuples()
{
super.emitTuples();
if (lastRowInBatch != null) {
startRowToken = getPrimaryKeyToken(primaryKeyColumnType.getName());
}
}
private Long getPrimaryKeyToken(DataType.Name primaryKeyDataType)
{
Object keyValue;
switch (primaryKeyDataType) {
case UUID:
keyValue = lastRowInBatch.getUUID(primaryKeyColumn);
break;
case INT:
keyValue = lastRowInBatch.getInt(primaryKeyColumn);
break;
case COUNTER:
keyValue = lastRowInBatch.getLong(primaryKeyColumn);
break;
case FLOAT:
keyValue = lastRowInBatch.getFloat(primaryKeyColumn);
break;
case DOUBLE:
keyValue = lastRowInBatch.getDouble(primaryKeyColumn);
break;
default:
throw new RuntimeException("unsupported data type " + primaryKeyColumnType.getName());
}
return fetchKeyTokenFromDB(keyValue);
}
private Long fetchKeyTokenFromDB(Object keyValue)
{
fetchKeyStatement.bind(keyValue);
ResultSet rs = store.getSession().execute(fetchKeyStatement);
Long keyTokenValue = rs.one().getLong(0);
return keyTokenValue;
}
@Override
protected void emit(Object tuple)
{
outputPort.emit(tuple);
}
@Override
public void deactivate()
{
}
private static final Logger LOG = LoggerFactory.getLogger(CassandraPOJOInputOperator.class);
}
| |
/*
* Copyright 2013 Barzan Mozafari
*
* 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 dbseer.gui.panel;
import dbseer.comp.PredictionCenter;
import dbseer.gui.DBSeerConstants;
import dbseer.gui.DBSeerGUI;
import dbseer.gui.frame.DBSeerPredictionFrame;
import dbseer.gui.model.SharedComboBoxModel;
import dbseer.gui.user.DBSeerConfiguration;
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by dyoon on 5/8/15.
*/
public class DBSeerPerformancePredictionPanel extends JPanel implements ActionListener
{
private DBSeerWhatIfAnalysisPanel whatIfAnalysisPanel;
private DBSeerBottleneckAnalysisPanel bottleneckAnalysisPanel;
private DBSeerBlameAnalysisPanel blameAnalysisPanel;
private DBSeerThrottleAnalysisPanel throttlingAnalysisPanel;
private JComboBox trainConfigComboBox;
private JPanel tabbedPanePanel;
private JTabbedPane tabbedPane;
private JButton performAnalysisButton;
private JButton viewAnalysisChartButton;
private JButton cancelAnalysisButton;
private JTextArea answerTextArea;
private int lastChartType;
private PredictionCenter predictionCenter;
private boolean isAnalysisDone = false;
private SwingWorker<Void, Void> currentWorker;
public DBSeerPerformancePredictionPanel()
{
this.setLayout(new MigLayout("flowy, ins 0","[][grow]","[][fill,grow]"));
initialize();
}
private void initialize()
{
trainConfigComboBox = new JComboBox(new SharedComboBoxModel(DBSeerGUI.configs));
trainConfigComboBox.setBorder(BorderFactory.createTitledBorder("Choose a config"));
trainConfigComboBox.addActionListener(this);
tabbedPanePanel = new JPanel();
tabbedPanePanel.setLayout(new MigLayout("fill"));
tabbedPane = new JTabbedPane();
whatIfAnalysisPanel = new DBSeerWhatIfAnalysisPanel(this);
bottleneckAnalysisPanel = new DBSeerBottleneckAnalysisPanel();
blameAnalysisPanel = new DBSeerBlameAnalysisPanel();
throttlingAnalysisPanel = new DBSeerThrottleAnalysisPanel();
performAnalysisButton = new JButton("Run Analysis");
performAnalysisButton.addActionListener(this);
viewAnalysisChartButton = new JButton("View Analysis Chart");
viewAnalysisChartButton.addActionListener(this);
viewAnalysisChartButton.setEnabled(false);
cancelAnalysisButton = new JButton("Cancel Analysis");
cancelAnalysisButton.addActionListener(this);
cancelAnalysisButton.setEnabled(false);
answerTextArea = new JTextArea();
answerTextArea.setEditable(false);
answerTextArea.setLineWrap(true);
answerTextArea.setBorder(BorderFactory.createTitledBorder("Analysis Result"));
JScrollPane answerScrollPane = new JScrollPane(answerTextArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
answerScrollPane.setViewportView(answerTextArea);
answerScrollPane.setAutoscrolls(false);
tabbedPane.addTab("What-if Analysis", whatIfAnalysisPanel);
tabbedPane.addTab("Bottleneck Analysis", bottleneckAnalysisPanel);
tabbedPane.addTab("Blame Analysis", blameAnalysisPanel);
tabbedPane.addTab("Throttle Analysis", throttlingAnalysisPanel);
tabbedPanePanel.add(tabbedPane, "grow");
this.add(trainConfigComboBox, "growx, split 4");
this.add(performAnalysisButton, "growx");
this.add(viewAnalysisChartButton, "growx");
this.add(cancelAnalysisButton, "growx, wrap");
this.add(tabbedPanePanel, "growx");
this.add(answerScrollPane, "grow");
}
public DBSeerConfiguration getTrainConfig()
{
return (DBSeerConfiguration)trainConfigComboBox.getSelectedItem();
}
@Override
public void actionPerformed(ActionEvent e)
{
// perform analysis
if (e.getSource() == performAnalysisButton)
{
if (trainConfigComboBox.getSelectedItem() == null)
{
JOptionPane.showMessageDialog(DBSeerGUI.mainFrame, "Please select a config first.", "Warning",
JOptionPane.WARNING_MESSAGE);
return;
}
final DBSeerConfiguration trainConfig = (DBSeerConfiguration) trainConfigComboBox.getSelectedItem();
if (trainConfig.getDatasetCount() == 0)
{
JOptionPane.showMessageDialog(DBSeerGUI.mainFrame, "The selected train config does not include a dataset.", "Warning",
JOptionPane.WARNING_MESSAGE);
return;
}
if (trainConfig.isLive() && !DBSeerGUI.isLiveDataReady)
{
JOptionPane.showMessageDialog(DBSeerGUI.mainFrame, "It should be monitoring to perform predictions with live config.", "Warning",
JOptionPane.WARNING_MESSAGE);
return;
}
if (trainConfig.getDataset(0).getTransactionTypeNames().size() == 0)
{
JOptionPane.showMessageDialog(DBSeerGUI.mainFrame, "The dataset needs to have at least one transaction type enabled.", "Warning",
JOptionPane.WARNING_MESSAGE);
return;
}
if (tabbedPane.getSelectedIndex() == DBSeerConstants.ANALYSIS_THROTTLING)
{
if (throttlingAnalysisPanel.getTargetLatency() == 0)
{
JOptionPane.showMessageDialog(DBSeerGUI.mainFrame, "Latency must be greater than zero.", "Warning",
JOptionPane.WARNING_MESSAGE);
return;
}
}
isAnalysisDone = false;
answerTextArea.setText("");
cancelAnalysisButton.setEnabled(true);
if (tabbedPane.getSelectedIndex() == DBSeerConstants.ANALYSIS_WHATIF)
{
int idx = 0;
String predictionString = "";
for (String target : DBSeerWhatIfAnalysisPanel.predictionTargets)
{
if (target.equalsIgnoreCase(whatIfAnalysisPanel.getPredictionTarget()))
{
predictionString = DBSeerWhatIfAnalysisPanel.actualPredictions[idx];
break;
}
++idx;
}
final PredictionCenter center = new PredictionCenter(DBSeerGUI.runner,
predictionString, DBSeerGUI.userSettings.getDBSeerRootPath(), true);
center.setPredictionDescription("What-if Analysis");
final int targetIndex = whatIfAnalysisPanel.getSelectedPredictionTargetIndex();
DBSeerGUI.status.setText("Running What-if Analysis...");
final SwingWorker<Void, Void> worker = performAnalysis(center, DBSeerConstants.ANALYSIS_WHATIF, DBSeerConstants.CHART_XYLINE);
SwingWorker<Void, Void> printWorker = new SwingWorker<Void, Void>()
{
@Override
protected Void doInBackground() throws Exception
{
while (!worker.isDone())
{
Thread.sleep(250);
}
return null;
}
@Override
protected void done()
{
if (!worker.isCancelled() && isAnalysisDone)
{
printWhatIfAnalysisResult(center, trainConfig, targetIndex);
DBSeerGUI.status.setText("What-if Analysis Completed.");
}
else
{
DBSeerGUI.status.setText("What-if Analysis Failed.");
}
cancelAnalysisButton.setEnabled(false);
}
};
printWorker.execute();
}
else if (tabbedPane.getSelectedIndex() == DBSeerConstants.ANALYSIS_BOTTLENECK)
{
int chartType = DBSeerConstants.CHART_XYLINE;
final int selectedIndex = bottleneckAnalysisPanel.getSelectedQuestion();
final PredictionCenter center = new PredictionCenter(DBSeerGUI.runner,
DBSeerBottleneckAnalysisPanel.actualFunctions[selectedIndex],
DBSeerGUI.userSettings.getDBSeerRootPath(), true);
center.setPredictionDescription("Bottleneck Analysis");
DBSeerGUI.status.setText("Running Bottleneck Analysis...");
if (selectedIndex == DBSeerBottleneckAnalysisPanel.BOTTLENECK_RESOURCE)
{
chartType = DBSeerConstants.CHART_BAR;
}
final SwingWorker<Void, Void> worker = performAnalysis(center, DBSeerConstants.ANALYSIS_BOTTLENECK, chartType);
SwingWorker<Void, Void> printWorker = new SwingWorker<Void, Void>()
{
@Override
protected Void doInBackground() throws Exception
{
while (!worker.isDone())
{
Thread.sleep(250);
}
return null;
}
@Override
protected void done()
{
if (!worker.isCancelled() && isAnalysisDone)
{
printBottleneckAnalysisResult(center, trainConfig, selectedIndex);
DBSeerGUI.status.setText("Bottleneck Analysis Completed.");
}
else
{
DBSeerGUI.status.setText("Bottleneck Analysis Failed.");
}
cancelAnalysisButton.setEnabled(false);
}
};
printWorker.execute();
}
else if (tabbedPane.getSelectedIndex() == DBSeerConstants.ANALYSIS_BLAME)
{
final int selectedIndex = blameAnalysisPanel.getSelectedIndex();
final PredictionCenter center = new PredictionCenter(DBSeerGUI.runner,
blameAnalysisPanel.getAnalysisFunction(), DBSeerGUI.userSettings.getDBSeerRootPath(), true);
center.setPredictionDescription("Blame Analysis");
DBSeerGUI.status.setText("Running Blame Analysis...");
final SwingWorker<Void, Void> worker = performAnalysis(center, DBSeerConstants.ANALYSIS_BLAME, DBSeerConstants.CHART_XYLINE);
SwingWorker<Void, Void> printWorker = new SwingWorker<Void, Void>()
{
@Override
protected Void doInBackground() throws Exception
{
while (!worker.isDone())
{
Thread.sleep(250);
}
return null;
}
@Override
protected void done()
{
if (!worker.isCancelled() && isAnalysisDone)
{
printBlameAnalysisResult(center, trainConfig, selectedIndex);
DBSeerGUI.status.setText("Blame Analysis Completed.");
}
else
{
DBSeerGUI.status.setText("Blame Analysis Failed.");
}
cancelAnalysisButton.setEnabled(false);
}
};
printWorker.execute();
}
else if (tabbedPane.getSelectedIndex() == DBSeerConstants.ANALYSIS_THROTTLING)
{
final PredictionCenter center = new PredictionCenter(DBSeerGUI.runner,
"ThrottlingAnalysis", DBSeerGUI.userSettings.getDBSeerRootPath(), true);
final int throttleType = throttlingAnalysisPanel.getThrottleType();
center.setPredictionDescription("Throttle Analysis");
center.setThrottleLatencyType(throttlingAnalysisPanel.getLatencyType());
if (throttleType == DBSeerThrottleAnalysisPanel.THROTTLE_INDIVIDUAL)
{
center.setThrottleIndividualTransactions(true);
center.setThrottlePenalty(throttlingAnalysisPanel.getPenaltyMatrix());
}
else if (throttleType == DBSeerThrottleAnalysisPanel.THROTTLE_OVERALL)
{
center.setThrottleIndividualTransactions(false);
}
DBSeerGUI.status.setText("Running Throttle Analysis...");
final SwingWorker<Void, Void> worker = performAnalysis(center, DBSeerConstants.ANALYSIS_THROTTLING, DBSeerConstants.CHART_XYLINE);
SwingWorker<Void, Void> printWorker = new SwingWorker<Void, Void>()
{
@Override
protected Void doInBackground() throws Exception
{
while (!worker.isDone())
{
Thread.sleep(250);
}
return null;
}
@Override
protected void done()
{
if (!worker.isCancelled() && isAnalysisDone)
{
printThrottlingAnalysisResult(center, trainConfig, throttleType);
DBSeerGUI.status.setText("Throttle Analysis Completed.");
}
else
{
DBSeerGUI.status.setText("Throttle Analysis Failed.");
}
cancelAnalysisButton.setEnabled(false);
}
};
printWorker.execute();
}
}
else if (e.getSource() == viewAnalysisChartButton)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
if (predictionCenter != null)
{
DBSeerGUI.status.setText("");
DBSeerPredictionFrame predictionFrame = new DBSeerPredictionFrame(predictionCenter, lastChartType);
predictionFrame.pack();
predictionFrame.setVisible(true);
}
}
});
}
else if (e.getSource() == trainConfigComboBox)
{
DBSeerConfiguration trainConfig = (DBSeerConfiguration)trainConfigComboBox.getSelectedItem();
if (trainConfig != null)
{
whatIfAnalysisPanel.updateTransactionType(trainConfig);
throttlingAnalysisPanel.updateTransactionType(trainConfig);
throttlingAnalysisPanel.updatePenaltyPanel(trainConfig);
}
}
else if (e.getSource() == cancelAnalysisButton)
{
if (currentWorker != null)
{
DBSeerGUI.status.setText("Cancelling Analysis Process. This may take a few minutes.");
final JButton performAnalysis = this.performAnalysisButton;
final JComboBox trainConfigComboBox = this.trainConfigComboBox;
final DBSeerConfiguration trainConfig = (DBSeerConfiguration) trainConfigComboBox.getSelectedItem();
currentWorker.cancel(true);
trainConfig.setReinitialize();
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
trainConfigComboBox.setEnabled(false);
performAnalysis.setEnabled(false);
DBSeerGUI.mainFrame.getMainTabbedPane().setEnabled(false);
}
});
SwingWorker<Void, Void> cancelWorker = new SwingWorker<Void, Void>()
{
@Override
protected Void doInBackground() throws Exception
{
DBSeerGUI.isProxyRenewing = true;
DBSeerGUI.resetStatRunner();
DBSeerGUI.isProxyRenewing = false;
return null;
}
@Override
protected void done()
{
performAnalysis.setEnabled(true);
trainConfigComboBox.setEnabled(true);
DBSeerGUI.mainFrame.getMainTabbedPane().setEnabled(true);
DBSeerGUI.status.setText("Analysis has been cancelled successfully.");
}
};
cancelWorker.execute();
}
}
}
private void printBlameAnalysisResult(PredictionCenter center, DBSeerConfiguration config, int targetIndex)
{
switch (targetIndex)
{
case DBSeerBlameAnalysisPanel.TARGET_CPU:
{
center.printBlameAnalysisCPUResult(answerTextArea, config);
break;
}
case DBSeerBlameAnalysisPanel.TARGET_IO:
{
center.printBlameAnalysisIOResult(answerTextArea, config);
break;
}
case DBSeerBlameAnalysisPanel.TARGET_LOCK:
{
center.printBlameAnalysisLockResult(answerTextArea, config);
break;
}
default:
break;
}
}
private void printBottleneckAnalysisResult(PredictionCenter center, DBSeerConfiguration config, int targetIndex)
{
switch (targetIndex)
{
case DBSeerBottleneckAnalysisPanel.BOTTLENECK_MAX_THROUGHPUT:
{
center.printBottleneckAnalysisMaxThroughputResult(answerTextArea, config);
break;
}
case DBSeerBottleneckAnalysisPanel.BOTTLENECK_RESOURCE:
{
center.printBottleneckAnalysisResourceResult(answerTextArea, config);
break;
}
default:
break;
}
}
private void printWhatIfAnalysisResult(PredictionCenter center, DBSeerConfiguration config, int targetIndex)
{
switch(targetIndex)
{
case DBSeerWhatIfAnalysisPanel.TARGET_LATENCY:
{
center.printWhatIfAnalysisLatencyResult(answerTextArea, config);
break;
}
case DBSeerWhatIfAnalysisPanel.TARGET_IO:
{
center.printWhatIfAnalysisIOResult(answerTextArea, config);
break;
}
case DBSeerWhatIfAnalysisPanel.TARGET_CPU:
{
center.printWhatIfAnalysisCPUResult(answerTextArea, config);
break;
}
case DBSeerWhatIfAnalysisPanel.TARGET_FLUSH_RATE:
{
center.printWhatIfAnalysisFlushRateResult(answerTextArea, config);
break;
}
default:
break;
}
}
private void printThrottlingAnalysisResult(PredictionCenter center, DBSeerConfiguration config, int throttleType)
{
if (throttleType == DBSeerThrottleAnalysisPanel.THROTTLE_OVERALL)
{
center.printThrottlingAnalysisOverallResult(answerTextArea, config);
}
else if (throttleType == DBSeerThrottleAnalysisPanel.THROTTLE_INDIVIDUAL)
{
center.printThrottlingAnalysisIndividualResult(answerTextArea, config);
}
}
public JButton getPerformAnalysisButton()
{
return performAnalysisButton;
}
private SwingWorker<Void, Void> performAnalysis(PredictionCenter center, final int analyisType, int chartType)
{
trainConfigComboBox.setEnabled(false);
performAnalysisButton.setEnabled(false);
viewAnalysisChartButton.setEnabled(false);
final int cType = chartType;
final PredictionCenter pc = center;
final DBSeerConfiguration trainConfig = (DBSeerConfiguration) trainConfigComboBox.getSelectedItem();
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>()
{
boolean isRun = false;
@Override
protected Void doInBackground() throws Exception
{
if (!trainConfig.initialize())
{
return null;
}
pc.setTestMode(DBSeerConstants.TEST_MODE_MIXTURE_TPS);
pc.setTrainConfig((DBSeerConfiguration) trainConfigComboBox.getSelectedItem());
double workloadRatio = 1.0;
if (tabbedPane.getSelectedIndex() == DBSeerConstants.ANALYSIS_WHATIF)
{
workloadRatio = whatIfAnalysisPanel.getWorkloadRatio() / 100.0;
}
else if (tabbedPane.getSelectedIndex() == DBSeerConstants.ANALYSIS_THROTTLING)
{
pc.setThrottleTargetLatency(throttlingAnalysisPanel.getTargetLatency());
pc.setThrottleTargetTransactionIndex(throttlingAnalysisPanel.getTransactionTypeIndex());
}
pc.setTestWorkloadRatio(workloadRatio);
pc.setTestManualMinTPS(trainConfig.getMinTPS() * workloadRatio);
pc.setTestManualMaxTPS(trainConfig.getMaxTPS() * workloadRatio);
pc.setTestMixture(trainConfig.getTransactionMixString());
if (tabbedPane.getSelectedIndex() == DBSeerConstants.ANALYSIS_WHATIF &&
whatIfAnalysisPanel.getMixtureType() == DBSeerWhatIfAnalysisPanel.MIXTURE_DIFFERENT)
{
int targetTransaction = whatIfAnalysisPanel.getTransactionType();
int ratioOption = whatIfAnalysisPanel.getMixtureRatio();
String mixtureString = "[";
double[] originalMix = trainConfig.getTransactionMix();
int index = 0;
for (double m : originalMix)
{
// Only include target transaction
if (ratioOption == whatIfAnalysisPanel.RATIO_ONLY)
{
if (index != targetTransaction)
{
mixtureString += "0";
}
else
{
mixtureString += m;
}
}
else
{
if (index == targetTransaction)
{
mixtureString += (m * DBSeerWhatIfAnalysisPanel.ratios[ratioOption]);
}
else
{
mixtureString += m;
}
}
++index;
mixtureString += " ";
}
mixtureString += "]";
pc.setTestMixture(mixtureString);
}
pc.setIoConfiguration(trainConfig.getIoConfiguration());
pc.setLockConfiguration(trainConfig.getLockConfiguration());
if (pc.initialize())
{
isRun = pc.run();
}
return null;
}
@Override
protected void done()
{
if (isRun)
{
predictionCenter = pc;
lastChartType = cType;
viewAnalysisChartButton.setEnabled(true);
isAnalysisDone = true;
}
performAnalysisButton.setEnabled(true);
trainConfigComboBox.setEnabled(true);
}
};
currentWorker = worker;
worker.execute();
return worker;
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.datatorrent.lib.testbench;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import com.datatorrent.api.Context.OperatorContext;
import com.datatorrent.api.DefaultInputPort;
import com.datatorrent.api.DefaultOutputPort;
import com.datatorrent.common.util.BaseOperator;
/**
* An implementation of BaseOperator that creates a load with pair of keys by taking in an input stream event and adding to incoming keys
* to create a new tuple that is emitted on output port data.
* <p>
* Takes a input stream event and adds to incoming keys to create a new tuple that is emitted on output port data.
* <br>
* Examples of pairs include<br>
* publisher,advertizer<br>
* automobile,model<br>
* <br>
* The keys to be inserted are given by the property <b>keys</b>. Users can choose to insert their
* own values via property <b>values</b>. Insertion can be done as replacement, addition, multiply,
* or append (append is not yet supported)<br>. For each incoming key users can provide an insertion
* probability for the insert keys. This allows for randomization of the insert key choice<br><br>
* <br>
* <b>Tuple Schema</b>: Each tuple is HashMap<String, Double> on both the ports. Currently other schemas are not supported<br>
* <b>Port Interface</b><br>
* <b>data</b>: emits HashMap<String,Double><br>
* <b>event</b>: expects HashMap<String,Double><br>
* <br>
* <b>Properties</b>:
* None<br>
* <br>
* Compile time checks are:<br>
* <b>keys</b> cannot be empty<br>
* <b>values</b> if specified has to be comma separated doubles and their number must match the number of keys<br>
* <b>weights</b> if specified the format has to be "key1:val1,val2,...,valn;key2:val1,val2,...,valn;...", where n has to be
* number of keys in parameter <b>keys</b>. If not specified all weights are equal<br>
* <br>
* <br>
* <b>Benchmarks</b>: This node has been benchmarked at over 5 million tuples/second in local/inline mode<br>
* <p>
* @displayName Event Classifier
* @category Test Bench
* @tags hashmap,classification
* @since 0.3.2
*/
public class EventClassifier extends BaseOperator
{
public final transient DefaultInputPort<HashMap<String, Double>> event = new DefaultInputPort<HashMap<String, Double>>()
{
@Override
public void process(HashMap<String, Double> tuple)
{
for (Map.Entry<String, Double> e : tuple.entrySet()) {
String inkey = e.getKey();
ArrayList<Integer> alist = null;
if (inkeys != null) {
alist = inkeys.get(e.getKey());
}
if (alist == null) {
alist = noweight;
}
// now alist are the weights
int rval = random.nextInt(alist.get(alist.size() - 1));
int j = 0;
int wval = 0;
for (Integer ew : alist) {
wval += ew.intValue();
if (wval >= rval) {
break;
}
j++;
}
HashMap<String, Double> otuple = new HashMap<String, Double>(1);
String key = wtostr_index.get(j); // the key
Double keyval = null;
if (hasvalues) {
if (voper == value_operation.VOPR_REPLACE) { // replace the incoming value
keyval = keys.get(key);
} else if (voper == value_operation.VOPR_ADD) {
keyval = keys.get(key) + e.getValue();
} else if (voper == value_operation.VOPR_MULT) {
keyval = keys.get(key) * e.getValue();
} else if (voper == value_operation.VOPR_APPEND) { // not supported yet
keyval = keys.get(key);
}
} else { // pass on the value from incoming tuple
keyval = e.getValue();
}
otuple.put(key + "," + inkey, keyval);
data.emit(otuple);
}
}
};
/**
* Output data port that emits a hashmap of <string,double>.
*/
public final transient DefaultOutputPort<HashMap<String, Double>> data = new DefaultOutputPort<HashMap<String, Double>>();
HashMap<String, Double> keys = new HashMap<String, Double>();
HashMap<Integer, String> wtostr_index = new HashMap<Integer, String>();
// One of inkeys (Key to weight hash) or noweight (even weight) would be not null
HashMap<String, ArrayList<Integer>> inkeys = null;
ArrayList<Integer> noweight = null;
boolean hasvalues = false;
int total_weight = 0;
private Random random = new Random();
enum value_operation
{
VOPR_REPLACE, VOPR_ADD, VOPR_MULT, VOPR_APPEND
}
value_operation voper = value_operation.VOPR_REPLACE;
public void setOperationReplace()
{
voper = value_operation.VOPR_REPLACE;
}
public void setOperationAdd()
{
voper = value_operation.VOPR_ADD;
}
public void setOperationMult()
{
voper = value_operation.VOPR_MULT;
}
public void setOperationAppend()
{
voper = value_operation.VOPR_MULT;
}
public void setKeyWeights(HashMap<String, ArrayList<Integer>> map)
{
if (inkeys == null) {
inkeys = new HashMap<String, ArrayList<Integer>>();
}
for (Map.Entry<String, ArrayList<Integer>> e: map.entrySet()) {
inkeys.put(e.getKey(), e.getValue());
}
for (Map.Entry<String, ArrayList<Integer>> e: inkeys.entrySet()) {
ArrayList<Integer> list = e.getValue();
int total = 0;
for (Integer i: list) {
total += i.intValue();
}
list.add(total);
}
}
@Override
public void setup(OperatorContext context)
{
noweight = new ArrayList<Integer>();
for (int i = 0; i < keys.size(); i++) {
noweight.add(100); // Even distribution
total_weight += 100;
}
noweight.add(total_weight);
}
public void setKeyMap(HashMap<String,Double> map)
{
int i = 0;
// First load up the keys and the index hash (wtostr_index) for randomization to work
boolean foundvalue = false;
for (Map.Entry<String, Double> e: map.entrySet()) {
keys.put(e.getKey(), e.getValue());
foundvalue = foundvalue || (e.getValue() != null);
wtostr_index.put(i, e.getKey());
i += 1;
}
hasvalues = foundvalue;
}
}
| |
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.widgets;
import android.content.Context;
import android.util.TypedValue;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import org.javarosa.core.model.SelectChoice;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.SelectMultiData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.form.api.FormEntryCaption;
import org.javarosa.form.api.FormEntryPrompt;
import org.javarosa.xpath.expr.XPathFuncExpr;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.external.ExternalDataUtil;
import org.odk.collect.android.external.ExternalSelectChoice;
import org.odk.collect.android.views.MediaLayout;
import java.util.ArrayList;
import java.util.Vector;
/**
* SelctMultiWidget handles multiple selection fields using checkboxes.
*
* @author Carl Hartung (carlhartung@gmail.com)
* @author Yaw Anokwa (yanokwa@gmail.com)
*/
public class SelectMultiWidget extends QuestionWidget {
private boolean mCheckboxInit = true;
Vector<SelectChoice> mItems;
private ArrayList<CheckBox> mCheckboxes;
@SuppressWarnings("unchecked")
public SelectMultiWidget(Context context, FormEntryPrompt prompt) {
super(context, prompt);
mPrompt = prompt;
mCheckboxes = new ArrayList<CheckBox>();
// SurveyCTO-added support for dynamic select content (from .csv files)
XPathFuncExpr xPathFuncExpr = ExternalDataUtil.getSearchXPathExpression(prompt.getAppearanceHint());
if (xPathFuncExpr != null) {
mItems = ExternalDataUtil.populateExternalChoices(prompt, xPathFuncExpr);
} else {
mItems = prompt.getSelectChoices();
}
setOrientation(LinearLayout.VERTICAL);
Vector<Selection> ve = new Vector<Selection>();
if (prompt.getAnswerValue() != null) {
ve = (Vector<Selection>) prompt.getAnswerValue().getValue();
}
if (mItems != null) {
for (int i = 0; i < mItems.size(); i++) {
// no checkbox group so id by answer + offset
CheckBox c = new CheckBox(getContext());
c.setTag(Integer.valueOf(i));
c.setId(QuestionWidget.newUniqueId());
c.setText(prompt.getSelectChoiceText(mItems.get(i)));
c.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
c.setFocusable(!prompt.isReadOnly());
c.setEnabled(!prompt.isReadOnly());
for (int vi = 0; vi < ve.size(); vi++) {
// match based on value, not key
if (mItems.get(i).getValue().equals(ve.elementAt(vi).getValue())) {
c.setChecked(true);
break;
}
}
mCheckboxes.add(c);
// when clicked, check for readonly before toggling
c.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!mCheckboxInit && mPrompt.isReadOnly()) {
if (buttonView.isChecked()) {
buttonView.setChecked(false);
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.deselect",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
} else {
buttonView.setChecked(true);
Collect.getInstance().getActivityLogger().logInstanceAction(this, "onItemClick.select",
mItems.get((Integer)buttonView.getTag()).getValue(), mPrompt.getIndex());
}
}
}
});
String audioURI = null;
audioURI =
prompt.getSpecialFormSelectChoiceText(mItems.get(i),
FormEntryCaption.TEXT_FORM_AUDIO);
String imageURI;
if (mItems.get(i) instanceof ExternalSelectChoice) {
imageURI = ((ExternalSelectChoice) mItems.get(i)).getImage();
} else {
imageURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), FormEntryCaption.TEXT_FORM_IMAGE);
}
String videoURI = null;
videoURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), "video");
String bigImageURI = null;
bigImageURI = prompt.getSpecialFormSelectChoiceText(mItems.get(i), "big-image");
MediaLayout mediaLayout = new MediaLayout(getContext());
mediaLayout.setAVT(prompt.getIndex(), "." + Integer.toString(i), c, audioURI, imageURI, videoURI, bigImageURI);
addView(mediaLayout);
// Last, add the dividing line between elements (except for the last element)
ImageView divider = new ImageView(getContext());
divider.setBackgroundResource(android.R.drawable.divider_horizontal_bright);
if (i != mItems.size() - 1) {
addView(divider);
}
}
}
mCheckboxInit = false;
}
@Override
public void clearAnswer() {
for ( CheckBox c : mCheckboxes ) {
if ( c.isChecked() ) {
c.setChecked(false);
}
}
}
@Override
public IAnswerData getAnswer() {
Vector<Selection> vc = new Vector<Selection>();
for ( int i = 0; i < mCheckboxes.size() ; ++i ) {
CheckBox c = mCheckboxes.get(i);
if ( c.isChecked() ) {
vc.add(new Selection(mItems.get(i)));
}
}
if (vc.size() == 0) {
return null;
} else {
return new SelectMultiData(vc);
}
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
for (CheckBox c : mCheckboxes) {
c.setOnLongClickListener(l);
}
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
for (CheckBox c : mCheckboxes) {
c.cancelLongPress();
}
}
}
| |
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.kie.workbench.common.stunner.client.widgets.presenters.session.impl;
import java.lang.annotation.Annotation;
import java.util.Optional;
import java.util.function.Predicate;
import javax.enterprise.event.Event;
import org.kie.workbench.common.stunner.client.widgets.event.SessionFocusedEvent;
import org.kie.workbench.common.stunner.client.widgets.notification.CommandNotification;
import org.kie.workbench.common.stunner.client.widgets.notification.Notification;
import org.kie.workbench.common.stunner.client.widgets.notification.NotificationContext;
import org.kie.workbench.common.stunner.client.widgets.notification.NotificationsObserver;
import org.kie.workbench.common.stunner.client.widgets.notification.ValidationFailedNotification;
import org.kie.workbench.common.stunner.client.widgets.palette.DefaultPaletteFactory;
import org.kie.workbench.common.stunner.client.widgets.palette.PaletteWidget;
import org.kie.workbench.common.stunner.client.widgets.presenters.session.SessionPresenter;
import org.kie.workbench.common.stunner.client.widgets.presenters.session.SessionViewer;
import org.kie.workbench.common.stunner.client.widgets.toolbar.Toolbar;
import org.kie.workbench.common.stunner.core.client.api.SessionManager;
import org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler;
import org.kie.workbench.common.stunner.core.client.components.palette.PaletteDefinition;
import org.kie.workbench.common.stunner.core.client.preferences.StunnerPreferencesRegistries;
import org.kie.workbench.common.stunner.core.client.service.ClientRuntimeError;
import org.kie.workbench.common.stunner.core.client.session.impl.AbstractSession;
import org.kie.workbench.common.stunner.core.diagram.Diagram;
import org.kie.workbench.common.stunner.core.util.DefinitionUtils;
public abstract class AbstractSessionPresenter<D extends Diagram, H extends AbstractCanvasHandler,
S extends AbstractSession, E extends SessionViewer<S, H, D>>
implements SessionPresenter<S, H, D> {
private final DefinitionUtils definitionUtils;
private final SessionManager sessionManager;
private final DefaultPaletteFactory<H> paletteFactory;
private final SessionPresenter.View view;
private final NotificationsObserver notificationsObserver;
private final Event<SessionFocusedEvent> sessionFocusedEvent;
private final StunnerPreferencesRegistries preferencesRegistries;
private D diagram;
private Toolbar<S> toolbar;
private PaletteWidget<PaletteDefinition> palette;
private boolean hasToolbar = false;
private boolean hasPalette = false;
private Optional<Predicate<Notification.Type>> typePredicate;
@SuppressWarnings("unchecked")
protected AbstractSessionPresenter(final DefinitionUtils definitionUtils,
final SessionManager sessionManager,
final SessionPresenter.View view,
final DefaultPaletteFactory<H> paletteFactory,
final NotificationsObserver notificationsObserver,
final Event<SessionFocusedEvent> sessionFocusedEvent,
final StunnerPreferencesRegistries preferencesRegistries) {
this.definitionUtils = definitionUtils;
this.sessionManager = sessionManager;
this.paletteFactory = paletteFactory;
this.notificationsObserver = notificationsObserver;
this.sessionFocusedEvent = sessionFocusedEvent;
this.view = view;
this.preferencesRegistries = preferencesRegistries;
this.hasToolbar = true;
this.hasPalette = true;
this.typePredicate = Optional.empty();
}
public abstract E getDisplayer();
protected abstract Class<? extends AbstractSession> getSessionType();
protected abstract Toolbar<S> newToolbar(Annotation qualifier);
protected abstract void destroyToolbarInstace(Toolbar<S> toolbar);
@Override
@SuppressWarnings("unchecked")
public void open(final D diagram,
final SessionPresenterCallback<D> callback) {
this.diagram = diagram;
notificationsObserver.onCommandExecutionFailed(this::showCommandError);
notificationsObserver.onValidationSuccess(this::showNotificationMessage);
notificationsObserver.onValidationFailed(this::showValidationError);
sessionManager.newSession(diagram.getMetadata(),
getSessionType(),
session -> open((S) session,
callback));
}
public void open(final S session,
final SessionPresenterCallback<D> callback) {
beforeOpen(session);
getDisplayer().open(session,
new SessionViewer.SessionViewerCallback<D>() {
@Override
public void afterCanvasInitialized() {
callback.afterCanvasInitialized();
sessionManager.open(session);
callback.afterSessionOpened();
}
@Override
public void onSuccess() {
onSessionOpened(session);
callback.onSuccess();
}
@Override
public void onError(final ClientRuntimeError error) {
AbstractSessionPresenter.this.showError(error);
callback.onError(error);
}
});
}
public void open(final S session,
final int width,
final int height,
final SessionPresenterCallback<D> callback) {
beforeOpen(session);
getDisplayer().open(session,
width,
height,
new SessionViewer.SessionViewerCallback<D>() {
@Override
public void afterCanvasInitialized() {
callback.afterCanvasInitialized();
sessionManager.open(session);
callback.afterSessionOpened();
}
@Override
public void onSuccess() {
onSessionOpened(session);
callback.onSuccess();
}
@Override
public void onError(final ClientRuntimeError error) {
AbstractSessionPresenter.this.showError(error);
callback.onError(error);
}
});
}
@Override
public SessionPresenter<S, H, D> withToolbar(final boolean hasToolbar) {
this.hasToolbar = hasToolbar;
return this;
}
@Override
public SessionPresenter<S, H, D> withPalette(final boolean hasPalette) {
this.hasPalette = hasPalette;
return this;
}
@Override
public SessionPresenter<S, H, D> displayNotifications(final Predicate<Notification.Type> typePredicate) {
this.typePredicate = Optional.of(typePredicate);
return this;
}
@Override
public SessionPresenter<S, H, D> hideNotifications() {
typePredicate = Optional.empty();
return this;
}
@Override
public void focus() {
getSession().ifPresent(sessionManager::open);
getSession().ifPresent(s -> sessionFocusedEvent.fire(new SessionFocusedEvent(s)));
}
@Override
public void lostFocus() {
}
public void scale(final int width,
final int height) {
getDisplayer().scale(width,
height);
}
public void clear() {
if (null != palette) {
palette.unbind();
}
if (null != toolbar) {
destroyToolbar();
}
getDisplayer().clear();
diagram = null;
}
@Override
public void destroy() {
destroyToolbar();
destroyPalette();
getSession().ifPresent(sessionManager::destroy);
getDisplayer().destroy();
getView().destroy();
diagram = null;
}
public S getInstance() {
return getDisplayer().getInstance();
}
public Optional<S> getSession() {
return Optional.ofNullable(getInstance());
}
@Override
public Toolbar<S> getToolbar() {
return toolbar;
}
@Override
public PaletteWidget<PaletteDefinition> getPalette() {
return palette;
}
@Override
public View getView() {
return view;
}
public H getHandler() {
return getDisplayer().getHandler();
}
protected D getDiagram() {
return diagram;
}
protected void beforeOpen(final S item) {
getView().showLoading(true);
}
@SuppressWarnings("unchecked")
protected void onSessionOpened(final S session) {
destroyToolbar();
destroyPalette();
initToolbar(session);
initPalette(session);
getView().setCanvasWidget(getDisplayer().getView());
getView().showLoading(false);
}
@SuppressWarnings("unchecked")
private void initToolbar(final S session) {
if (hasToolbar) {
final Annotation qualifier =
definitionUtils.getQualifier(session.getCanvasHandler().getDiagram().getMetadata().getDefinitionSetId());
toolbar = newToolbar(qualifier);
if (null != toolbar) {
toolbar.load(session);
}
getView().setToolbarWidget(toolbar.getView());
}
}
@SuppressWarnings("unchecked")
private void initPalette(final S session) {
if (hasPalette) {
palette = (PaletteWidget<PaletteDefinition>) buildPalette(session);
if (null != palette) {
getView().setPaletteWidget(palette);
}
}
}
public void refresh() {
destroyPalette();
getSession().ifPresent(this::initPalette);
}
private void showMessage(final String message) {
if (isDisplayNotifications()) {
getView().showMessage(message);
}
}
private void showWarning(final String error) {
if (isDisplayErrors()) {
getView().showWarning(error);
}
}
private void showError(final String message) {
if (isDisplayErrors()) {
getView().showError(message);
}
}
private void showError(final ClientRuntimeError error) {
if (isDisplayErrors()) {
getView().showLoading(false);
getView().showError(error.getMessage());
}
}
@SuppressWarnings("unchecked")
private PaletteWidget<? extends PaletteDefinition> buildPalette(final S session) {
if (null != paletteFactory) {
return paletteFactory.newPalette((H) session.getCanvasHandler());
}
return null;
}
private void destroyToolbar() {
if (null != toolbar) {
toolbar.destroy();
destroyToolbarInstace(toolbar);
toolbar = null;
}
}
private void destroyPalette() {
if (null != palette) {
palette.destroy();
palette = null;
}
}
private void showNotificationMessage(final Notification notification) {
if (isThisContext(notification)) {
showMessage(notification.getMessage());
}
}
private void showCommandError(final CommandNotification notification) {
if (isThisContext(notification)) {
showError(notification.getMessage());
}
}
private void showValidationError(final ValidationFailedNotification notification) {
if (isThisContext(notification)) {
if (Notification.Type.ERROR.equals(notification.getType())) {
showError(notification.getMessage());
} else {
showWarning(notification.getMessage());
}
}
}
private boolean isThisContext(final Notification notification) {
try {
final NotificationContext context = (NotificationContext) notification.getContext();
return null != getDiagram() && getDiagram().getName().equals(context.getDiagramName());
} catch (final ClassCastException e) {
return false;
}
}
private boolean isDisplayNotifications() {
return typePredicate
.orElse(t -> false)
.test(Notification.Type.INFO);
}
private boolean isDisplayErrors() {
return typePredicate
.orElse(t -> false)
.or(Notification.Type.WARNING::equals)
.test(Notification.Type.ERROR);
}
}
| |
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.jbpm.workbench.common.client.menu;
import java.util.Arrays;
import java.util.Collections;
import com.google.gwtmockito.GwtMockitoTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.server.controller.api.model.events.ServerTemplateUpdated;
import org.kie.server.controller.api.model.runtime.ServerInstanceKey;
import org.kie.server.controller.api.model.spec.ServerTemplate;
import org.kie.workbench.common.screens.server.management.service.SpecManagementService;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.uberfire.mocks.CallerMock;
import org.uberfire.mvp.ParameterizedCommand;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
@RunWith(GwtMockitoTestRunner.class)
public class ServerTemplateSelectorMenuBuilderTest {
@InjectMocks
ServerTemplateSelectorMenuBuilder serverTemplateSelectorMenuBuilder;
@Mock
ServerTemplateSelectorMenuBuilder.ServerTemplateSelectorView view;
private CallerMock<SpecManagementService> specManagementServiceCaller;
@Mock
private SpecManagementService specManagementService;
@Before
public void setup() {
specManagementServiceCaller = new CallerMock<SpecManagementService>(specManagementService);
serverTemplateSelectorMenuBuilder.setSpecManagementService(specManagementServiceCaller);
}
@Test
public void testAddServerTemplates() {
final String serverTemplateId = "id1";
final ServerTemplate st1 = new ServerTemplate(serverTemplateId,
"kie-server-template1");
st1.addServerInstance(new ServerInstanceKey());
final ServerTemplate st2 = new ServerTemplate("id2",
"kie-server-template2");
st2.addServerInstance(new ServerInstanceKey());
when(specManagementService.listServerTemplates()).thenReturn(Arrays.asList(st1,
st2));
when(view.getSelectedServerTemplate()).thenReturn(serverTemplateId);
serverTemplateSelectorMenuBuilder.init();
verify(specManagementService).listServerTemplates();
verify(view).setServerTemplateChangeHandler(any(ParameterizedCommand.class));
verify(view).removeAllServerTemplates();
verify(view).addServerTemplate(serverTemplateId);
verify(view).addServerTemplate("id2");
verify(view).getSelectedServerTemplate();
verify(view).selectServerTemplate(serverTemplateId);
verify(view).setVisible(true);
verifyNoMoreInteractions(view);
}
@Test
public void testAddServerTemplatesSelectedRemoved() {
final ServerTemplate st1 = new ServerTemplate("id1",
"kie-server-template1");
st1.addServerInstance(new ServerInstanceKey());
final ServerTemplate st2 = new ServerTemplate("id2",
"kie-server-template2");
st2.addServerInstance(new ServerInstanceKey());
when(specManagementService.listServerTemplates()).thenReturn(Arrays.asList(st1,
st2));
when(view.getSelectedServerTemplate()).thenReturn("id3");
serverTemplateSelectorMenuBuilder.init();
verify(specManagementService).listServerTemplates();
verify(view).setServerTemplateChangeHandler(any(ParameterizedCommand.class));
verify(view).removeAllServerTemplates();
verify(view).addServerTemplate("id1");
verify(view).addServerTemplate("id2");
verify(view).getSelectedServerTemplate();
verify(view).clearSelectedServerTemplate();
verify(view).setVisible(true);
verifyNoMoreInteractions(view);
}
@Test
public void testOneServerTemplate() {
final String serverTemplateId = "id1";
final ServerTemplate st1 = new ServerTemplate(serverTemplateId,
"kie-server-template1");
st1.addServerInstance(new ServerInstanceKey());
when(specManagementService.listServerTemplates()).thenReturn(Collections.singletonList(st1));
serverTemplateSelectorMenuBuilder.init();
verify(specManagementService).listServerTemplates();
verify(view).setServerTemplateChangeHandler(any(ParameterizedCommand.class));
verify(view).removeAllServerTemplates();
verify(view).addServerTemplate(serverTemplateId);
verify(view).selectServerTemplate(serverTemplateId);
verify(view).setVisible(false);
verifyNoMoreInteractions(view);
}
@Test
public void testServerTemplateSelected() {
final String serverTemplateId = "id1";
final ServerTemplate st1 = new ServerTemplate(serverTemplateId,
"kie-server-template1");
st1.addServerInstance(new ServerInstanceKey());
when(specManagementService.listServerTemplates()).thenReturn(Collections.singletonList(st1));
when(view.getSelectedServerTemplate()).thenReturn(serverTemplateId);
serverTemplateSelectorMenuBuilder.init();
verify(specManagementService).listServerTemplates();
verify(view).setServerTemplateChangeHandler(any(ParameterizedCommand.class));
verify(view).removeAllServerTemplates();
verify(view).addServerTemplate(serverTemplateId);
verify(view).selectServerTemplate(serverTemplateId);
verify(view).setVisible(false);
verifyNoMoreInteractions(view);
}
@Test
public void testServerTemplateSelectedRemoved() {
final String serverTemplateId = "id1";
final ServerTemplate st1 = new ServerTemplate(serverTemplateId,
"kie-server-template1");
st1.addServerInstance(new ServerInstanceKey());
when(specManagementService.listServerTemplates()).thenReturn(Collections.singletonList(st1));
when(view.getSelectedServerTemplate()).thenReturn("id2");
serverTemplateSelectorMenuBuilder.init();
verify(specManagementService).listServerTemplates();
verify(view).setServerTemplateChangeHandler(any(ParameterizedCommand.class));
verify(view).removeAllServerTemplates();
verify(view).addServerTemplate(serverTemplateId);
verify(view).selectServerTemplate(serverTemplateId);
verify(view).setVisible(false);
verifyNoMoreInteractions(view);
}
@Test
public void testServerTemplateUpdatedWithoutServerInstance() {
final String serverTemplateId = "id1";
final ServerTemplate st1 = new ServerTemplate(serverTemplateId,
"kie-server-template1");
when(specManagementService.listServerTemplates()).thenReturn(Collections.singletonList(st1));
serverTemplateSelectorMenuBuilder.onServerTemplateUpdated(new ServerTemplateUpdated(st1));
verify(specManagementService).listServerTemplates();
verify(view).removeAllServerTemplates();
verify(view,
never()).addServerTemplate(serverTemplateId);
verify(view).setVisible(false);
verify(view).getSelectedServerTemplate();
verifyNoMoreInteractions(view);
}
@Test
public void testServerTemplateUpdatedWithServerInstance() {
final String serverTemplateId = "id1";
final ServerTemplate st1 = new ServerTemplate(serverTemplateId,
"kie-server-template1");
st1.addServerInstance(new ServerInstanceKey());
when(specManagementService.listServerTemplates()).thenReturn(Collections.singletonList(st1));
serverTemplateSelectorMenuBuilder.onServerTemplateUpdated(new ServerTemplateUpdated(st1));
verifyNoMoreInteractions(view);
}
}
| |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tmf.org.dsmapi.catalog.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.codehaus.jackson.node.ObjectNode;
import tmf.org.dsmapi.catalog.Price;
import tmf.org.dsmapi.catalog.RefInfo;
import tmf.org.dsmapi.catalog.ProductOffering;
import tmf.org.dsmapi.catalog.ProductOfferingPrice;
import tmf.org.dsmapi.catalog.Report;
import tmf.org.dsmapi.catalog.TimeRange;
import tmf.org.dsmapi.commons.exceptions.BadUsageException;
/**
*
* @author pierregauthier
*/
@Stateless
@Path("tmf.org.dsmapi.catalog.productoffering")
public class ProductOfferingFacadeREST {
@EJB
ProductOfferingFacade manager;
public ProductOfferingFacadeREST() {
}
@POST
@Consumes({"application/json"})
@Produces({"application/json"})
public Response create(ProductOffering entity) {
entity.setId(null);
manager.create(entity);
Response response = Response.ok(entity).build();
return response;
}
@PUT
@Path("{id}")
@Consumes({"application/json"})
@Produces({"application/json"})
public Response edit(@PathParam("id") String id, ProductOffering entity) {
Response response = null;
ProductOffering productOffering = manager.find(id);
if (productOffering != null) {
// 200
entity.setId(id);
manager.edit(entity);
response = Response.ok(entity).build();
} else {
// 404 not found
response = Response.status(Response.Status.NOT_FOUND).build();
}
return response;
}
@GET
@Produces({"application/json"})
public Response findByCriteriaWithFields(@Context UriInfo info) throws BadUsageException {
// search criteria
MultivaluedMap<String, String> criteria = info.getQueryParameters();
// fields to filter view
Set<String> fieldSet = FacadeRestUtil.getFieldSet(criteria);
Set<ProductOffering> resultList = findByCriteria(criteria);
Response response;
if (fieldSet.isEmpty() || fieldSet.contains(FacadeRestUtil.ALL_FIELDS)) {
response = Response.ok(resultList).build();
} else {
fieldSet.add(FacadeRestUtil.ID_FIELD);
List<ObjectNode> nodeList = FacadeRestUtil.createNodeListViewWithFields(resultList, fieldSet);
response = Response.ok(nodeList).build();
}
return response;
/*
List<TroubleTicket> tickets;
if (queryParameters != null && !queryParameters.isEmpty()) {
tickets = findByCriteria(queryParameters, TroubleTicket.class);
} else {
tickets = this.findAll();
}
return tickets;
*/
}
// return Set of unique elements to avoid List with same elements in case of join
private Set<ProductOffering> findByCriteria(MultivaluedMap<String, String> criteria) throws BadUsageException {
List<ProductOffering> resultList = null;
if (criteria != null && !criteria.isEmpty()) {
resultList = manager.findByCriteria(criteria, ProductOffering.class);
} else {
resultList = manager.findAll();
}
if (resultList == null) {
return new LinkedHashSet<ProductOffering>();
} else {
return new LinkedHashSet<ProductOffering>(resultList);
}
}
@GET
@Path("{id}")
@Produces({"application/json"})
public Response findById(@PathParam("id") String id, @Context UriInfo info) {
// fields to filter view
Set<String> fieldSet = FacadeRestUtil.getFieldSet(info.getQueryParameters());
ProductOffering p = manager.find(id);
Response response;
if (p != null) {
// 200
if (fieldSet.isEmpty() || fieldSet.contains(FacadeRestUtil.ALL_FIELDS)) {
response = Response.ok(p).build();
} else {
fieldSet.add(FacadeRestUtil.ID_FIELD);
ObjectNode node = FacadeRestUtil.createNodeViewWithFields(p, fieldSet);
response = Response.ok(node).build();
}
} else {
// 404 not found
response = Response.status(Response.Status.NOT_FOUND).build();
}
return response;
}
@DELETE
@Path("admin/{id}")
public void remove(@PathParam("id") String id) {
manager.remove(manager.find(id));
}
@GET
@Path("admin/count")
@Produces({"application/json"})
public Report count() {
return new Report(manager.count());
}
@POST
@Path("admin")
@Consumes({"application/json"})
@Produces({"application/json"})
public Response createList(List<ProductOffering> entities) {
if (entities == null) {
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
}
int previousRows = manager.count();
int affectedRows;
affectedRows = manager.create(entities);
Report stat = new Report(manager.count());
stat.setAffectedRows(affectedRows);
stat.setPreviousRows(previousRows);
// 201 OK
return Response.created(null).
entity(stat).
build();
}
@DELETE
@Path("admin")
public Report deleteAll() {
int previousRows = manager.count();
manager.removeAll();
int currentRows = manager.count();
int affectedRows = previousRows - currentRows;
Report stat = new Report(currentRows);
stat.setAffectedRows(affectedRows);
stat.setPreviousRows(previousRows);
return stat;
}
@GET
@Path("proto")
@Produces({"application/json"})
public ProductOffering proto() {
ProductOffering po = new ProductOffering();
RefInfo[] bundledProductOffering = new RefInfo[1];
RefInfo refInfo = new RefInfo();
refInfo.setDescription("desc");
refInfo.setId("id");
refInfo.setName("name");
bundledProductOffering[0] = refInfo;
po.setBundledProductOfferings(Arrays.asList(bundledProductOffering));
po.setDescription("ProductOffering");
po.setId("id");
po.setIsBundle(Boolean.TRUE);
po.setName("PO");
RefInfo[] productCategory = new RefInfo[2];
productCategory[0] = refInfo;
productCategory[1] = refInfo;
TimeRange vf = new TimeRange();
vf.setEndDateTime(new Date());
vf.setStartDateTime(new Date());
po.setProductCategories(Arrays.asList(productCategory));
ProductOfferingPrice[] productOfferingPrices = new ProductOfferingPrice[1];
ProductOfferingPrice pop = new ProductOfferingPrice();
pop.setName("name");
Price price = new Price();
price.setAmount("amount");
price.setCurrency("currency");
pop.setPrice(price);
pop.setRecurringChargePeriod("period");
pop.setUnitOfMeasure(null);
pop.setValidFor(vf);
productOfferingPrices[0] = pop;
po.setProductOfferingPrices(Arrays.asList(productOfferingPrices));
po.setProductSpecification(refInfo);
po.setValidFor(vf);
return po;
}
}
| |
/***
* ASM examples: examples showing how ASM can be used
* Copyright (c) 2000-2011 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.
*/
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
/**
* @author Eric Bruneton
*/
public class Adapt extends ClassLoader {
@Override
protected synchronized Class<?> loadClass(
final String name,
final boolean resolve) throws ClassNotFoundException
{
if (name.startsWith("java.")) {
System.err.println("Adapt: loading class '" + name
+ "' without on the fly adaptation");
return super.loadClass(name, resolve);
} else {
System.err.println("Adapt: loading class '" + name
+ "' with on the fly adaptation");
}
// gets an input stream to read the bytecode of the class
String resource = name.replace('.', '/') + ".class";
InputStream is = getResourceAsStream(resource);
byte[] b;
// adapts the class on the fly
try {
ClassReader cr = new ClassReader(is);
ClassWriter cw = new ClassWriter(0);
ClassVisitor cv = new TraceFieldClassAdapter(cw);
cr.accept(cv, 0);
b = cw.toByteArray();
} catch (Exception e) {
throw new ClassNotFoundException(name, e);
}
// optional: stores the adapted class on disk
try {
FileOutputStream fos = new FileOutputStream(resource + ".adapted");
fos.write(b);
fos.close();
} catch (IOException e) {
}
// returns the adapted class
return defineClass(name, b, 0, b.length);
}
public static void main(final String args[]) throws Exception {
// loads the application class (in args[0]) with an Adapt class loader
ClassLoader loader = new Adapt();
Class<?> c = loader.loadClass(args[0]);
// calls the 'main' static method of this class with the
// application arguments (in args[1] ... args[n]) as parameter
Method m = c.getMethod("main", new Class<?>[] { String[].class });
String[] applicationArgs = new String[args.length - 1];
System.arraycopy(args, 1, applicationArgs, 0, applicationArgs.length);
m.invoke(null, new Object[] { applicationArgs });
}
}
class TraceFieldClassAdapter extends ClassVisitor implements Opcodes {
private String owner;
public TraceFieldClassAdapter(final ClassVisitor cv) {
super(Opcodes.ASM4, cv);
}
@Override
public void visit(
final int version,
final int access,
final String name,
final String signature,
final String superName,
final String[] interfaces)
{
owner = name;
super.visit(version, access, name, signature, superName, interfaces);
}
@Override
public FieldVisitor visitField(
final int access,
final String name,
final String desc,
final String signature,
final Object value)
{
FieldVisitor fv = super.visitField(access, name, desc, signature, value);
if ((access & ACC_STATIC) == 0) {
Type t = Type.getType(desc);
int size = t.getSize();
// generates getter method
String gDesc = "()" + desc;
MethodVisitor gv = cv.visitMethod(ACC_PRIVATE,
"_get" + name,
gDesc,
null,
null);
gv.visitFieldInsn(GETSTATIC,
"java/lang/System",
"err",
"Ljava/io/PrintStream;");
gv.visitLdcInsn("_get" + name + " called");
gv.visitMethodInsn(INVOKEVIRTUAL,
"java/io/PrintStream",
"println",
"(Ljava/lang/String;)V");
gv.visitVarInsn(ALOAD, 0);
gv.visitFieldInsn(GETFIELD, owner, name, desc);
gv.visitInsn(t.getOpcode(IRETURN));
gv.visitMaxs(1 + size, 1);
gv.visitEnd();
// generates setter method
String sDesc = "(" + desc + ")V";
MethodVisitor sv = cv.visitMethod(ACC_PRIVATE,
"_set" + name,
sDesc,
null,
null);
sv.visitFieldInsn(GETSTATIC,
"java/lang/System",
"err",
"Ljava/io/PrintStream;");
sv.visitLdcInsn("_set" + name + " called");
sv.visitMethodInsn(INVOKEVIRTUAL,
"java/io/PrintStream",
"println",
"(Ljava/lang/String;)V");
sv.visitVarInsn(ALOAD, 0);
sv.visitVarInsn(t.getOpcode(ILOAD), 1);
sv.visitFieldInsn(PUTFIELD, owner, name, desc);
sv.visitInsn(RETURN);
sv.visitMaxs(1 + size, 1 + size);
sv.visitEnd();
}
return fv;
}
@Override
public MethodVisitor visitMethod(
final int access,
final String name,
final String desc,
final String signature,
final String[] exceptions)
{
MethodVisitor mv = cv.visitMethod(access,
name,
desc,
signature,
exceptions);
return mv == null ? null : new TraceFieldCodeAdapter(mv, owner);
}
}
class TraceFieldCodeAdapter extends MethodVisitor implements Opcodes {
private String owner;
public TraceFieldCodeAdapter(final MethodVisitor mv, final String owner) {
super(Opcodes.ASM4, mv);
this.owner = owner;
}
@Override
public void visitFieldInsn(
final int opcode,
final String owner,
final String name,
final String desc)
{
if (owner.equals(this.owner)) {
if (opcode == GETFIELD) {
// replaces GETFIELD f by INVOKESPECIAL _getf
String gDesc = "()" + desc;
visitMethodInsn(INVOKESPECIAL, owner, "_get" + name, gDesc);
return;
} else if (opcode == PUTFIELD) {
// replaces PUTFIELD f by INVOKESPECIAL _setf
String sDesc = "(" + desc + ")V";
visitMethodInsn(INVOKESPECIAL, owner, "_set" + name, sDesc);
return;
}
}
super.visitFieldInsn(opcode, owner, name, desc);
}
}
| |
package org.cboard.controller;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Functions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.cboard.dao.*;
import org.cboard.dataprovider.DataProviderManager;
import org.cboard.dataprovider.DataProviderViewManager;
import org.cboard.dto.*;
import org.cboard.pojo.*;
import org.cboard.services.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by yfyuan on 2016/8/9.
*/
@RestController
@RequestMapping("/dashboard")
public class DashboardController {
@Autowired
private BoardDao boardDao;
@Autowired
private DatasourceDao datasourceDao;
@Autowired
private DataProviderService dataProviderService;
@Autowired
private CachedDataProviderService cachedDataProviderService;
@Autowired
private DatasourceService datasourceService;
@Autowired
private WidgetService widgetService;
@Autowired
private WidgetDao widgetDao;
@Autowired
private BoardService boardService;
@Autowired
private CategoryDao categoryDao;
@Autowired
private CategoryService categoryService;
@Autowired
private AuthenticationService authenticationService;
@Autowired
private DatasetDao datasetDao;
@Autowired
private DatasetService datasetService;
@RequestMapping(value = "/test")
public ServiceStatus test(@RequestParam(name = "datasource", required = false) String datasource, @RequestParam(name = "query", required = false) String query) {
JSONObject queryO = JSONObject.parseObject(query);
JSONObject datasourceO = JSONObject.parseObject(datasource);
return dataProviderService.test(datasourceO, Maps.transformValues(queryO, Functions.toStringFunction()));
}
@RequestMapping(value = "/getData")
public DataProviderResult getData(@RequestParam(name = "datasourceId", required = false) Long datasourceId, @RequestParam(name = "query", required = false) String query, @RequestParam(name = "datasetId", required = false) Long datasetId) {
Map<String, String> strParams = null;
if (query != null) {
JSONObject queryO = JSONObject.parseObject(query);
strParams = Maps.transformValues(queryO, Functions.toStringFunction());
}
DataProviderResult result = dataProviderService.getData(datasourceId, strParams, datasetId);
return result;
}
@RequestMapping(value = "/getCachedData")
public DataProviderResult getCachedData(@RequestParam(name = "datasourceId", required = false) Long datasourceId, @RequestParam(name = "query", required = false) String query, @RequestParam(name = "datasetId", required = false) Long datasetId, @RequestParam(name = "reload", required = false, defaultValue = "false") Boolean reload) {
Map<String, String> strParams = null;
if (query != null) {
JSONObject queryO = JSONObject.parseObject(query);
strParams = Maps.transformValues(queryO, Functions.toStringFunction());
}
DataProviderResult result = cachedDataProviderService.getData(datasourceId, strParams, datasetId, reload);
return result;
}
@RequestMapping(value = "/getDatasourceList")
public List<ViewDashboardDatasource> getDatasourceList() {
String userid = authenticationService.getCurrentUser().getUserId();
List<DashboardDatasource> list = datasourceDao.getDatasourceList(userid);
return Lists.transform(list, ViewDashboardDatasource.TO);
}
@RequestMapping(value = "/getProviderList")
public Set<String> getProviderList() {
return DataProviderManager.getProviderList();
}
@RequestMapping(value = "/getConfigView")
public String getConfigView(@RequestParam(name = "type") String type) {
return DataProviderViewManager.getQueryView(type);
}
@RequestMapping(value = "/getDatasourceView")
public String getDatasourceView(@RequestParam(name = "type") String type) {
return DataProviderViewManager.getDatasourceView(type);
}
@RequestMapping(value = "/saveNewDatasource")
public ServiceStatus saveNewDatasource(@RequestParam(name = "json") String json) {
String userid = authenticationService.getCurrentUser().getUserId();
return datasourceService.save(userid, json);
}
@RequestMapping(value = "/updateDatasource")
public ServiceStatus updateDatasource(@RequestParam(name = "json") String json) {
String userid = authenticationService.getCurrentUser().getUserId();
return datasourceService.update(userid, json);
}
@RequestMapping(value = "/deleteDatasource")
public ServiceStatus deleteDatasource(@RequestParam(name = "id") Long id) {
String userid = authenticationService.getCurrentUser().getUserId();
return datasourceService.delete(userid, id);
}
@RequestMapping(value = "/saveNewWidget")
public ServiceStatus saveNewWidget(@RequestParam(name = "json") String json) {
String userid = authenticationService.getCurrentUser().getUserId();
return widgetService.save(userid, json);
}
@RequestMapping(value = "/getWidgetList")
public List<ViewDashboardWidget> getWidgetList() {
String userid = authenticationService.getCurrentUser().getUserId();
List<DashboardWidget> list = widgetDao.getWidgetList(userid);
return Lists.transform(list, ViewDashboardWidget.TO);
}
@RequestMapping(value = "/updateWidget")
public ServiceStatus updateWidget(@RequestParam(name = "json") String json) {
String userid = authenticationService.getCurrentUser().getUserId();
return widgetService.update(userid, json);
}
@RequestMapping(value = "/deleteWidget")
public ServiceStatus deleteWidget(@RequestParam(name = "id") Long id) {
String userid = authenticationService.getCurrentUser().getUserId();
return widgetService.delete(userid, id);
}
@RequestMapping(value = "/getBoardList")
public List<ViewDashboardBoard> getBoardList() {
String userid = authenticationService.getCurrentUser().getUserId();
List<DashboardBoard> list = boardService.getBoardList(userid);
return Lists.transform(list, ViewDashboardBoard.TO);
}
@RequestMapping(value = "/saveNewBoard")
public ServiceStatus saveNewBoard(@RequestParam(name = "json") String json) {
String userid = authenticationService.getCurrentUser().getUserId();
return boardService.save(userid, json);
}
@RequestMapping(value = "/updateBoard")
public ServiceStatus updateBoard(@RequestParam(name = "json") String json) {
String userid = authenticationService.getCurrentUser().getUserId();
return boardService.update(userid, json);
}
@RequestMapping(value = "/deleteBoard")
public String deleteBoard(@RequestParam(name = "id") Long id) {
String userid = authenticationService.getCurrentUser().getUserId();
return boardService.delete(userid, id);
}
@RequestMapping(value = "/getBoardData")
public ViewDashboardBoard getBoardData(@RequestParam(name = "id") Long id) {
return boardService.getBoardData(id);
}
@RequestMapping(value = "/saveNewCategory")
public ServiceStatus saveNewCategory(@RequestParam(name = "json") String json) {
String userid = authenticationService.getCurrentUser().getUserId();
return categoryService.save(userid, json);
}
@RequestMapping(value = "/getCategoryList")
public List<DashboardCategory> getCategoryList() {
List<DashboardCategory> list = categoryDao.getCategoryList();
return list;
}
@RequestMapping(value = "/updateCategory")
public ServiceStatus updateCategory(@RequestParam(name = "json") String json) {
String userid = authenticationService.getCurrentUser().getUserId();
return categoryService.update(userid, json);
}
@RequestMapping(value = "/deleteCategory")
public String deleteCategory(@RequestParam(name = "id") Long id) {
return categoryService.delete(id);
}
@RequestMapping(value = "/getWidgetCategoryList")
public List<String> getWidgetCategoryList() {
return widgetDao.getCategoryList();
}
@RequestMapping(value = "/saveNewDataset")
public ServiceStatus saveNewDataset(@RequestParam(name = "json") String json) {
String userid = authenticationService.getCurrentUser().getUserId();
return datasetService.save(userid, json);
}
@RequestMapping(value = "/getDatasetList")
public List<ViewDashboardDataset> getDatasetList() {
String userid = authenticationService.getCurrentUser().getUserId();
List<DashboardDataset> list = datasetDao.getDatasetList(userid);
return Lists.transform(list, ViewDashboardDataset.TO);
}
@RequestMapping(value = "/updateDataset")
public ServiceStatus updateDataset(@RequestParam(name = "json") String json) {
String userid = authenticationService.getCurrentUser().getUserId();
return datasetService.update(userid, json);
}
@RequestMapping(value = "/deleteDataset")
public ServiceStatus deleteDataset(@RequestParam(name = "id") Long id) {
String userid = authenticationService.getCurrentUser().getUserId();
return datasetService.delete(userid, id);
}
@RequestMapping(value = "/getDatasetCategoryList")
public List<String> getDatasetCategoryList() {
return datasetDao.getCategoryList();
}
@RequestMapping(value = "/checkWidget")
public ServiceStatus checkWidget(@RequestParam(name = "id") Long id) {
return widgetService.checkRule(authenticationService.getCurrentUser().getUserId(), id);
}
@RequestMapping(value = "/checkDatasource")
public ServiceStatus checkDatasource(@RequestParam(name = "id") Long id) {
return datasourceService.checkDatasource(authenticationService.getCurrentUser().getUserId(), id);
}
}
| |
/*
* 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;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import org.junit.*;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.dht.Murmur3Partitioner;
import org.apache.cassandra.io.util.BufferedDataOutputStreamPlus;
import org.apache.cassandra.io.util.DataOutputBuffer;
import org.apache.cassandra.io.util.DataOutputStreamPlus;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.utils.IFilter.FilterKey;
import org.apache.cassandra.utils.KeyGenerator.RandomStringGenerator;
public class BloomFilterTest
{
public IFilter bfInvHashes;
public BloomFilterTest()
{
}
public static IFilter testSerialize(IFilter f) throws IOException
{
f.add(FilterTestHelper.bytes("a"));
DataOutputBuffer out = new DataOutputBuffer();
FilterFactory.serialize(f, out);
ByteArrayInputStream in = new ByteArrayInputStream(out.getData(), 0, out.getLength());
IFilter f2 = FilterFactory.deserialize(new DataInputStream(in), true);
assert f2.isPresent(FilterTestHelper.bytes("a"));
assert !f2.isPresent(FilterTestHelper.bytes("b"));
return f2;
}
@Before
public void setup()
{
bfInvHashes = FilterFactory.getFilter(10000L, FilterTestHelper.MAX_FAILURE_RATE, true);
}
@After
public void destroy()
{
bfInvHashes.close();
}
@Test(expected = UnsupportedOperationException.class)
public void testBloomLimits1()
{
int maxBuckets = BloomCalculations.probs.length - 1;
int maxK = BloomCalculations.probs[maxBuckets].length - 1;
// possible
BloomCalculations.computeBloomSpec(maxBuckets, BloomCalculations.probs[maxBuckets][maxK]);
// impossible, throws
BloomCalculations.computeBloomSpec(maxBuckets, BloomCalculations.probs[maxBuckets][maxK] / 2);
}
@Test
public void testOne()
{
bfInvHashes.add(FilterTestHelper.bytes("a"));
assert bfInvHashes.isPresent(FilterTestHelper.bytes("a"));
assert !bfInvHashes.isPresent(FilterTestHelper.bytes("b"));
}
@Test
public void testFalsePositivesInt()
{
FilterTestHelper.testFalsePositives(bfInvHashes, FilterTestHelper.intKeys(), FilterTestHelper.randomKeys2());
}
@Test
public void testFalsePositivesRandom()
{
FilterTestHelper.testFalsePositives(bfInvHashes, FilterTestHelper.randomKeys(), FilterTestHelper.randomKeys2());
}
@Test
public void testWords()
{
if (KeyGenerator.WordGenerator.WORDS == 0)
{
return;
}
IFilter bf2 = FilterFactory.getFilter(KeyGenerator.WordGenerator.WORDS / 2, FilterTestHelper.MAX_FAILURE_RATE, true);
int skipEven = KeyGenerator.WordGenerator.WORDS % 2 == 0 ? 0 : 2;
FilterTestHelper.testFalsePositives(bf2,
new KeyGenerator.WordGenerator(skipEven, 2),
new KeyGenerator.WordGenerator(1, 2));
bf2.close();
}
@Test
public void testSerialize() throws IOException
{
BloomFilterTest.testSerialize(bfInvHashes).close();
}
@Test
@Ignore
public void testManyRandom()
{
testManyRandom(FilterTestHelper.randomKeys());
}
private static void testManyRandom(Iterator<ByteBuffer> keys)
{
int MAX_HASH_COUNT = 128;
Set<Long> hashes = new HashSet<>();
long collisions = 0;
while (keys.hasNext())
{
hashes.clear();
FilterKey buf = FilterTestHelper.wrap(keys.next());
BloomFilter bf = (BloomFilter) FilterFactory.getFilter(10, 1, false);
for (long hashIndex : bf.getHashBuckets(buf, MAX_HASH_COUNT, 1024 * 1024))
{
hashes.add(hashIndex);
}
collisions += (MAX_HASH_COUNT - hashes.size());
bf.close();
}
Assert.assertTrue("collisions=" + collisions, collisions <= 100);
}
@Test(expected = UnsupportedOperationException.class)
public void testOffHeapException()
{
long numKeys = ((long)Integer.MAX_VALUE) * 64L + 1L; // approx 128 Billion
FilterFactory.getFilter(numKeys, 0.01d, true).close();
}
@Test
public void compareCachedKey()
{
try (BloomFilter bf1 = (BloomFilter) FilterFactory.getFilter(FilterTestHelper.ELEMENTS / 2, FilterTestHelper.MAX_FAILURE_RATE, false);
BloomFilter bf2 = (BloomFilter) FilterFactory.getFilter(FilterTestHelper.ELEMENTS / 2, FilterTestHelper.MAX_FAILURE_RATE, false);
BloomFilter bf3 = (BloomFilter) FilterFactory.getFilter(FilterTestHelper.ELEMENTS / 2, FilterTestHelper.MAX_FAILURE_RATE, false))
{
RandomStringGenerator gen1 = new KeyGenerator.RandomStringGenerator(new Random().nextInt(), FilterTestHelper.ELEMENTS);
// make sure all bitsets are empty.
BitSetTest.compare(bf1.bitset, bf2.bitset);
BitSetTest.compare(bf1.bitset, bf3.bitset);
while (gen1.hasNext())
{
ByteBuffer key = gen1.next();
FilterKey cached = FilterTestHelper.wrapCached(key);
bf1.add(FilterTestHelper.wrap(key));
bf2.add(cached);
bf3.add(cached);
}
BitSetTest.compare(bf1.bitset, bf2.bitset);
BitSetTest.compare(bf1.bitset, bf3.bitset);
}
}
@Test
@Ignore
public void testHugeBFSerialization() throws IOException
{
ByteBuffer test = ByteBuffer.wrap(new byte[] {0, 1});
File file = FileUtils.createTempFile("bloomFilterTest-", ".dat");
BloomFilter filter = (BloomFilter) FilterFactory.getFilter(((long) Integer.MAX_VALUE / 8) + 1, 0.01d, true);
filter.add(FilterTestHelper.wrap(test));
DataOutputStreamPlus out = new BufferedDataOutputStreamPlus(new FileOutputStream(file));
FilterFactory.serialize(filter, out);
filter.bitset.serialize(out);
out.close();
filter.close();
DataInputStream in = new DataInputStream(new FileInputStream(file));
BloomFilter filter2 = (BloomFilter) FilterFactory.deserialize(in, true);
Assert.assertTrue(filter2.isPresent(FilterTestHelper.wrap(test)));
FileUtils.closeQuietly(in);
filter2.close();
}
@Test
public void testMurmur3FilterHash()
{
IPartitioner partitioner = new Murmur3Partitioner();
Iterator<ByteBuffer> gen = new KeyGenerator.RandomStringGenerator(new Random().nextInt(), FilterTestHelper.ELEMENTS);
long[] expected = new long[2];
long[] actual = new long[2];
while (gen.hasNext())
{
expected[0] = 1;
expected[1] = 2;
actual[0] = 3;
actual[1] = 4;
ByteBuffer key = gen.next();
FilterKey expectedKey = FilterTestHelper.wrap(key);
FilterKey actualKey = partitioner.decorateKey(key);
actualKey.filterHash(actual);
expectedKey.filterHash(expected);
Assert.assertArrayEquals(expected, actual);
}
}
}
| |
/*
* #%L
* SparkCommerce Framework
* %%
* Copyright (C) 2009 - 2013 Spark Commerce
* %%
* 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.
* #L%
*/
package org.sparkcommerce.core.order.domain;
import org.sparkcommerce.common.currency.util.SparkCurrencyUtils;
import org.sparkcommerce.common.currency.util.CurrencyCodeIdentifiable;
import org.sparkcommerce.common.extensibility.jpa.copy.DirectCopyTransform;
import org.sparkcommerce.common.extensibility.jpa.copy.DirectCopyTransformMember;
import org.sparkcommerce.common.extensibility.jpa.copy.DirectCopyTransformTypes;
import org.sparkcommerce.common.money.Money;
import org.sparkcommerce.common.presentation.AdminPresentation;
import org.sparkcommerce.common.presentation.AdminPresentationClass;
import org.sparkcommerce.common.presentation.AdminPresentationCollection;
import org.sparkcommerce.common.presentation.PopulateToOneFieldsEnum;
import org.sparkcommerce.common.presentation.client.SupportedFieldType;
import org.sparkcommerce.common.presentation.override.AdminPresentationMergeEntry;
import org.sparkcommerce.common.presentation.override.AdminPresentationMergeOverride;
import org.sparkcommerce.common.presentation.override.AdminPresentationMergeOverrides;
import org.sparkcommerce.common.presentation.override.PropertyType;
import org.sparkcommerce.core.offer.domain.CandidateFulfillmentGroupOffer;
import org.sparkcommerce.core.offer.domain.CandidateFulfillmentGroupOfferImpl;
import org.sparkcommerce.core.offer.domain.FulfillmentGroupAdjustment;
import org.sparkcommerce.core.offer.domain.FulfillmentGroupAdjustmentImpl;
import org.sparkcommerce.core.order.service.type.FulfillmentGroupStatusType;
import org.sparkcommerce.core.order.service.type.FulfillmentType;
import org.sparkcommerce.profile.core.domain.Address;
import org.sparkcommerce.profile.core.domain.AddressImpl;
import org.sparkcommerce.profile.core.domain.Phone;
import org.sparkcommerce.profile.core.domain.PhoneImpl;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Index;
import org.hibernate.annotations.Parameter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "SC_FULFILLMENT_GROUP")
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements")
@AdminPresentationMergeOverrides(
{
@AdminPresentationMergeOverride(name = "", mergeEntries =
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.READONLY,
booleanOverrideValue = true)),
@AdminPresentationMergeOverride(name = "currency", mergeEntries =
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.PROMINENT,
booleanOverrideValue = false)),
@AdminPresentationMergeOverride(name = "personalMessage", mergeEntries = {
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.TAB,
overrideValue = FulfillmentGroupImpl.Presentation.Tab.Name.Advanced),
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.TABORDER,
intOverrideValue = FulfillmentGroupImpl.Presentation.Tab.Order.Advanced)
}),
@AdminPresentationMergeOverride(name = "address", mergeEntries = {
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.TAB,
overrideValue = FulfillmentGroupImpl.Presentation.Tab.Name.Address),
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.TABORDER,
intOverrideValue = FulfillmentGroupImpl.Presentation.Tab.Order.Address)
}),
@AdminPresentationMergeOverride(name = "address.isDefault", mergeEntries = {
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.EXCLUDED,
booleanOverrideValue = true)
}),
@AdminPresentationMergeOverride(name = "address.isActive", mergeEntries = {
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.EXCLUDED,
booleanOverrideValue = true)
}),
@AdminPresentationMergeOverride(name = "address.isBusiness", mergeEntries = {
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.EXCLUDED,
booleanOverrideValue = true)
}),
@AdminPresentationMergeOverride(name = "phone", mergeEntries = {
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.EXCLUDED,
booleanOverrideValue = true)
}),
@AdminPresentationMergeOverride(name = "phone.phoneNumber", mergeEntries = {
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.EXCLUDED,
booleanOverrideValue = false),
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.ORDER,
intOverrideValue = FulfillmentGroupImpl.Presentation.FieldOrder.PHONE),
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.GROUP,
overrideValue = "General"),
@AdminPresentationMergeEntry(propertyType = PropertyType.AdminPresentation.REQUIREDOVERRIDE,
overrideValue = "NOT_REQUIRED")
})
}
)
@AdminPresentationClass(populateToOneFields = PopulateToOneFieldsEnum.TRUE, friendlyName = "FulfillmentGroupImpl_baseFulfillmentGroup")
@DirectCopyTransform({
@DirectCopyTransformMember(templateTokens = DirectCopyTransformTypes.MULTITENANT_SITE)
})
public class FulfillmentGroupImpl implements FulfillmentGroup, CurrencyCodeIdentifiable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "FulfillmentGroupId")
@GenericGenerator(
name="FulfillmentGroupId",
strategy="org.sparkcommerce.common.persistence.IdOverrideTableGenerator",
parameters = {
@Parameter(name="segment_value", value="FulfillmentGroupImpl"),
@Parameter(name="entity_name", value="org.sparkcommerce.core.order.domain.FulfillmentGroupImpl")
}
)
@Column(name = "FULFILLMENT_GROUP_ID")
protected Long id;
@Column(name = "REFERENCE_NUMBER")
@Index(name="FG_REFERENCE_INDEX", columnNames={"REFERENCE_NUMBER"})
@AdminPresentation(friendlyName = "FulfillmentGroupImpl_FG_Reference_Number", order=Presentation.FieldOrder.REFNUMBER,
groupOrder = Presentation.Group.Order.General)
protected String referenceNumber;
@Column(name = "METHOD")
@Index(name="FG_METHOD_INDEX", columnNames={"METHOD"})
@AdminPresentation(excluded = true)
@Deprecated
protected String method;
@Column(name = "SERVICE")
@Index(name="FG_SERVICE_INDEX", columnNames={"SERVICE"})
@AdminPresentation(excluded = true)
@Deprecated
protected String service;
@Column(name = "RETAIL_PRICE", precision=19, scale=5)
@AdminPresentation(friendlyName = "FulfillmentGroupImpl_Retail_Shipping_Price", order=Presentation.FieldOrder.RETAIL,
group = Presentation.Group.Name.Pricing, groupOrder = Presentation.Group.Order.Pricing,
tab = Presentation.Tab.Name.Pricing, tabOrder = Presentation.Tab.Order.Pricing,
fieldType=SupportedFieldType.MONEY)
protected BigDecimal retailFulfillmentPrice;
@Column(name = "SALE_PRICE", precision=19, scale=5)
@AdminPresentation(friendlyName = "FulfillmentGroupImpl_Sale_Shipping_Price", order=Presentation.FieldOrder.SALE,
group = Presentation.Group.Name.Pricing, groupOrder = Presentation.Group.Order.Pricing,
tab = Presentation.Tab.Name.Pricing, tabOrder = Presentation.Tab.Order.Pricing,
fieldType=SupportedFieldType.MONEY)
protected BigDecimal saleFulfillmentPrice;
@Column(name = "PRICE", precision=19, scale=5)
@AdminPresentation(friendlyName = "FulfillmentGroupImpl_Shipping_Price", order=Presentation.FieldOrder.PRICE,
group = Presentation.Group.Name.Pricing, groupOrder = Presentation.Group.Order.Pricing,
tab = Presentation.Tab.Name.Pricing, tabOrder = Presentation.Tab.Order.Pricing,
fieldType=SupportedFieldType.MONEY)
protected BigDecimal fulfillmentPrice;
@Column(name = "TYPE")
@AdminPresentation(friendlyName = "FulfillmentGroupImpl_FG_Type", order=Presentation.FieldOrder.TYPE,
fieldType=SupportedFieldType.BROADLEAF_ENUMERATION,
sparkEnumeration="org.sparkcommerce.core.order.service.type.FulfillmentType",
prominent = true, gridOrder = 3000)
protected String type;
@Column(name = "TOTAL_TAX", precision=19, scale=5)
@AdminPresentation(friendlyName = "FulfillmentGroupImpl_FG_Total_Tax", order=Presentation.FieldOrder.TOTALTAX,
group = Presentation.Group.Name.Pricing, groupOrder = Presentation.Group.Order.Pricing,
tab = Presentation.Tab.Name.Pricing, tabOrder = Presentation.Tab.Order.Pricing,
fieldType=SupportedFieldType.MONEY)
protected BigDecimal totalTax;
@Column(name = "TOTAL_ITEM_TAX", precision=19, scale=5)
@AdminPresentation(friendlyName = "FulfillmentGroupImpl_FG_Total_Item_Tax", order=Presentation.FieldOrder.ITEMTAX,
group = Presentation.Group.Name.Pricing, groupOrder = Presentation.Group.Order.Pricing,
tab = Presentation.Tab.Name.Pricing, tabOrder = Presentation.Tab.Order.Pricing,
fieldType=SupportedFieldType.MONEY)
protected BigDecimal totalItemTax;
@Column(name = "TOTAL_FEE_TAX", precision=19, scale=5)
@AdminPresentation(friendlyName = "FulfillmentGroupImpl_FG_Total_Fee_Tax", order=Presentation.FieldOrder.FEETAX,
group = Presentation.Group.Name.Pricing, groupOrder = Presentation.Group.Order.Pricing,
tab = Presentation.Tab.Name.Pricing, tabOrder = Presentation.Tab.Order.Pricing,
fieldType=SupportedFieldType.MONEY)
protected BigDecimal totalFeeTax;
@Column(name = "TOTAL_FG_TAX", precision=19, scale=5)
@AdminPresentation(friendlyName = "FulfillmentGroupImpl_FG_Total_FG_Tax", order=Presentation.FieldOrder.FGTAX,
group = Presentation.Group.Name.Pricing, groupOrder = Presentation.Group.Order.Pricing,
tab = Presentation.Tab.Name.Pricing, tabOrder = Presentation.Tab.Order.Pricing,
fieldType=SupportedFieldType.MONEY)
protected BigDecimal totalFulfillmentGroupTax;
@Column(name = "DELIVERY_INSTRUCTION")
@AdminPresentation(friendlyName = "FulfillmentGroupImpl_FG_Delivery_Instruction", order=Presentation.FieldOrder.DELIVERINSTRUCTION)
protected String deliveryInstruction;
@Column(name = "IS_PRIMARY")
@Index(name="FG_PRIMARY_INDEX", columnNames={"IS_PRIMARY"})
@AdminPresentation(friendlyName = "FulfillmentGroupImpl_Primary_FG", order=Presentation.FieldOrder.PRIMARY)
protected boolean primary = false;
@Column(name = "MERCHANDISE_TOTAL", precision=19, scale=5)
@AdminPresentation(friendlyName = "FulfillmentGroupImpl_FG_Merchandise_Total", order=Presentation.FieldOrder.MERCHANDISETOTAL,
group = Presentation.Group.Name.Pricing, groupOrder = Presentation.Group.Order.Pricing,
tab = Presentation.Tab.Name.Pricing, tabOrder = Presentation.Tab.Order.Pricing,
fieldType=SupportedFieldType.MONEY)
protected BigDecimal merchandiseTotal;
@Column(name = "TOTAL", precision=19, scale=5)
@AdminPresentation(friendlyName = "FulfillmentGroupImpl_FG_Total", order=Presentation.FieldOrder.TOTAL,
group = Presentation.Group.Name.Pricing, groupOrder = Presentation.Group.Order.Pricing,
tab = Presentation.Tab.Name.Pricing, tabOrder = Presentation.Tab.Order.Pricing,
fieldType= SupportedFieldType.MONEY, prominent = true, gridOrder = 2000)
protected BigDecimal total;
@Column(name = "STATUS")
@Index(name="FG_STATUS_INDEX", columnNames={"STATUS"})
@AdminPresentation(friendlyName = "FulfillmentGroupImpl_FG_Status", order=Presentation.FieldOrder.STATUS,
fieldType=SupportedFieldType.BROADLEAF_ENUMERATION,
sparkEnumeration="org.sparkcommerce.core.order.service.type.FulfillmentGroupStatusType",
prominent = true, gridOrder = 4000)
protected String status;
@Column(name = "SHIPPING_PRICE_TAXABLE")
@AdminPresentation(friendlyName = "FulfillmentGroupImpl_Shipping_Price_Taxable", order=Presentation.FieldOrder.TAXABLE,
group = Presentation.Group.Name.Pricing, groupOrder = Presentation.Group.Order.Pricing,
tab = Presentation.Tab.Name.Pricing, tabOrder = Presentation.Tab.Order.Pricing)
protected Boolean isShippingPriceTaxable = Boolean.FALSE;
@ManyToOne(targetEntity = FulfillmentOptionImpl.class, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name = "FULFILLMENT_OPTION_ID")
protected FulfillmentOption fulfillmentOption;
@ManyToOne(targetEntity = OrderImpl.class, optional=false)
@JoinColumn(name = "ORDER_ID")
@Index(name="FG_ORDER_INDEX", columnNames={"ORDER_ID"})
@AdminPresentation(excluded = true)
protected Order order;
@Column(name = "FULFILLMENT_GROUP_SEQUNCE")
protected Integer sequence;
@ManyToOne(targetEntity = AddressImpl.class, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name = "ADDRESS_ID")
@Index(name="FG_ADDRESS_INDEX", columnNames={"ADDRESS_ID"})
protected Address address;
/**
* @deprecated uses the phonePrimary property on AddressImpl instead
*/
@ManyToOne(targetEntity = PhoneImpl.class, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name = "PHONE_ID")
@Index(name="FG_PHONE_INDEX", columnNames={"PHONE_ID"})
@Deprecated
protected Phone phone;
@ManyToOne(targetEntity = PersonalMessageImpl.class, cascade = { CascadeType.ALL })
@JoinColumn(name = "PERSONAL_MESSAGE_ID")
@Index(name="FG_MESSAGE_INDEX", columnNames={"PERSONAL_MESSAGE_ID"})
protected PersonalMessage personalMessage;
@OneToMany(mappedBy = "fulfillmentGroup", targetEntity = FulfillmentGroupItemImpl.class, cascade = CascadeType.ALL,
orphanRemoval = true)
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements")
@AdminPresentationCollection(friendlyName="FulfillmentGroupImpl_Items",
tab = Presentation.Tab.Name.Items, tabOrder = Presentation.Tab.Order.Items)
protected List<FulfillmentGroupItem> fulfillmentGroupItems = new ArrayList<FulfillmentGroupItem>();
@OneToMany(mappedBy = "fulfillmentGroup", targetEntity = FulfillmentGroupFeeImpl.class, cascade = { CascadeType.ALL },
orphanRemoval = true)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region = "blOrderElements")
@AdminPresentationCollection(friendlyName="FulfillmentGroupImpl_Fees",
tab = Presentation.Tab.Name.Pricing, tabOrder = Presentation.Tab.Order.Pricing)
protected List<FulfillmentGroupFee> fulfillmentGroupFees = new ArrayList<FulfillmentGroupFee>();
@OneToMany(mappedBy = "fulfillmentGroup", targetEntity = CandidateFulfillmentGroupOfferImpl.class, cascade = { CascadeType.ALL },
orphanRemoval = true)
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements")
protected List<CandidateFulfillmentGroupOffer> candidateOffers = new ArrayList<CandidateFulfillmentGroupOffer>();
@OneToMany(mappedBy = "fulfillmentGroup", targetEntity = FulfillmentGroupAdjustmentImpl.class, cascade = { CascadeType.ALL },
orphanRemoval = true)
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements")
@AdminPresentationCollection(friendlyName="FulfillmentGroupImpl_Adjustments",
tab = Presentation.Tab.Name.Advanced, tabOrder = Presentation.Tab.Order.Advanced)
protected List<FulfillmentGroupAdjustment> fulfillmentGroupAdjustments = new ArrayList<FulfillmentGroupAdjustment>();
@OneToMany(fetch = FetchType.LAZY, targetEntity = TaxDetailImpl.class, cascade = { CascadeType.ALL }, orphanRemoval = true)
@JoinTable(name = "SC_FG_FG_TAX_XREF", joinColumns = @JoinColumn(name = "FULFILLMENT_GROUP_ID"),
inverseJoinColumns = @JoinColumn(name = "TAX_DETAIL_ID"))
@Cache(usage=CacheConcurrencyStrategy.NONSTRICT_READ_WRITE, region="blOrderElements")
protected List<TaxDetail> taxes = new ArrayList<TaxDetail>();
@Column(name = "SHIPPING_OVERRIDE")
protected Boolean shippingOverride;
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
@Override
public Order getOrder() {
return order;
}
@Override
public void setOrder(Order order) {
this.order = order;
}
@Override
public FulfillmentOption getFulfillmentOption() {
return fulfillmentOption;
}
@Override
public void setFulfillmentOption(FulfillmentOption fulfillmentOption) {
this.fulfillmentOption = fulfillmentOption;
}
@Override
public String getReferenceNumber() {
return referenceNumber;
}
@Override
public void setReferenceNumber(String referenceNumber) {
this.referenceNumber = referenceNumber;
}
@Override
public List<FulfillmentGroupItem> getFulfillmentGroupItems() {
return fulfillmentGroupItems;
}
@Override
public List<DiscreteOrderItem> getDiscreteOrderItems() {
List<DiscreteOrderItem> discreteOrderItems = new ArrayList<DiscreteOrderItem>();
for (FulfillmentGroupItem fgItem : fulfillmentGroupItems) {
OrderItem orderItem = fgItem.getOrderItem();
if (orderItem instanceof BundleOrderItem) {
BundleOrderItemImpl bundleOrderItem = (BundleOrderItemImpl)orderItem;
for (DiscreteOrderItem discreteOrderItem : bundleOrderItem.getDiscreteOrderItems()) {
discreteOrderItems.add(discreteOrderItem);
}
} else if (orderItem instanceof DiscreteOrderItem) {
DiscreteOrderItem discreteOrderItem = (DiscreteOrderItem)orderItem;
discreteOrderItems.add(discreteOrderItem);
}
}
return discreteOrderItems;
}
@Override
public void setFulfillmentGroupItems(List<FulfillmentGroupItem> fulfillmentGroupItems) {
this.fulfillmentGroupItems = fulfillmentGroupItems;
}
@Override
public void addFulfillmentGroupItem(FulfillmentGroupItem fulfillmentGroupItem) {
if (this.fulfillmentGroupItems == null) {
this.fulfillmentGroupItems = new Vector<FulfillmentGroupItem>();
}
this.fulfillmentGroupItems.add(fulfillmentGroupItem);
}
@Override
public Address getAddress() {
return address;
}
@Override
public void setAddress(Address address) {
this.address = address;
}
/**
* @deprecated use the phonePrimary property on the related Address instead
*/
@Deprecated
@Override
public Phone getPhone() {
return phone;
}
/**
* @deprecated use the phonePrimary property on the related Address instead
*/
@Deprecated
@Override
public void setPhone(Phone phone) {
this.phone = phone;
}
@Override
@Deprecated
public String getMethod() {
return method;
}
@Override
@Deprecated
public void setMethod(String fulfillmentMethod) {
this.method = fulfillmentMethod;
}
@Override
public Money getRetailFulfillmentPrice() {
return retailFulfillmentPrice == null ? null :
SparkCurrencyUtils.getMoney(retailFulfillmentPrice, getOrder().getCurrency());
}
@Override
public void setRetailFulfillmentPrice(Money retailFulfillmentPrice) {
this.retailFulfillmentPrice = Money.toAmount(retailFulfillmentPrice);
}
@Override
public Money getRetailShippingPrice() {
return getRetailFulfillmentPrice();
}
@Override
public void setRetailShippingPrice(Money retailShippingPrice) {
setRetailFulfillmentPrice(retailShippingPrice);
}
@Override
public FulfillmentType getType() {
return FulfillmentType.getInstance(type);
}
@Override
public void setType(FulfillmentType type) {
this.type = type == null ? null : type.getType();
}
@Override
public void addCandidateFulfillmentGroupOffer(CandidateFulfillmentGroupOffer candidateOffer) {
candidateOffers.add(candidateOffer);
}
@Override
public List<CandidateFulfillmentGroupOffer> getCandidateFulfillmentGroupOffers() {
return candidateOffers;
}
@Override
public void setCandidateFulfillmentGroupOffer(List<CandidateFulfillmentGroupOffer> candidateOffers) {
this.candidateOffers = candidateOffers;
}
@Override
public void removeAllCandidateOffers() {
if (candidateOffers != null) {
for (CandidateFulfillmentGroupOffer offer : candidateOffers) {
offer.setFulfillmentGroup(null);
}
candidateOffers.clear();
}
}
@Override
public List<FulfillmentGroupAdjustment> getFulfillmentGroupAdjustments() {
return this.fulfillmentGroupAdjustments;
}
@Override
public Money getFulfillmentGroupAdjustmentsValue() {
Money adjustmentsValue = SparkCurrencyUtils.getMoney(BigDecimal.ZERO, getOrder().getCurrency());
for (FulfillmentGroupAdjustment adjustment : fulfillmentGroupAdjustments) {
adjustmentsValue = adjustmentsValue.add(adjustment.getValue());
}
return adjustmentsValue;
}
@Override
public void removeAllAdjustments() {
if (fulfillmentGroupAdjustments != null) {
for (FulfillmentGroupAdjustment adjustment : fulfillmentGroupAdjustments) {
adjustment.setFulfillmentGroup(null);
}
fulfillmentGroupAdjustments.clear();
}
}
@Override
public void setFulfillmentGroupAdjustments(List<FulfillmentGroupAdjustment> fulfillmentGroupAdjustments) {
this.fulfillmentGroupAdjustments = fulfillmentGroupAdjustments;
}
@Override
public Money getSaleFulfillmentPrice() {
return saleFulfillmentPrice == null ? null : SparkCurrencyUtils.getMoney(saleFulfillmentPrice,
getOrder().getCurrency());
}
@Override
public void setSaleFulfillmentPrice(Money saleFulfillmentPrice) {
this.saleFulfillmentPrice = Money.toAmount(saleFulfillmentPrice);
}
@Override
public Money getSaleShippingPrice() {
return getSaleFulfillmentPrice();
}
@Override
public void setSaleShippingPrice(Money saleShippingPrice) {
setSaleFulfillmentPrice(saleShippingPrice);
}
@Override
public Money getFulfillmentPrice() {
return fulfillmentPrice == null ? null : SparkCurrencyUtils.getMoney(fulfillmentPrice,
getOrder().getCurrency());
}
@Override
public void setFulfillmentPrice(Money fulfillmentPrice) {
this.fulfillmentPrice = Money.toAmount(fulfillmentPrice);
}
@Override
public Money getShippingPrice() {
return getFulfillmentPrice();
}
@Override
public void setShippingPrice(Money shippingPrice) {
setFulfillmentPrice(shippingPrice);
}
@Override
public List<TaxDetail> getTaxes() {
return taxes;
}
@Override
public void setTaxes(List<TaxDetail> taxes) {
this.taxes = taxes;
}
@Override
public Money getTotalTax() {
return totalTax == null ? null : SparkCurrencyUtils.getMoney(totalTax, getOrder().getCurrency());
}
@Override
public void setTotalTax(Money totalTax) {
this.totalTax = Money.toAmount(totalTax);
}
@Override
public Money getTotalItemTax() {
return totalItemTax == null ? null : SparkCurrencyUtils.getMoney(totalItemTax, getOrder().getCurrency());
}
@Override
public void setTotalItemTax(Money totalItemTax) {
this.totalItemTax = Money.toAmount(totalItemTax);
}
@Override
public Money getTotalFeeTax() {
return totalFeeTax == null ? null : SparkCurrencyUtils.getMoney(totalFeeTax, getOrder().getCurrency());
}
@Override
public void setTotalFeeTax(Money totalFeeTax) {
this.totalFeeTax = Money.toAmount(totalFeeTax);
}
@Override
public Money getTotalFulfillmentGroupTax() {
return totalFulfillmentGroupTax == null ? null : SparkCurrencyUtils.getMoney(totalFulfillmentGroupTax,
getOrder().getCurrency());
}
@Override
public void setTotalFulfillmentGroupTax(Money totalFulfillmentGroupTax) {
this.totalFulfillmentGroupTax = Money.toAmount(totalFulfillmentGroupTax);
}
@Override
public String getDeliveryInstruction() {
return deliveryInstruction;
}
@Override
public void setDeliveryInstruction(String deliveryInstruction) {
this.deliveryInstruction = deliveryInstruction;
}
@Override
public PersonalMessage getPersonalMessage() {
return personalMessage;
}
@Override
public void setPersonalMessage(PersonalMessage personalMessage) {
this.personalMessage = personalMessage;
}
@Override
public boolean isPrimary() {
return primary;
}
@Override
public void setPrimary(boolean primary) {
this.primary = primary;
}
@Override
public Money getMerchandiseTotal() {
return merchandiseTotal == null ? null : SparkCurrencyUtils.getMoney(merchandiseTotal,
getOrder().getCurrency());
}
@Override
public void setMerchandiseTotal(Money merchandiseTotal) {
this.merchandiseTotal = Money.toAmount(merchandiseTotal);
}
@Override
public Money getTotal() {
return total == null ? null : SparkCurrencyUtils.getMoney(total, getOrder().getCurrency());
}
@Override
public void setTotal(Money orderTotal) {
this.total = Money.toAmount(orderTotal);
}
@Override
public FulfillmentGroupStatusType getStatus() {
return FulfillmentGroupStatusType.getInstance(status);
}
@Override
public void setStatus(FulfillmentGroupStatusType status) {
this.status = status.getType();
}
@Override
public List<FulfillmentGroupFee> getFulfillmentGroupFees() {
return fulfillmentGroupFees;
}
@Override
public void setFulfillmentGroupFees(List<FulfillmentGroupFee> fulfillmentGroupFees) {
this.fulfillmentGroupFees = fulfillmentGroupFees;
}
@Override
public void addFulfillmentGroupFee(FulfillmentGroupFee fulfillmentGroupFee) {
if (fulfillmentGroupFees == null) {
fulfillmentGroupFees = new ArrayList<FulfillmentGroupFee>();
}
fulfillmentGroupFees.add(fulfillmentGroupFee);
}
@Override
public void removeAllFulfillmentGroupFees() {
if (fulfillmentGroupFees != null) {
fulfillmentGroupFees.clear();
}
}
@Override
public Boolean isShippingPriceTaxable() {
return isShippingPriceTaxable;
}
@Override
public void setIsShippingPriceTaxable(Boolean isShippingPriceTaxable) {
this.isShippingPriceTaxable = isShippingPriceTaxable;
}
@Override
public void setSequence(Integer sequence) {
this.sequence = sequence;
}
@Override
public Integer getSequence() {
return this.sequence;
}
@Override
@Deprecated
public String getService() {
return service;
}
@Override
@Deprecated
public void setService(String service) {
this.service = service;
}
@Override
public String getCurrencyCode() {
if (getOrder().getCurrency() != null) {
return getOrder().getCurrency().getCurrencyCode();
}
return null;
}
@Override
public Boolean getShippingOverride() {
return shippingOverride == null ? false : shippingOverride;
}
@Override
public void setShippingOverride(Boolean shippingOverride) {
this.shippingOverride = shippingOverride;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + ((fulfillmentGroupItems == null) ? 0 : fulfillmentGroupItems.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!getClass().isAssignableFrom(obj.getClass())) {
return false;
}
FulfillmentGroupImpl other = (FulfillmentGroupImpl) obj;
if (id != null && other.id != null) {
return id.equals(other.id);
}
if (address == null) {
if (other.address != null) {
return false;
}
} else if (!address.equals(other.address)) {
return false;
}
if (fulfillmentGroupItems == null) {
if (other.fulfillmentGroupItems != null) {
return false;
}
} else if (!fulfillmentGroupItems.equals(other.fulfillmentGroupItems)) {
return false;
}
return true;
}
public static class Presentation {
public static class Tab {
public static class Name {
public static final String Items = "FulfillmentGroupImpl_Items_Tab";
public static final String Pricing = "FulfillmentGroupImpl_Pricing_Tab";
public static final String Address = "FulfillmentGroupImpl_Address_Tab";
public static final String Advanced = "FulfillmentGroupImpl_Advanced_Tab";
}
public static class Order {
public static final int Items = 2000;
public static final int Pricing = 3000;
public static final int Address = 4000;
public static final int Advanced = 5000;
}
}
public static class Group {
public static class Name {
public static final String Pricing = "FulfillmentGroupImpl_Pricing";
}
public static class Order {
public static final int General = 1000;
public static final int Pricing = 2000;
}
}
public static class FieldOrder {
public static final int REFNUMBER = 3000;
public static final int STATUS = 4000;
public static final int TYPE = 5000;
public static final int DELIVERINSTRUCTION = 6000;
public static final int PRIMARY = 7000;
public static final int PHONE = 8000;
public static final int RETAIL = 1000;
public static final int SALE = 2000;
public static final int PRICE = 3000;
public static final int ITEMTAX = 4000;
public static final int FEETAX = 5000;
public static final int FGTAX = 6000;
public static final int TOTALTAX = 7000;
public static final int MERCHANDISETOTAL = 8000;
public static final int TOTAL = 9000;
public static final int TAXABLE = 10000;
}
}
}
| |
/*
* Copyright 2003-2011 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.siyeh.ig;
import com.intellij.codeInspection.BaseJavaBatchLocalInspectionTool;
import com.intellij.codeInspection.LocalInspectionToolSession;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.ui.DocumentAdapter;
import com.intellij.util.ui.UIUtil;
import com.siyeh.ig.telemetry.InspectionGadgetsTelemetry;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.text.Document;
import java.lang.reflect.Field;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.List;
public abstract class BaseInspection extends BaseJavaBatchLocalInspectionTool {
private static final Logger LOG = Logger.getInstance("#com.siyeh.ig.BaseInspection");
@NonNls private static final String INSPECTION = "Inspection";
@NonNls private static final String INSPECTION_BASE = "InspectionBase";
private String m_shortName = null;
private long timestamp = -1L;
@Override
@NotNull
public final String getShortName() {
if (m_shortName == null) {
final Class<? extends BaseInspection> aClass = getClass();
final String name = aClass.getName();
if (name.endsWith(INSPECTION)) {
m_shortName = name.substring(name.lastIndexOf((int)'.') + 1, name.length() - INSPECTION.length());
}
else if (name.endsWith(INSPECTION_BASE)) {
m_shortName = name.substring(name.lastIndexOf((int)'.') + 1, name.length() - INSPECTION_BASE.length());
}
else {
throw new AssertionError("class name must end with 'Inspection' to correctly calculate the short name: " + name);
}
}
return m_shortName;
}
@Nls
@NotNull
@Override
public abstract String getDisplayName();
@Override
@Nls
@NotNull
public final String getGroupDisplayName() {
return GroupDisplayNameUtil.getGroupDisplayName(getClass());
}
@NotNull
protected abstract String buildErrorString(Object... infos);
protected boolean buildQuickFixesOnlyForOnTheFlyErrors() {
return false;
}
@Nullable
protected InspectionGadgetsFix buildFix(Object... infos) {
return null;
}
@NotNull
protected InspectionGadgetsFix[] buildFixes(Object... infos) {
return InspectionGadgetsFix.EMPTY_ARRAY;
}
public abstract BaseInspectionVisitor buildVisitor();
@Override
@NotNull
public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder,
boolean isOnTheFly) {
final BaseInspectionVisitor visitor = buildVisitor();
visitor.setProblemsHolder(holder);
visitor.setOnTheFly(isOnTheFly);
visitor.setInspection(this);
return visitor;
}
protected JFormattedTextField prepareNumberEditor(@NonNls String fieldName) {
try {
final NumberFormat formatter = NumberFormat.getIntegerInstance();
formatter.setParseIntegerOnly(true);
final JFormattedTextField valueField = new JFormattedTextField(formatter);
final Field field = getClass().getField(fieldName);
valueField.setValue(field.get(this));
valueField.setColumns(2);
UIUtil.fixFormattedField(valueField);
final Document document = valueField.getDocument();
document.addDocumentListener(new DocumentAdapter() {
@Override
public void textChanged(DocumentEvent evt) {
try {
valueField.commitEdit();
final Number number = (Number)valueField.getValue();
field.set(BaseInspection.this,
Integer.valueOf(number.intValue()));
}
catch (IllegalAccessException e) {
LOG.error(e);
}
catch (ParseException e) {
// No luck this time. Will update the field when correct value is entered.
}
}
});
return valueField;
}
catch (NoSuchFieldException e) {
LOG.error(e);
}
catch (IllegalAccessException e) {
LOG.error(e);
}
return null;
}
protected static void parseString(String string, List<String>... outs) {
final List<String> strings = StringUtil.split(string, ",");
for (List<String> out : outs) {
out.clear();
}
int iMax = strings.size();
for (int i = 0; i < iMax; i += outs.length) {
for (int j = 0; j < outs.length; j++) {
final List<String> out = outs[j];
if (i + j >= iMax) {
out.add("");
}
else {
out.add(strings.get(i + j));
}
}
}
}
protected static String formatString(List<String>... strings) {
final StringBuilder buffer = new StringBuilder();
final int size = strings[0].size();
if (size > 0) {
formatString(strings, 0, buffer);
for (int i = 1; i < size; i++) {
buffer.append(',');
formatString(strings, i, buffer);
}
}
return buffer.toString();
}
private static void formatString(List<String>[] strings, int index,
StringBuilder out) {
out.append(strings[0].get(index));
for (int i = 1; i < strings.length; i++) {
out.append(',');
out.append(strings[i].get(index));
}
}
@Override
public void inspectionStarted(@NotNull LocalInspectionToolSession session, boolean isOnTheFly) {
super.inspectionStarted(session, isOnTheFly);
if (InspectionGadgetsTelemetry.isEnabled()) {
timestamp = System.currentTimeMillis();
}
}
@Override
public void inspectionFinished(@NotNull LocalInspectionToolSession session,
@NotNull ProblemsHolder problemsHolder) {
super.inspectionFinished(session, problemsHolder);
if (InspectionGadgetsTelemetry.isEnabled()) {
if (timestamp < 0L) {
LOG.warn("finish reported without corresponding start");
return;
}
final long end = System.currentTimeMillis();
final String displayName = getDisplayName();
InspectionGadgetsTelemetry.getInstance().reportRun(displayName, end - timestamp);
timestamp = -1L;
}
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Peter Skrypalle
*
* 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 dk.skrypalle.bpl.vm;
import dk.skrypalle.bpl.compiler.type.*;
import dk.skrypalle.bpl.util.*;
import dk.skrypalle.bpl.vm.err.*;
import java.util.*;
import static dk.skrypalle.bpl.vm.Bytecode.*;
class CPU {
static int MAX_STACK_SIZE = 0xffff;
private final VM vm;
private int ip;
private int sp;
private int fp;
private byte op;
byte[] code;
int ds_len;
private StackEntry[] stack;
CPU(VM vm, byte[] code) {
this.ds_len = Marshal.s32BE(code, 0);
this.vm = vm;
this.ip = VM.HEADER + ds_len;
this.sp = -1;
this.fp = 0;
this.code = code;
this.stack = new StackEntry[0];
}
void step() {
op = fetch();
if (vm.trace)
disassemble();
int addr, off, nArgs;
StackEntry lhs, rhs, cmp, arg;
long res;
long val;
switch (op) {
case NOP:
break;
case POP:
pop();
break;
case IPUSH:
val = fetchS64();
push(val, Types.lookup("int"));
break;
case IADD:
rhs = pop();
lhs = pop();
if (lhs.type != rhs.type)
throw new IllegalArgumentException(String.format("IADD:: want [INT,INT], have [%s,%s]", lhs.type, rhs.type));
res = lhs.val + rhs.val;
push(res, Types.lookup("int"));
break;
case ISUB:
rhs = pop();
lhs = pop();
if (lhs.type != rhs.type)
throw new IllegalArgumentException(String.format("ISUB:: want [INT,INT], have [%s,%s]", lhs.type, rhs.type));
res = lhs.val - rhs.val;
push(res, Types.lookup("int"));
break;
case IMUL:
rhs = pop();
lhs = pop();
if (lhs.type != rhs.type)
throw new IllegalArgumentException(String.format("IMUL:: want [INT,INT], have [%s,%s]", lhs.type, rhs.type));
res = lhs.val*rhs.val;
push(res, Types.lookup("int"));
break;
case IDIV:
rhs = pop();
lhs = pop();
if (lhs.type != rhs.type)
throw new IllegalArgumentException(String.format("IDIV:: want [INT,INT], have [%s,%s]", lhs.type, rhs.type));
res = lhs.val/rhs.val;
push(res, Types.lookup("int"));
break;
case ILT:
rhs = pop();
lhs = pop();
if (lhs.type != rhs.type)
throw new IllegalArgumentException(String.format("ILT:: want [INT,INT], have [%s,%s]", lhs.type, rhs.type));
res = lhs.val < rhs.val ? 1 : 0;
push(res, Types.lookup("int"));
break;
case IGT:
rhs = pop();
lhs = pop();
if (lhs.type != rhs.type)
throw new IllegalArgumentException(String.format("IGT:: want [INT,INT], have [%s,%s]", lhs.type, rhs.type));
res = lhs.val > rhs.val ? 1 : 0;
push(res, Types.lookup("int"));
break;
case ILTE:
rhs = pop();
lhs = pop();
if (lhs.type != rhs.type)
throw new IllegalArgumentException(String.format("ILTE:: want [INT,INT], have [%s,%s]", lhs.type, rhs.type));
res = lhs.val <= rhs.val ? 1 : 0;
push(res, Types.lookup("int"));
break;
case IGTE:
rhs = pop();
lhs = pop();
if (lhs.type != rhs.type)
throw new IllegalArgumentException(String.format("IGTE:: want [INT,INT], have [%s,%s]", lhs.type, rhs.type));
res = lhs.val >= rhs.val ? 1 : 0;
push(res, Types.lookup("int"));
break;
case IEQ:
rhs = pop();
lhs = pop();
if (lhs.type != rhs.type)
throw new IllegalArgumentException(String.format("IEQ:: want [INT,INT], have [%s,%s]", lhs.type, rhs.type));
res = lhs.val == rhs.val ? 1 : 0;
push(res, Types.lookup("int"));
break;
case INEQ:
rhs = pop();
lhs = pop();
if (lhs.type != rhs.type)
throw new IllegalArgumentException(String.format("INEQ:: want [INT,INT], have [%s,%s]", lhs.type, rhs.type));
res = lhs.val != rhs.val ? 1 : 0;
push(res, Types.lookup("int"));
break;
case ISTORE:
rhs = pop();
lhs = pop();
addr = fp + (int) lhs.val + 1;
sput(addr, rhs.val, rhs.type);
break;
case ILOAD:
lhs = pop();
addr = fp + (int) lhs.val + 1;
rhs = sget(addr);
push(rhs.val, rhs.type);
break;
case ADDR_OF:
lhs = pop();
addr = fp + (int) lhs.val + 1;
push(addr, Types.ref(lhs.type));
break;
case VAL_OF:
lhs = pop();
addr = (int) lhs.val;
rhs = sget(addr);
push(rhs.val, rhs.type);
break;
case RESOLVE:
lhs = pop();
push(lhs.val - fp - 1, Types.lookup("int"));
break;
case SPUSH:
int t = fetchS32();
addr = fetchS32();
push(addr, Types.lookup(t));
break;
case SLOAD:
lhs = pop();
addr = fp + (int) lhs.val + 1;
rhs = sget(addr);
push(rhs.val, rhs.type);
break;
case CALL:
addr = fetchS32();
nArgs = fetchS32();
push(nArgs, Types.lookup("int"));
push(fp, Types.lookup("int"));
push(ip, Types.lookup("int"));
fp = sp;
ip = addr;
if (ip < 0 || ip >= code.length)
throw new ArrayIndexOutOfBoundsException(String.format("call to invalid addr 0x%08x\n", ip));
break;
case RET:
rhs = pop();
sp = fp;
StackEntry _ip = pop();
StackEntry _fp = pop();
StackEntry _nArgs = pop();
if (_ip.type != Types.lookup("int"))
throw new IllegalArgumentException(String.format("RET:: want ip[INT], have ip[%s]", _ip.type));
if (_fp.type != Types.lookup("int"))
throw new IllegalArgumentException(String.format("RET:: want fp[INT], have fp[%s]", _fp.type));
if (_nArgs.type != Types.lookup("int"))
throw new IllegalArgumentException(String.format("RET:: want nArgs[INT], have nArgs[%s]", _nArgs.type));
ip = (int) _ip.val;
fp = (int) _fp.val;
nArgs = (int) _nArgs.val;
sp -= nArgs;
push(rhs.val, rhs.type);
break;
case LOCALS:
// sp += fetchS32();
// while (sp >= stack.length)
// growStack();
int l = fetchS32();
// simulate garbage in local storage
for (int i = 0; i < l; i++)
push((long) (Math.random()*23452345.0), Types.lookup("int"));
break;
case JMP:
off = fetchS32();
ip += off;
if (ip < 0 || ip >= code.length)
throw new ArrayIndexOutOfBoundsException(String.format("jmp to invalid addr 0x%08x --> 0x%08x\n", ip - off, ip));
break;
case BRNE:
off = fetchS32();
cmp = pop();
if (cmp.type != Types.lookup("int"))
throw new IllegalArgumentException(String.format("BRNE:: want [INT], have [%s]", cmp.type));
if (cmp.val != 0)
ip += off;
break;
case BREQ:
off = fetchS32();
cmp = pop();
if (cmp.type != Types.lookup("int"))
throw new IllegalArgumentException(String.format("BREQ:: want [INT], have [%s]", cmp.type));
if (cmp.val == 0)
ip += off;
break;
case PRINT:
off = fetchS32();
Deque<StackEntry> args = new ArrayDeque<>();
for (int i = 0; i < off; i++) {
args.push(pop());
}
for (int i = 0; i < off; i++) {
arg = args.pop();
switch (arg.type.name) { // TODO
case "int":
vm.out(String.format("%x", arg.val));
break;
case "string":
addr = (int) arg.val;
int len = Marshal.s32BE(code, addr);
addr += 4;
String s = new String(code, addr, len, IO.UTF8);
vm.out(s);
break;
default:
vm.out(String.format("Don't know, how to print [%s] addr=0x%08x", arg.type, arg.val));
break;
}
}
break;
case HALT:
break;
default:
throw new BPLVMIllegalStateError(op);
}
if (vm.trace)
traceStack();
}
boolean hasInstructions() {
return op != HALT && ip < code.length;
}
int exitCode() {
return (int) stack[sp].val;
}
//region mem code
private byte fetch() {
return code[ip++];
}
private int fetchS32() {
int val = Marshal.s32BE(code, ip);
ip += 4;
return val;
}
private long fetchS64() {
long val = Marshal.s64BE(code, ip);
ip += 8;
return val;
}
//endregion
//region mem stack
private void push(long val, Type type) {
sp++;
if (sp == stack.length)
growStack();
stack[sp].val = val;
stack[sp].type = type;
}
private StackEntry pop() {
if (sp < 0)
throw new BPLVMStackUnderflowError();
return stack[sp--];
}
private StackEntry sget(int addr) {
if (addr < 0)
throw new BPLVMStackUnderflowError();
return stack[addr];
}
private void sput(int addr, long val, Type type) {
if (addr < 0)
throw new BPLVMStackUnderflowError();
stack[addr].val = val;
stack[addr].type = type;
}
private void growStack() {
int newLen = stack.length*2;
if (newLen == 0)
newLen = 1;
if (newLen > MAX_STACK_SIZE)
throw new BPLVMStackOverflowError(newLen, MAX_STACK_SIZE);
StackEntry[] newStack = new StackEntry[newLen];
for (int i = 0; i < newLen; i++)
newStack[i] = new StackEntry();
System.arraycopy(stack, 0, newStack, 0, stack.length);
stack = newStack;
}
//endregion
//region trace
private void disassemble() {
Op inst = Bytecode.opCodes.get(op);
if (inst == null)
throw new IllegalStateException(String.format("Illegal op code 0x%02x", op));
StringBuilder argBuf = new StringBuilder();
argBuf.append('[');
for (int i = 0; i < inst.nArgs; i++) {
argBuf.append(String.format("0x%02x", code[ip + i]));
if (i < inst.nArgs - 1)
argBuf.append(", ");
}
argBuf.append(']');
String trace = String.format("%08x (0x%02x) %-8s %s", ip - 1, op, inst.name, argBuf.toString());
vm.trace(String.format("%-80s", trace));
}
private void traceStack() {
StringBuilder stackBuf = new StringBuilder();
stackBuf.append('[');
for (int i = 0; i < sp + 1; i++) {
stackBuf.append(String.format("0x%x(%s)", stack[i].val, stack[i].type));
if (i < sp)
stackBuf.append(", ");
}
stackBuf.append(']');
vm.trace(String.format("stack=%s", stackBuf));
}
//endregion
private static class StackEntry {
private long val;
private Type type;
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof StackEntry)) return false;
StackEntry other = (StackEntry) obj;
return this.val == other.val
&& this.type == other.type;
}
@Override
public String toString() {
return String.format("StackEntry{val=0x%016x, type=%s}", val, type);
}
}
}
| |
/**
* 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.hbase.replication;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.hadoop.hbase.Abortable;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hbase.HBaseInterfaceAudience;
import org.apache.hadoop.hbase.TableDescriptors;
import org.apache.hadoop.hbase.wal.WAL.Entry;
import org.apache.hadoop.hbase.replication.regionserver.MetricsSource;
/**
* ReplicationEndpoint is a plugin which implements replication
* to other HBase clusters, or other systems. ReplicationEndpoint implementation
* can be specified at the peer creation time by specifying it
* in the {@link ReplicationPeerConfig}. A ReplicationEndpoint is run in a thread
* in each region server in the same process.
* <p>
* ReplicationEndpoint is closely tied to ReplicationSource in a producer-consumer
* relation. ReplicationSource is an HBase-private class which tails the logs and manages
* the queue of logs plus management and persistence of all the state for replication.
* ReplicationEndpoint on the other hand is responsible for doing the actual shipping
* and persisting of the WAL entries in the other cluster.
*/
@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.REPLICATION)
public interface ReplicationEndpoint extends ReplicationPeerConfigListener {
// TODO: This class needs doc. Has a Context and a ReplicationContext. Then has #start, #stop.
// How they relate? Do we #start before #init(Context)? We fail fast if you don't?
@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.REPLICATION)
class Context {
private final Configuration conf;
private final FileSystem fs;
private final TableDescriptors tableDescriptors;
private final ReplicationPeer replicationPeer;
private final String peerId;
private final UUID clusterId;
private final MetricsSource metrics;
private final Abortable abortable;
@InterfaceAudience.Private
public Context(
final Configuration conf,
final FileSystem fs,
final String peerId,
final UUID clusterId,
final ReplicationPeer replicationPeer,
final MetricsSource metrics,
final TableDescriptors tableDescriptors,
final Abortable abortable) {
this.conf = conf;
this.fs = fs;
this.clusterId = clusterId;
this.peerId = peerId;
this.replicationPeer = replicationPeer;
this.metrics = metrics;
this.tableDescriptors = tableDescriptors;
this.abortable = abortable;
}
public Configuration getConfiguration() {
return conf;
}
public FileSystem getFilesystem() {
return fs;
}
public UUID getClusterId() {
return clusterId;
}
public String getPeerId() {
return peerId;
}
public ReplicationPeerConfig getPeerConfig() {
return replicationPeer.getPeerConfig();
}
public ReplicationPeer getReplicationPeer() {
return replicationPeer;
}
public MetricsSource getMetrics() {
return metrics;
}
public TableDescriptors getTableDescriptors() {
return tableDescriptors;
}
public Abortable getAbortable() { return abortable; }
}
/**
* Initialize the replication endpoint with the given context.
* @param context replication context
* @throws IOException
*/
void init(Context context) throws IOException;
/** Whether or not, the replication endpoint can replicate to it's source cluster with the same
* UUID */
boolean canReplicateToSameCluster();
/**
* Returns a UUID of the provided peer id. Every HBase cluster instance has a persisted
* associated UUID. If the replication is not performed to an actual HBase cluster (but
* some other system), the UUID returned has to uniquely identify the connected target system.
* @return a UUID or null if the peer cluster does not exist or is not connected.
*/
UUID getPeerUUID();
/**
* Returns a WALEntryFilter to use for filtering out WALEntries from the log. Replication
* infrastructure will call this filter before sending the edits to shipEdits().
* @return a {@link WALEntryFilter} or null.
*/
WALEntryFilter getWALEntryfilter();
/**
* A context for {@link ReplicationEndpoint#replicate(ReplicateContext)} method.
*/
@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.REPLICATION)
static class ReplicateContext {
List<Entry> entries;
int size;
String walGroupId;
@InterfaceAudience.Private
public ReplicateContext() {
}
public ReplicateContext setEntries(List<Entry> entries) {
this.entries = entries;
return this;
}
public ReplicateContext setSize(int size) {
this.size = size;
return this;
}
public ReplicateContext setWalGroupId(String walGroupId) {
this.walGroupId = walGroupId;
return this;
}
public List<Entry> getEntries() {
return entries;
}
public int getSize() {
return size;
}
public String getWalGroupId(){
return walGroupId;
}
}
/**
* Replicate the given set of entries (in the context) to the other cluster.
* Can block until all the given entries are replicated. Upon this method is returned,
* all entries that were passed in the context are assumed to be persisted in the
* target cluster.
* @param replicateContext a context where WAL entries and other
* parameters can be obtained.
*/
boolean replicate(ReplicateContext replicateContext);
// The below methods are inspired by Guava Service. See
// https://github.com/google/guava/wiki/ServiceExplained for overview of Guava Service.
// Below we implement a subset only with different names on some methods so we can implement
// the below internally using Guava (without exposing our implementation to
// ReplicationEndpoint implementors.
/**
* Returns {@code true} if this service is RUNNING.
*/
boolean isRunning();
/**
* @return Return {@code true} is this service is STARTING (but not yet RUNNING).
*/
boolean isStarting();
/**
* Initiates service startup and returns immediately. A stopped service may not be restarted.
* Equivalent of startAsync call in Guava Service.
* @throws IllegalStateException if the service is not new, if it has been run already.
*/
void start();
/**
* Waits for the {@link ReplicationEndpoint} to be up and running.
*
* @throws IllegalStateException if the service reaches a state from which it is not possible to
* enter the (internal) running state. e.g. if the state is terminated when this method is
* called then this will throw an IllegalStateException.
*/
void awaitRunning();
/**
* Waits for the {@link ReplicationEndpoint} to to be up and running for no more
* than the given time.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @throws TimeoutException if the service has not reached the given state within the deadline
* @throws IllegalStateException if the service reaches a state from which it is not possible to
* enter the (internal) running state. e.g. if the state is terminated when this method is
* called then this will throw an IllegalStateException.
*/
void awaitRunning(long timeout, TimeUnit unit) throws TimeoutException;
/**
* If the service is starting or running, this initiates service shutdown and returns immediately.
* If the service has already been stopped, this method returns immediately without taking action.
* Equivalent of stopAsync call in Guava Service.
*/
void stop();
/**
* Waits for the {@link ReplicationEndpoint} to reach the terminated (internal) state.
*
* @throws IllegalStateException if the service FAILED.
*/
void awaitTerminated();
/**
* Waits for the {@link ReplicationEndpoint} to reach a terminal state for no
* more than the given time.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @throws TimeoutException if the service has not reached the given state within the deadline
* @throws IllegalStateException if the service FAILED.
*/
void awaitTerminated(long timeout, TimeUnit unit) throws TimeoutException;
/**
* Returns the {@link Throwable} that caused this service to fail.
*
* @throws IllegalStateException if this service's state isn't FAILED.
*/
Throwable failureCause();
}
| |
/*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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 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/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.apache.jk.apr;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Hashtable;
import org.apache.jk.core.JkHandler;
import org.apache.jk.core.MsgContext;
/** Implements the interface with the APR library. This is for internal-use
* only. The goal is to use 'natural' mappings for user code - for example
* java.net.Socket for unix-domain sockets, etc.
*
*/
public class AprImpl extends JkHandler { // This will be o.a.t.util.handler.TcHandler - lifecycle and config
static AprImpl aprSingleton=null;
String baseDir;
String aprHome;
String soExt="so";
static boolean ok=true;
boolean initialized=false;
// Handlers for native callbacks
Hashtable jkHandlers=new Hashtable();
// Name of the so used in inprocess mode
String jniModeSo="inprocess";
// name of the so used by java. If not set we'll loadLibrary("jkjni" ),
// if set we load( nativeSo )
String nativeSo;
public AprImpl() {
aprSingleton=this;
}
// -------------------- Properties --------------------
/** Native libraries are located based on base dir.
* XXX Add platform, version, etc
*/
public void setBaseDir(String s) {
baseDir=s;
}
public void setSoExt(String s ) {
soExt=s;
}
// XXX maybe install the jni lib in apr-home ?
public void setAprHome( String s ) {
aprHome=s;
}
/** Add a Handler for jni callbacks.
*/
public void addJkHandler(String type, JkHandler cb) {
jkHandlers.put( type, cb );
}
/** Name of the so used in inprocess mode
*/
public void setJniModeSo(String jniModeSo ) {
this.jniModeSo=jniModeSo;
}
/** name of the so used by java. If not set we'll loadLibrary("jkjni" ),
if set we load( nativeSo )
*/
public void setNativeSo( String nativeSo ) {
this.nativeSo=nativeSo;
}
/** Sets the System.out stream */
public static void setOut( String filename ) {
try{
if( filename !=null ){
System.setOut( new PrintStream(new FileOutputStream(filename )));
}
}catch (Throwable th){
}
}
/** Sets the System.err stream */
public static void setErr( String filename ) {
try{
if( filename !=null ){
System.setErr( new PrintStream(new FileOutputStream(filename )));
}
}catch (Throwable th){
}
}
// -------------------- Apr generic utils --------------------
/** Initialize APR
*/
public native int initialize();
public native int terminate();
/* -------------------- Access to the jk_env_t -------------------- */
/* The jk_env_t provide temporary storage ( pool ), logging, common services
*/
/* Return a jk_env_t, used to keep the execution context ( temp pool, etc )
*/
public native long getJkEnv();
/** Clean the temp pool, put back the env in the pool
*/
public native void releaseJkEnv(long xEnv);
/* -------------------- Interface to the jk_bean object -------------------- */
/* Each jk component is 'wrapped' as a bean, with a specified lifecycle
*
*/
/** Get a native component
* @return 0 if the component is not found.
*/
public native long getJkHandler(long xEnv, String compName );
public native long createJkHandler(long xEnv, String compName );
public native int jkSetAttribute( long xEnv, long componentP, String name, String val );
public native String jkGetAttribute( long xEnv, long componentP, String name );
public native int jkInit( long xEnv, long componentP );
public native int jkDestroy( long xEnv, long componentP );
/** Send the packet to the C side. On return it contains the response
* or indication there is no response. Asymetrical because we can't
* do things like continuations.
*/
public static native int jkInvoke(long xEnv, long componentP, long endpointP,
int code, byte data[], int off, int len, int raw);
/** Recycle an endpoint after use.
*/
public native void jkRecycle(long xEnv, long endpointP);
// -------------------- Called from C --------------------
// XXX Check security, add guard or other protection
// It's better to do it the other way - on init 'push' AprImpl into
// the native library, and have native code call instance methods.
public static Object createJavaContext(String type, long cContext) {
// XXX will be an instance method, fields accessible directly
AprImpl apr=aprSingleton;
JkHandler jkH=(JkHandler)apr.jkHandlers.get( type );
if( jkH==null ) return null;
MsgContext ep=jkH.createMsgContext();
ep.setSource( jkH );
ep.setJniContext( cContext );
return ep;
}
/** Return a buffer associated with the ctx.
*/
public static byte[] getBuffer( Object ctx, int id ) {
return ((MsgContext)ctx).getBuffer( id );
}
public static int jniInvoke( long jContext, Object ctx ) {
try {
MsgContext ep=(MsgContext)ctx;
ep.setJniEnv( jContext );
ep.setType( 0 );
return ((MsgContext)ctx).execute();
} catch( Throwable ex ) {
ex.printStackTrace();
return -1;
}
}
// -------------------- Initialization --------------------
public void init() throws IOException {
try {
initialized=true;
loadNative();
initialize();
jkSetAttribute(0, 0, "channel:jni", "starting");
log.info("JK2: Initialized apr" );
} catch( Throwable t ) {
throw new IOException( t.toString() );
}
ok=true;
}
public boolean isLoaded() {
if( ! initialized ) {
try {
init();
} catch( Throwable t ) {
log.info("Apr not loaded: " + t);
}
}
return ok;
}
static boolean jniMode=false;
public static void jniMode() {
jniMode=true;
}
/** This method of loading the libs doesn't require setting
* LD_LIBRARY_PATH. Assuming a 'right' binary distribution,
* or a correct build all files will be in their right place.
*
* The burden is on our code to deal with platform specific
* extensions and to keep the paths consistent - not easy, but
* worth it if it avoids one extra step for the user.
*
* Of course, this can change to System.load() and putting the
* libs in LD_LIBRARY_PATH.
*/
public void loadNative() throws Throwable {
if( aprHome==null )
aprHome=baseDir;
// XXX Update for windows
if( jniMode ) {
/* In JNI mode we use mod_jk for the native functions.
This seems the cleanest solution that works with multiple
VMs.
*/
if (jniModeSo.equals("inprocess")) {
ok=true;
return;
}
try {
log.info("Loading " + jniModeSo);
if( jniModeSo!= null ) System.load( jniModeSo );
} catch( Throwable ex ) {
// ignore
//ex.printStackTrace();
return;
}
ok=true;
return;
}
/*
jkjni _must_ be linked with apr and crypt -
this seem the only ( decent ) way to support JDK1.4 and
JDK1.3 at the same time
try {
System.loadLibrary( "crypt" );
} catch( Throwable ex ) {
// ignore
ex.printStackTrace();
}
try {
System.loadLibrary( "apr" );
} catch( Throwable ex ) {
System.out.println("can't load apr, that's fine");
ex.printStackTrace();
}
*/
try {
if( nativeSo == null ) {
// This will load libjkjni.so or jkjni.dll in LD_LIBRARY_PATH
log.debug("Loading jkjni from " + System.getProperty("java.library.path"));
System.loadLibrary( "jkjni" );
} else {
System.load( nativeSo );
}
} catch( Throwable ex ) {
ok=false;
//ex.printStackTrace();
throw ex;
}
}
public void loadNative(String libPath) {
try {
System.load( libPath );
} catch( Throwable ex ) {
ok=false;
if( log.isDebugEnabled() )
log.debug( "Error loading native library ", ex);
}
}
private static org.apache.commons.logging.Log log=
org.apache.commons.logging.LogFactory.getLog( AprImpl.class );
}
| |
package io.hentitydb.store.hbase;
import io.hentitydb.serialization.Codec;
import io.hentitydb.store.CompareOp;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import java.util.Date;
public class HBasePut<K, C> extends HBaseRowMutation<K, C> implements io.hentitydb.store.Put<K, C> {
private final String defaultFamily;
private final Put put;
private final Codec<C> columnCodec;
public HBasePut(K key, String defaultFamily, Codec<K> keyCodec, Codec<C> columnCodec) {
super(key, null);
this.defaultFamily = defaultFamily;
this.columnCodec = columnCodec;
this.put = new Put(HBaseUtil.keyToBytes(key, keyCodec));
}
public HBasePut(K key, HBaseTable<K, C> table) {
super(key, table);
this.defaultFamily = table.getMetadata().getDefaultFamily();
this.columnCodec = table.getMetadata().getColumnCodec();
this.put = new Put(HBaseUtil.keyToBytes(key, table.getMetadata()));
}
public HBasePut(byte[] rawKey, String defaultFamily, Codec<C> columnCodec) {
super(null, null);
this.defaultFamily = defaultFamily;
this.columnCodec = columnCodec;
this.put = new Put(rawKey);
}
@Override
public Put getHOperation() {
return put;
}
@Override
public HBasePut<K, C> addColumn(C column, boolean value) {
return addColumn(defaultFamily, column, value);
}
@Override
public HBasePut<K, C> addColumn(String family, C column, boolean value) {
put.addImmutable(Bytes.toBytes(family), columnCodec.encode(column), Bytes.toBytes(value));
return this;
}
@Override
public HBasePut<K, C> addColumn(C column, short value) {
return addColumn(defaultFamily, column, value);
}
@Override
public HBasePut<K, C> addColumn(String family, C column, short value) {
put.addImmutable(Bytes.toBytes(family), columnCodec.encode(column), Bytes.toBytes(value));
return this;
}
@Override
public HBasePut<K, C> addColumn(C column, int value) {
return addColumn(defaultFamily, column, value);
}
@Override
public HBasePut<K, C> addColumn(String family, C column, int value) {
put.addImmutable(Bytes.toBytes(family), columnCodec.encode(column), Bytes.toBytes(value));
return this;
}
@Override
public HBasePut<K, C> addColumn(C column, long value) {
return addColumn(defaultFamily, column, value);
}
@Override
public HBasePut<K, C> addColumn(String family, C column, long value) {
put.addImmutable(Bytes.toBytes(family), columnCodec.encode(column), Bytes.toBytes(value));
return this;
}
@Override
public HBasePut<K, C> addColumn(C column, Date value) {
return addColumn(defaultFamily, column, value);
}
@Override
public HBasePut<K, C> addColumn(String family, C column, Date value) {
put.addImmutable(Bytes.toBytes(family), columnCodec.encode(column), Bytes.toBytes(value.getTime()));
return this;
}
@Override
public HBasePut<K, C> addColumn(C column, float value) {
return addColumn(defaultFamily, column, value);
}
@Override
public HBasePut<K, C> addColumn(String family, C column, float value) {
put.addImmutable(Bytes.toBytes(family), columnCodec.encode(column), Bytes.toBytes(value));
return this;
}
@Override
public HBasePut<K, C> addColumn(C column, double value) {
return addColumn(defaultFamily, column, value);
}
@Override
public HBasePut<K, C> addColumn(String family, C column, double value) {
put.addImmutable(Bytes.toBytes(family), columnCodec.encode(column), Bytes.toBytes(value));
return this;
}
@Override
public HBasePut<K, C> addColumn(C column, byte[] value) {
return addColumn(defaultFamily, column, value);
}
@Override
public HBasePut<K, C> addColumn(String family, C column, byte[] value) {
put.addImmutable(Bytes.toBytes(family), columnCodec.encode(column), value);
return this;
}
@Override
public HBasePut<K, C> addColumn(C column, String value) {
return addColumn(defaultFamily, column, value);
}
@Override
public HBasePut<K, C> addColumn(String family, C column, String value) {
put.addImmutable(Bytes.toBytes(family), columnCodec.encode(column), Bytes.toBytes(value));
return this;
}
@Override
public <V> HBasePut<K, C> addColumn(C column, V value, Codec<V> valueCodec) {
return addColumn(defaultFamily, column, value, valueCodec);
}
@Override
public <V> HBasePut<K, C> addColumn(String family, C column, V value, Codec<V> valueCodec) {
put.addImmutable(Bytes.toBytes(family), columnCodec.encode(column), valueCodec.encode(value));
return this;
}
@Override
public void execute() {
getTable().doPut(this);
}
@Override
public boolean executeIfAbsent(C column) {
return executeIfAbsent(defaultFamily, column);
}
@Override
public boolean executeIfAbsent(String family, C column) {
return getTable().doPutIf(family, column, CompareOp.EQUAL, null, this);
}
@Override
public boolean executeIf(C column, CompareOp compareOp, boolean value) {
return executeIf(defaultFamily, column, compareOp, value);
}
@Override
public boolean executeIf(String family, C column, CompareOp compareOp, boolean value) {
return getTable().doPutIf(family, column, compareOp, Bytes.toBytes(value), this);
}
@Override
public boolean executeIf(C column, CompareOp compareOp, short value) {
return executeIf(defaultFamily, column, compareOp, value);
}
@Override
public boolean executeIf(String family, C column, CompareOp compareOp, short value) {
return getTable().doPutIf(family, column, compareOp, Bytes.toBytes(value), this);
}
@Override
public boolean executeIf(C column, CompareOp compareOp, int value) {
return executeIf(defaultFamily, column, compareOp, value);
}
@Override
public boolean executeIf(String family, C column, CompareOp compareOp, int value) {
return getTable().doPutIf(family, column, compareOp, Bytes.toBytes(value), this);
}
@Override
public boolean executeIf(C column, CompareOp compareOp, long value) {
return executeIf(defaultFamily, column, compareOp, value);
}
@Override
public boolean executeIf(String family, C column, CompareOp compareOp, long value) {
return getTable().doPutIf(family, column, compareOp, Bytes.toBytes(value), this);
}
@Override
public boolean executeIf(C column, CompareOp compareOp, Date value) {
return executeIf(defaultFamily, column, compareOp, value);
}
@Override
public boolean executeIf(String family, C column, CompareOp compareOp, Date value) {
return getTable().doPutIf(family, column, compareOp, Bytes.toBytes(value.getTime()), this);
}
@Override
public boolean executeIf(C column, CompareOp compareOp, float value) {
return executeIf(defaultFamily, column, compareOp, value);
}
@Override
public boolean executeIf(String family, C column, CompareOp compareOp, float value) {
return getTable().doPutIf(family, column, compareOp, Bytes.toBytes(value), this);
}
@Override
public boolean executeIf(C column, CompareOp compareOp, double value) {
return executeIf(defaultFamily, column, compareOp, value);
}
@Override
public boolean executeIf(String family, C column, CompareOp compareOp, double value) {
return getTable().doPutIf(family, column, compareOp, Bytes.toBytes(value), this);
}
@Override
public boolean executeIf(C column, CompareOp compareOp, byte[] value) {
return executeIf(defaultFamily, column, compareOp, value);
}
@Override
public boolean executeIf(String family, C column, CompareOp compareOp, byte[] value) {
return getTable().doPutIf(family, column, compareOp, value, this);
}
@Override
public boolean executeIf(C column, CompareOp compareOp, String value) {
return executeIf(defaultFamily, column, compareOp, value);
}
@Override
public boolean executeIf(String family, C column, CompareOp compareOp, String value) {
return getTable().doPutIf(family, column, compareOp, Bytes.toBytes(value), this);
}
@Override
public <V> boolean executeIf(C column, CompareOp compareOp, V value, Codec<V> valueCodec) {
return executeIf(defaultFamily, column, compareOp, value, valueCodec);
}
@Override
public <V> boolean executeIf(String family, C column, CompareOp compareOp, V value, Codec<V> valueCodec) {
return getTable().doPutIf(family, column, compareOp, valueCodec.encode(value), this);
}
@Override
public HBasePut<K, C> setTTL(int ttl) {
put.setTTL(ttl);
return this;
}
}
| |
/**
* Copyright 2012-2014 eBay Software Foundation, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.ebay.myriad.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import org.hibernate.validator.constraints.NotEmpty;
import java.util.Map;
/**
* Myriad Configuration commonly defined in the YML file
* mesosMaster: 10.0.2.15:5050
* checkpoint: false
* frameworkFailoverTimeout: 43200000
* frameworkName: MyriadAlpha
* nativeLibrary: /usr/local/lib/libmesos.so
* zkServers: localhost:2181
* zkTimeout: 20000
* profiles:
* small:
* cpu: 1
* mem: 1100
* medium:
* cpu: 2
* mem: 2048
* large:
* cpu: 4
* mem: 4096
* rebalancer: false
* nodemanager:
* jvmMaxMemoryMB: 1024
* user: hduser
* cpus: 0.2
* cgroups: false
* executor:
* jvmMaxMemoryMB: 256
* path: file://localhost/usr/local/libexec/mesos/myriad-executor-runnable-0.0.1.jar
* yarnEnvironment:
* YARN_HOME: /usr/local/hadoop
*/
public class MyriadConfiguration {
/**
* By default framework checkpointing is turned off.
*/
public static final Boolean DEFAULT_CHECKPOINT = false;
/**
* By default rebalancer is turned off.
*/
public static final Boolean DEFAULT_REBALANCER = true;
/**
* By default framework failover timeout is 1 day.
*/
public static final Double DEFAULT_FRAMEWORK_FAILOVER_TIMEOUT_MS = 86400000.0;
public static final String DEFAULT_FRAMEWORK_NAME = "myriad-scheduler";
public static final String DEFAULT_NATIVE_LIBRARY = "/usr/local/lib/libmesos.so";
public static final Integer DEFAULT_ZK_TIMEOUT = 20000;
public static final Integer DEFAULT_REST_API_PORT = 8192;
@JsonProperty
@NotEmpty
private String mesosMaster;
@JsonProperty
private Boolean checkpoint;
@JsonProperty
private Double frameworkFailoverTimeout;
@JsonProperty
private String frameworkName;
@JsonProperty
private String frameworkRole;
@JsonProperty
private String frameworkUser;
@JsonProperty
private String frameworkSuperUser;
@JsonProperty
@NotEmpty
private Map<String, Map<String, String>> profiles;
@JsonProperty
private Boolean rebalancer;
@JsonProperty
private NodeManagerConfiguration nodemanager;
@JsonProperty
@NotEmpty
private MyriadExecutorConfiguration executor;
@JsonProperty
private String nativeLibrary;
@JsonProperty
@NotEmpty
private String zkServers;
@JsonProperty
private Integer zkTimeout;
@JsonProperty
private Integer restApiPort;
@JsonProperty
@NotEmpty
private Map<String, String> yarnEnvironment;
@JsonProperty
private String mesosAuthenticationPrincipal;
@JsonProperty
private String mesosAuthenticationSecretFilename;
public MyriadConfiguration() {
}
public String getMesosMaster() {
return mesosMaster;
}
public Boolean isCheckpoint() {
return this.checkpoint != null ? checkpoint : DEFAULT_CHECKPOINT;
}
public Double getFrameworkFailoverTimeout() {
return this.frameworkFailoverTimeout != null ? this.frameworkFailoverTimeout
: DEFAULT_FRAMEWORK_FAILOVER_TIMEOUT_MS;
}
public String getFrameworkName() {
return Strings.isNullOrEmpty(this.frameworkName) ? DEFAULT_FRAMEWORK_NAME
: this.frameworkName;
}
public String getFrameworkRole() {
return frameworkRole;
}
public Optional<String> getFrameworkUser() {
return Optional.fromNullable(frameworkUser);
}
public Optional<String> getFrameworkSuperUser() {
return Optional.fromNullable(frameworkSuperUser);
}
public Map<String, Map<String, String>> getProfiles() {
return profiles;
}
public Boolean isRebalancer() {
return rebalancer != null ? rebalancer : DEFAULT_REBALANCER;
}
public NodeManagerConfiguration getNodeManagerConfiguration() {
return this.nodemanager;
}
public MyriadExecutorConfiguration getMyriadExecutorConfiguration() {
return this.executor;
}
public String getNativeLibrary() {
return Strings.isNullOrEmpty(this.nativeLibrary) ? DEFAULT_NATIVE_LIBRARY : this.nativeLibrary;
}
public String getZkServers() {
return this.zkServers;
}
public Integer getZkTimeout() {
return this.zkTimeout != null ? this.zkTimeout : DEFAULT_ZK_TIMEOUT;
}
public Integer getRestApiPort() {
return this.restApiPort != null ? this.restApiPort : DEFAULT_REST_API_PORT;
}
public Map<String, String> getYarnEnvironment() {
return yarnEnvironment;
}
public String getMesosAuthenticationSecretFilename() {
return mesosAuthenticationSecretFilename;
}
public String getMesosAuthenticationPrincipal() {
return mesosAuthenticationPrincipal;
}
}
| |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Preconditions;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import javax.annotation.Nullable;
/**
* Implementation of {@link ImmutableList} with one or more elements.
*
* @author Kevin Bourrillion
*/
@GwtCompatible(serializable = true)
@SuppressWarnings("serial") // uses writeReplace(), not default serialization
final class RegularImmutableList<E> extends ImmutableList<E> {
private final transient int offset;
private final transient int size;
private final transient Object[] array;
RegularImmutableList(Object[] array, int offset, int size) {
this.offset = offset;
this.size = size;
this.array = array;
}
RegularImmutableList(Object[] array) {
this(array, 0, array.length);
}
public int size() {
return size;
}
@Override public boolean isEmpty() {
return false;
}
@Override public boolean contains(Object target) {
return indexOf(target) != -1;
}
// The fake cast to E is safe because the creation methods only allow E's
@SuppressWarnings("unchecked")
@Override public UnmodifiableIterator<E> iterator() {
return (UnmodifiableIterator<E>) Iterators.forArray(array, offset, size);
}
@Override public Object[] toArray() {
Object[] newArray = new Object[size()];
System.arraycopy(array, offset, newArray, 0, size);
return newArray;
}
@Override public <T> T[] toArray(T[] other) {
if (other.length < size) {
other = ObjectArrays.newArray(other, size);
} else if (other.length > size) {
other[size] = null;
}
System.arraycopy(array, offset, other, 0, size);
return other;
}
// The fake cast to E is safe because the creation methods only allow E's
@SuppressWarnings("unchecked")
public E get(int index) {
Preconditions.checkElementIndex(index, size);
return (E) array[index + offset];
}
@Override public int indexOf(Object target) {
if (target != null) {
for (int i = offset; i < offset + size; i++) {
if (array[i].equals(target)) {
return i - offset;
}
}
}
return -1;
}
@Override public int lastIndexOf(Object target) {
if (target != null) {
for (int i = offset + size - 1; i >= offset; i--) {
if (array[i].equals(target)) {
return i - offset;
}
}
}
return -1;
}
@Override public ImmutableList<E> subList(int fromIndex, int toIndex) {
Preconditions.checkPositionIndexes(fromIndex, toIndex, size);
return (fromIndex == toIndex)
? ImmutableList.<E>of()
: new RegularImmutableList<E>(
array, offset + fromIndex, toIndex - fromIndex);
}
public ListIterator<E> listIterator() {
return listIterator(0);
}
public ListIterator<E> listIterator(final int start) {
Preconditions.checkPositionIndex(start, size);
return new ListIterator<E>() {
int index = start;
public boolean hasNext() {
return index < size;
}
public boolean hasPrevious() {
return index > 0;
}
public int nextIndex() {
return index;
}
public int previousIndex() {
return index - 1;
}
public E next() {
E result;
try {
result = get(index);
} catch (IndexOutOfBoundsException rethrown) {
throw new NoSuchElementException();
}
index++;
return result;
}
public E previous() {
E result;
try {
result = get(index - 1);
} catch (IndexOutOfBoundsException rethrown) {
throw new NoSuchElementException();
}
index--;
return result;
}
public void set(E o) {
throw new UnsupportedOperationException();
}
public void add(E o) {
throw new UnsupportedOperationException();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (!(object instanceof List)) {
return false;
}
List<?> that = (List<?>) object;
if (this.size() != that.size()) {
return false;
}
int index = offset;
if (object instanceof RegularImmutableList) {
RegularImmutableList<?> other = (RegularImmutableList<?>) object;
for (int i = other.offset; i < other.offset + other.size; i++) {
if (!array[index++].equals(other.array[i])) {
return false;
}
}
} else {
for (Object element : that) {
if (!array[index++].equals(element)) {
return false;
}
}
}
return true;
}
@Override public int hashCode() {
// not caching hash code since it could change if the elements are mutable
// in a way that modifies their hash codes
int hashCode = 1;
for (int i = offset; i < offset + size; i++) {
hashCode = 31 * hashCode + array[i].hashCode();
}
return hashCode;
}
@Override public String toString() {
StringBuilder sb = new StringBuilder(size() * 16);
sb.append('[').append(array[offset]);
for (int i = offset + 1; i < offset + size; i++) {
sb.append(", ").append(array[i]);
}
return sb.append(']').toString();
}
}
| |
/*
* Copyright (C) 2012 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.dseuss.alarmclock;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.text.format.DateFormat;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService.RemoteViewsFactory;
import com.dseuss.deskclock.R;
import com.dseuss.deskclock.Utils;
import com.dseuss.deskclock.worldclock.CityObj;
import com.dseuss.deskclock.worldclock.WorldClockAdapter;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
public class DigitalWidgetViewsFactory implements RemoteViewsFactory {
private static final String TAG = "DigitalWidgetViewsFactory";
private Context mContext;
private Resources mResources;
private int mId = AppWidgetManager.INVALID_APPWIDGET_ID;
private RemoteWorldClockAdapter mAdapter;
private float mFontScale = 1;
// An adapter to provide the view for the list of cities in the world clock.
private class RemoteWorldClockAdapter extends WorldClockAdapter {
private final float mFontSize;
private final float mFont24Size;
public RemoteWorldClockAdapter(Context context) {
super(context);
mFontSize = context.getResources().getDimension(R.dimen.widget_medium_font_size);
mFont24Size = context.getResources().getDimension(R.dimen.widget_24_medium_font_size);
}
public RemoteViews getViewAt(int position) {
// There are 2 cities per item
int index = position * 2;
if (index < 0 || index >= mCitiesList.length) {
return null;
}
RemoteViews views = new RemoteViews(
mContext.getPackageName(), R.layout.world_clock_remote_list_item);
// Always how the left clock
updateView(views, (CityObj) mCitiesList[index], R.id.left_clock,
R.id.city_name_left, R.id.city_day_left);
// Show the right clock if any, make it invisible if there is no
// clock on the right
// to keep the left view on the left.
if (index + 1 < mCitiesList.length) {
updateView(views, (CityObj) mCitiesList[index + 1], R.id.right_clock,
R.id.city_name_right, R.id.city_day_right);
} else {
hideView(views, R.id.right_clock, R.id.city_name_right,
R.id.city_day_right);
}
// Hide last spacer if last row
int lastRow = ((mCitiesList.length + 1) / 2) - 1;
if (position == lastRow) {
views.setViewVisibility(R.id.city_spacer, View.GONE);
} else {
views.setViewVisibility(R.id.city_spacer, View.VISIBLE);
}
return views;
}
private void updateView(RemoteViews clock, CityObj cityObj, int clockId,
int labelId, int dayId) {
final Calendar now = Calendar.getInstance();
now.setTimeInMillis(System.currentTimeMillis());
int myDayOfWeek = now.get(Calendar.DAY_OF_WEEK);
CityObj cityInDb = mCitiesDb.get(cityObj.mCityId);
String cityTZ = (cityInDb != null) ? cityInDb.mTimeZone : cityObj.mTimeZone;
now.setTimeZone(TimeZone.getTimeZone(cityTZ));
int cityDayOfWeek = now.get(Calendar.DAY_OF_WEEK);
WidgetUtils.setTimeFormat(clock,
(int)mResources.getDimension(R.dimen.widget_label_font_size), clockId);
float fontSize = mFontScale * (DateFormat.is24HourFormat(mContext)
? mFont24Size : mFontSize);
clock.setTextViewTextSize(clockId, TypedValue.COMPLEX_UNIT_PX, fontSize * mFontScale);
clock.setString(clockId, "setTimeZone", cityObj.mTimeZone);
// Home city or city not in DB , use data from the save selected cities list
clock.setTextViewText(labelId, Utils.getCityName(cityObj, cityInDb));
if (myDayOfWeek != cityDayOfWeek) {
clock.setTextViewText(dayId, mContext.getString(
R.string.world_day_of_week_label, now.getDisplayName(
Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault())));
clock.setViewVisibility(dayId, View.VISIBLE);
} else {
clock.setViewVisibility(dayId, View.GONE);
}
clock.setViewVisibility(clockId, View.VISIBLE);
clock.setViewVisibility(labelId, View.VISIBLE);
}
private void hideView(
RemoteViews clock, int clockId, int labelId, int dayId) {
clock.setViewVisibility(clockId, View.INVISIBLE);
clock.setViewVisibility(labelId, View.INVISIBLE);
clock.setViewVisibility(dayId, View.INVISIBLE);
}
}
public DigitalWidgetViewsFactory(Context context, Intent intent) {
mContext = context;
mResources = mContext.getResources();
mId = intent.getIntExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
mAdapter = new RemoteWorldClockAdapter(context);
}
@SuppressWarnings("unused")
public DigitalWidgetViewsFactory() {
}
@Override
public int getCount() {
if (WidgetUtils.showList(mContext, mId, mFontScale)) {
return mAdapter.getCount();
}
return 0;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public RemoteViews getLoadingView() {
return null;
}
@Override
public RemoteViews getViewAt(int position) {
RemoteViews v = mAdapter.getViewAt(position);
if (v != null) {
Intent fillInIntent = new Intent();
v.setOnClickFillInIntent(R.id.widget_item, fillInIntent);
}
return v;
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public void onCreate() {
if (DigitalAppWidgetService.LOGGING) {
Log.i(TAG, "DigitalWidget onCreate " + mId);
}
}
@Override
public void onDataSetChanged() {
mAdapter.loadData(mContext);
mAdapter.loadCitiesDb(mContext);
mAdapter.updateHomeLabel(mContext);
mFontScale = WidgetUtils.getScaleRatio(mContext, null, mId);
}
@Override
public void onDestroy() {
if (DigitalAppWidgetService.LOGGING) {
Log.i(TAG, "DigitalWidget onDestroy " + mId);
}
}
}
| |
// Copyright (c) 2014 Dan Nagle. All rights reserved.
//
// Licensed MIT: https://github.com/dannagle/PacketSender-Android
package com.packetsender.android;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class NewPacketActivity extends Activity {
public DataStorage dataStore;
private Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_packet);
setTitle("Setup Packet");
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
dataStore = new DataStorage(
getSharedPreferences(DataStorage.PREFS_SETTINGS_NAME, 0),
getSharedPreferences(DataStorage.PREFS_SAVEDPACKETS_NAME, 0),
getSharedPreferences(DataStorage.PREFS_SERVICELOG_NAME, 0),
getSharedPreferences(DataStorage.PREFS_MAINTRAFFICLOG_NAME, 0)
);
mContext = getApplicationContext();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.new_packet, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private EditText nameEditText;
private EditText asciiEditText;
private EditText hexEditText;
private EditText ipEditText;
private EditText portEditText;
private Spinner methodSpinner;
private Button testButton;
private Button saveButton;
private boolean suppressListener;
public Packet getPacket() {
Packet returnPacket = new Packet();
returnPacket.name = nameEditText.getText().toString();
returnPacket.data = returnPacket.toBytes(hexEditText.getText().toString());
returnPacket.toIP = ipEditText.getText().toString();
returnPacket.port = Integer.parseInt(portEditText.getText().toString());
returnPacket.tcpOrUdp = methodSpinner.getSelectedItem().toString();
return returnPacket;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_new_packet, container, false);
suppressListener = false;
nameEditText = (EditText) rootView.findViewById(R.id.nameEditText);
asciiEditText = (EditText) rootView.findViewById(R.id.asciiEditText);
hexEditText = (EditText) rootView.findViewById(R.id.hexEditText);
ipEditText = (EditText) rootView.findViewById(R.id.ipEditText);
portEditText = (EditText) rootView.findViewById(R.id.portEditText);
methodSpinner = (Spinner) rootView.findViewById(R.id.methodSpinner);
testButton = (Button) rootView.findViewById(R.id.testButton);
saveButton = (Button) rootView.findViewById(R.id.saveButton);
NewPacketActivity NPA = (NewPacketActivity)getActivity();
Intent passedIntent = NPA.getIntent();
Packet receivedPacket = new Packet();
receivedPacket.UnitTest_conversions();
if(passedIntent.hasExtra(DataStorage.INTENT_OUT + "/name")) {
receivedPacket = DataStorage.getPacketFromIntent(NPA.getIntent());
}
if(!receivedPacket.name.isEmpty()) {
nameEditText.setText(receivedPacket.name);
asciiEditText.setText(receivedPacket.toAscii());
hexEditText.setText(receivedPacket.toHex());
ipEditText.setText(receivedPacket.toIP);
portEditText.setText(receivedPacket.port + "");
if(receivedPacket.tcpOrUdp.equalsIgnoreCase("udp")) {
methodSpinner.setSelection(1);
}
}
asciiEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(suppressListener) return;
// TODO Auto-generated method stub
suppressListener = true;
String tohex = asciiEditText.getText().toString();
Log.d("newpacket", DataStorage.FILE_LINE(tohex));
byte [] bytes = Packet.asciiToBytes(tohex);
hexEditText.setText(Packet.toHex(bytes));
suppressListener = false;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
hexEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(suppressListener) return;
// TODO Auto-generated method stub
suppressListener = true;
String toascii = hexEditText.getText().toString();
Log.d("newpacket", DataStorage.FILE_LINE(toascii));
byte [] bytes = Packet.toBytes(toascii);
asciiEditText.setText(Packet.toAscii(bytes));
suppressListener = false;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
testButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
{
//perform action
Packet testPacket = getPacket();
Log.d("newpacket", DataStorage.FILE_LINE(testPacket + ""));
NewPacketActivity NPA = (NewPacketActivity)getActivity();
NPA.dataStore.sendPacketToService(testPacket);
}
});
saveButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
{
//perform action
Packet savePacket = getPacket();
if(savePacket.name.trim().isEmpty()) {
Toast.makeText((NewPacketActivity)getActivity(), "Name cannot be blank.", Toast.LENGTH_LONG).show();
return;
}
if(savePacket.toIP.trim().isEmpty()) {
Toast.makeText((NewPacketActivity)getActivity(), "IP/DNS cannot be blank.", Toast.LENGTH_LONG).show();
return;
}
Log.d("newpacket", DataStorage.FILE_LINE(savePacket + ""));
NewPacketActivity NPA = (NewPacketActivity)getActivity();
NPA.dataStore.savePacket(savePacket);
NPA.dataStore.invalidateLists();
NPA.finish();
}
});
return rootView;
}
}
}
| |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.CollectPreconditions.checkNonnegative;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.WeakOuter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* Implementation of {@code Multimap} that does not allow duplicate key-value entries and that
* returns collections whose iterators follow the ordering in which the data was added to the
* multimap.
*
* <p>The collections returned by {@code keySet}, {@code keys}, and {@code asMap} iterate through
* the keys in the order they were first added to the multimap. Similarly, {@code get}, {@code
* removeAll}, and {@code replaceValues} return collections that iterate through the values in the
* order they were added. The collections generated by {@code entries} and {@code values} iterate
* across the key-value mappings in the order they were added to the multimap.
*
* <p>The iteration ordering of the collections generated by {@code keySet}, {@code keys}, and
* {@code asMap} has a few subtleties. As long as the set of keys remains unchanged, adding or
* removing mappings does not affect the key iteration order. However, if you remove all values
* associated with a key and then add the key back to the multimap, that key will come last in the
* key iteration order.
*
* <p>The multimap does not store duplicate key-value pairs. Adding a new key-value pair equal to an
* existing key-value pair has no effect.
*
* <p>Keys and values may be null. All optional multimap methods are supported, and all returned
* views are modifiable.
*
* <p>This class is not threadsafe when any concurrent operations update the multimap. Concurrent
* read operations will work correctly. To allow concurrent update operations, wrap your multimap
* with a call to {@link Multimaps#synchronizedSetMultimap}.
*
* <p><b>Warning:</b> Do not modify either a key <i>or a value</i> of a {@code LinkedHashMultimap}
* in a way that affects its {@link Object#equals} behavior. Undefined behavior and bugs will
* result.
*
* <p>See the Guava User Guide article on <a href=
* "https://github.com/google/guava/wiki/NewCollectionTypesExplained#multimap">{@code Multimap}</a>.
*
* @author Jared Levy
* @author Louis Wasserman
* @since 2.0
*/
@GwtCompatible(serializable = true, emulated = true)
@ElementTypesAreNonnullByDefault
public final class LinkedHashMultimap<K extends @Nullable Object, V extends @Nullable Object>
extends LinkedHashMultimapGwtSerializationDependencies<K, V> {
/** Creates a new, empty {@code LinkedHashMultimap} with the default initial capacities. */
public static <K extends @Nullable Object, V extends @Nullable Object>
LinkedHashMultimap<K, V> create() {
return new LinkedHashMultimap<>(DEFAULT_KEY_CAPACITY, DEFAULT_VALUE_SET_CAPACITY);
}
/**
* Constructs an empty {@code LinkedHashMultimap} with enough capacity to hold the specified
* numbers of keys and values without rehashing.
*
* @param expectedKeys the expected number of distinct keys
* @param expectedValuesPerKey the expected average number of values per key
* @throws IllegalArgumentException if {@code expectedKeys} or {@code expectedValuesPerKey} is
* negative
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
LinkedHashMultimap<K, V> create(int expectedKeys, int expectedValuesPerKey) {
return new LinkedHashMultimap<>(
Maps.capacity(expectedKeys), Maps.capacity(expectedValuesPerKey));
}
/**
* Constructs a {@code LinkedHashMultimap} with the same mappings as the specified multimap. If a
* key-value mapping appears multiple times in the input multimap, it only appears once in the
* constructed multimap. The new multimap has the same {@link Multimap#entries()} iteration order
* as the input multimap, except for excluding duplicate mappings.
*
* @param multimap the multimap whose contents are copied to this multimap
*/
public static <K extends @Nullable Object, V extends @Nullable Object>
LinkedHashMultimap<K, V> create(Multimap<? extends K, ? extends V> multimap) {
LinkedHashMultimap<K, V> result = create(multimap.keySet().size(), DEFAULT_VALUE_SET_CAPACITY);
result.putAll(multimap);
return result;
}
private interface ValueSetLink<K extends @Nullable Object, V extends @Nullable Object> {
ValueSetLink<K, V> getPredecessorInValueSet();
ValueSetLink<K, V> getSuccessorInValueSet();
void setPredecessorInValueSet(ValueSetLink<K, V> entry);
void setSuccessorInValueSet(ValueSetLink<K, V> entry);
}
private static <K extends @Nullable Object, V extends @Nullable Object> void succeedsInValueSet(
ValueSetLink<K, V> pred, ValueSetLink<K, V> succ) {
pred.setSuccessorInValueSet(succ);
succ.setPredecessorInValueSet(pred);
}
private static <K extends @Nullable Object, V extends @Nullable Object> void succeedsInMultimap(
ValueEntry<K, V> pred, ValueEntry<K, V> succ) {
pred.setSuccessorInMultimap(succ);
succ.setPredecessorInMultimap(pred);
}
private static <K extends @Nullable Object, V extends @Nullable Object> void deleteFromValueSet(
ValueSetLink<K, V> entry) {
succeedsInValueSet(entry.getPredecessorInValueSet(), entry.getSuccessorInValueSet());
}
private static <K extends @Nullable Object, V extends @Nullable Object> void deleteFromMultimap(
ValueEntry<K, V> entry) {
succeedsInMultimap(entry.getPredecessorInMultimap(), entry.getSuccessorInMultimap());
}
/**
* LinkedHashMultimap entries are in no less than three coexisting linked lists: a bucket in the
* hash table for a {@code Set<V>} associated with a key, the linked list of insertion-ordered
* entries in that {@code Set<V>}, and the linked list of entries in the LinkedHashMultimap as a
* whole.
*/
@VisibleForTesting
static final class ValueEntry<K extends @Nullable Object, V extends @Nullable Object>
extends ImmutableEntry<K, V> implements ValueSetLink<K, V> {
final int smearedValueHash;
@CheckForNull ValueEntry<K, V> nextInValueBucket;
/*
* The *InValueSet and *InMultimap fields below are null after construction, but we almost
* always call succeedsIn*() to initialize them immediately thereafter.
*
* The exception is the *InValueSet fields of multimapHeaderEntry, which are never set. (That
* works out fine as long as we continue to be careful not to try delete them or iterate past
* them.)
*
* We could consider "lying" and omitting @CheckNotNull from all these fields. Normally, I'm not
* a fan of that: What if we someday implement (presumably to be enabled during tests only)
* bytecode rewriting that checks for any null value that passes through an API with a
* known-non-null type? But that particular problem might not arise here, since we're not
* actually reading from the fields in any case in which they might be null (as proven by the
* requireNonNull checks below). Plus, we're *already* lying here, since newHeader passes a null
* key and value, which we pass to the superconstructor, even though the key and value type for
* a given entry might not include null. The right fix for the header problems is probably to
* define a separate MultimapLink interface with a separate "header" implementation, which
* hopefully could avoid implementing Entry or ValueSetLink at all. (But note that that approach
* requires us to define extra classes -- unfortunate under Android.) *Then* we could consider
* lying about the fields below on the grounds that we always initialize them just after the
* constructor -- an example of the kind of lying that our hypotheticaly bytecode rewriter would
* already have to deal with, thanks to DI frameworks that perform field and method injection,
* frameworks like Android that define post-construct hooks like Activity.onCreate, etc.
*/
@CheckForNull ValueSetLink<K, V> predecessorInValueSet;
@CheckForNull ValueSetLink<K, V> successorInValueSet;
@CheckForNull ValueEntry<K, V> predecessorInMultimap;
@CheckForNull ValueEntry<K, V> successorInMultimap;
ValueEntry(
@ParametricNullness K key,
@ParametricNullness V value,
int smearedValueHash,
@CheckForNull ValueEntry<K, V> nextInValueBucket) {
super(key, value);
this.smearedValueHash = smearedValueHash;
this.nextInValueBucket = nextInValueBucket;
}
@SuppressWarnings("nullness") // see the comment on the class fields, especially about newHeader
static <K extends @Nullable Object, V extends @Nullable Object> ValueEntry<K, V> newHeader() {
return new ValueEntry<>(null, null, 0, null);
}
boolean matchesValue(@CheckForNull Object v, int smearedVHash) {
return smearedValueHash == smearedVHash && Objects.equal(getValue(), v);
}
@Override
public ValueSetLink<K, V> getPredecessorInValueSet() {
return requireNonNull(predecessorInValueSet); // see the comment on the class fields
}
@Override
public ValueSetLink<K, V> getSuccessorInValueSet() {
return requireNonNull(successorInValueSet); // see the comment on the class fields
}
@Override
public void setPredecessorInValueSet(ValueSetLink<K, V> entry) {
predecessorInValueSet = entry;
}
@Override
public void setSuccessorInValueSet(ValueSetLink<K, V> entry) {
successorInValueSet = entry;
}
public ValueEntry<K, V> getPredecessorInMultimap() {
return requireNonNull(predecessorInMultimap); // see the comment on the class fields
}
public ValueEntry<K, V> getSuccessorInMultimap() {
return requireNonNull(successorInMultimap); // see the comment on the class fields
}
public void setSuccessorInMultimap(ValueEntry<K, V> multimapSuccessor) {
this.successorInMultimap = multimapSuccessor;
}
public void setPredecessorInMultimap(ValueEntry<K, V> multimapPredecessor) {
this.predecessorInMultimap = multimapPredecessor;
}
}
private static final int DEFAULT_KEY_CAPACITY = 16;
private static final int DEFAULT_VALUE_SET_CAPACITY = 2;
@VisibleForTesting static final double VALUE_SET_LOAD_FACTOR = 1.0;
@VisibleForTesting transient int valueSetCapacity = DEFAULT_VALUE_SET_CAPACITY;
private transient ValueEntry<K, V> multimapHeaderEntry;
private LinkedHashMultimap(int keyCapacity, int valueSetCapacity) {
super(Platform.<K, Collection<V>>newLinkedHashMapWithExpectedSize(keyCapacity));
checkNonnegative(valueSetCapacity, "expectedValuesPerKey");
this.valueSetCapacity = valueSetCapacity;
this.multimapHeaderEntry = ValueEntry.newHeader();
succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry);
}
/**
* {@inheritDoc}
*
* <p>Creates an empty {@code LinkedHashSet} for a collection of values for one key.
*
* @return a new {@code LinkedHashSet} containing a collection of values for one key
*/
@Override
Set<V> createCollection() {
return Platform.newLinkedHashSetWithExpectedSize(valueSetCapacity);
}
/**
* {@inheritDoc}
*
* <p>Creates a decorated insertion-ordered set that also keeps track of the order in which
* key-value pairs are added to the multimap.
*
* @param key key to associate with values in the collection
* @return a new decorated set containing a collection of values for one key
*/
@Override
Collection<V> createCollection(@ParametricNullness K key) {
return new ValueSet(key, valueSetCapacity);
}
/**
* {@inheritDoc}
*
* <p>If {@code values} is not empty and the multimap already contains a mapping for {@code key},
* the {@code keySet()} ordering is unchanged. However, the provided values always come last in
* the {@link #entries()} and {@link #values()} iteration orderings.
*/
@CanIgnoreReturnValue
@Override
public Set<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) {
return super.replaceValues(key, values);
}
/**
* Returns a set of all key-value pairs. Changes to the returned set will update the underlying
* multimap, and vice versa. The entries set does not support the {@code add} or {@code addAll}
* operations.
*
* <p>The iterator generated by the returned set traverses the entries in the order they were
* added to the multimap.
*
* <p>Each entry is an immutable snapshot of a key-value mapping in the multimap, taken at the
* time the entry is returned by a method call to the collection or its iterator.
*/
@Override
public Set<Entry<K, V>> entries() {
return super.entries();
}
/**
* Returns a view collection of all <i>distinct</i> keys contained in this multimap. Note that the
* key set contains a key if and only if this multimap maps that key to at least one value.
*
* <p>The iterator generated by the returned set traverses the keys in the order they were first
* added to the multimap.
*
* <p>Changes to the returned set will update the underlying multimap, and vice versa. However,
* <i>adding</i> to the returned set is not possible.
*/
@Override
public Set<K> keySet() {
return super.keySet();
}
/**
* Returns a collection of all values in the multimap. Changes to the returned collection will
* update the underlying multimap, and vice versa.
*
* <p>The iterator generated by the returned collection traverses the values in the order they
* were added to the multimap.
*/
@Override
public Collection<V> values() {
return super.values();
}
@VisibleForTesting
@WeakOuter
final class ValueSet extends Sets.ImprovedAbstractSet<V> implements ValueSetLink<K, V> {
/*
* We currently use a fixed load factor of 1.0, a bit higher than normal to reduce memory
* consumption.
*/
@ParametricNullness private final K key;
@VisibleForTesting @Nullable ValueEntry<K, V>[] hashTable;
private int size = 0;
private int modCount = 0;
// We use the set object itself as the end of the linked list, avoiding an unnecessary
// entry object per key.
private ValueSetLink<K, V> firstEntry;
private ValueSetLink<K, V> lastEntry;
ValueSet(@ParametricNullness K key, int expectedValues) {
this.key = key;
this.firstEntry = this;
this.lastEntry = this;
// Round expected values up to a power of 2 to get the table size.
int tableSize = Hashing.closedTableSize(expectedValues, VALUE_SET_LOAD_FACTOR);
@SuppressWarnings({"rawtypes", "unchecked"})
@Nullable
ValueEntry<K, V>[] hashTable = new @Nullable ValueEntry[tableSize];
this.hashTable = hashTable;
}
private int mask() {
return hashTable.length - 1;
}
@Override
public ValueSetLink<K, V> getPredecessorInValueSet() {
return lastEntry;
}
@Override
public ValueSetLink<K, V> getSuccessorInValueSet() {
return firstEntry;
}
@Override
public void setPredecessorInValueSet(ValueSetLink<K, V> entry) {
lastEntry = entry;
}
@Override
public void setSuccessorInValueSet(ValueSetLink<K, V> entry) {
firstEntry = entry;
}
@Override
public Iterator<V> iterator() {
return new Iterator<V>() {
ValueSetLink<K, V> nextEntry = firstEntry;
@CheckForNull ValueEntry<K, V> toRemove;
int expectedModCount = modCount;
private void checkForComodification() {
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
@Override
public boolean hasNext() {
checkForComodification();
return nextEntry != ValueSet.this;
}
@Override
@ParametricNullness
public V next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
ValueEntry<K, V> entry = (ValueEntry<K, V>) nextEntry;
V result = entry.getValue();
toRemove = entry;
nextEntry = entry.getSuccessorInValueSet();
return result;
}
@Override
public void remove() {
checkForComodification();
checkState(toRemove != null, "no calls to next() since the last call to remove()");
ValueSet.this.remove(toRemove.getValue());
expectedModCount = modCount;
toRemove = null;
}
};
}
@Override
public int size() {
return size;
}
@Override
public boolean contains(@CheckForNull Object o) {
int smearedHash = Hashing.smearedHash(o);
for (ValueEntry<K, V> entry = hashTable[smearedHash & mask()];
entry != null;
entry = entry.nextInValueBucket) {
if (entry.matchesValue(o, smearedHash)) {
return true;
}
}
return false;
}
@Override
public boolean add(@ParametricNullness V value) {
int smearedHash = Hashing.smearedHash(value);
int bucket = smearedHash & mask();
ValueEntry<K, V> rowHead = hashTable[bucket];
for (ValueEntry<K, V> entry = rowHead; entry != null; entry = entry.nextInValueBucket) {
if (entry.matchesValue(value, smearedHash)) {
return false;
}
}
ValueEntry<K, V> newEntry = new ValueEntry<>(key, value, smearedHash, rowHead);
succeedsInValueSet(lastEntry, newEntry);
succeedsInValueSet(newEntry, this);
succeedsInMultimap(multimapHeaderEntry.getPredecessorInMultimap(), newEntry);
succeedsInMultimap(newEntry, multimapHeaderEntry);
hashTable[bucket] = newEntry;
size++;
modCount++;
rehashIfNecessary();
return true;
}
private void rehashIfNecessary() {
if (Hashing.needsResizing(size, hashTable.length, VALUE_SET_LOAD_FACTOR)) {
@SuppressWarnings("unchecked")
ValueEntry<K, V>[] hashTable = new ValueEntry[this.hashTable.length * 2];
this.hashTable = hashTable;
int mask = hashTable.length - 1;
for (ValueSetLink<K, V> entry = firstEntry;
entry != this;
entry = entry.getSuccessorInValueSet()) {
ValueEntry<K, V> valueEntry = (ValueEntry<K, V>) entry;
int bucket = valueEntry.smearedValueHash & mask;
valueEntry.nextInValueBucket = hashTable[bucket];
hashTable[bucket] = valueEntry;
}
}
}
@CanIgnoreReturnValue
@Override
public boolean remove(@CheckForNull Object o) {
int smearedHash = Hashing.smearedHash(o);
int bucket = smearedHash & mask();
ValueEntry<K, V> prev = null;
for (ValueEntry<K, V> entry = hashTable[bucket];
entry != null;
prev = entry, entry = entry.nextInValueBucket) {
if (entry.matchesValue(o, smearedHash)) {
if (prev == null) {
// first entry in the bucket
hashTable[bucket] = entry.nextInValueBucket;
} else {
prev.nextInValueBucket = entry.nextInValueBucket;
}
deleteFromValueSet(entry);
deleteFromMultimap(entry);
size--;
modCount++;
return true;
}
}
return false;
}
@Override
public void clear() {
Arrays.fill(hashTable, null);
size = 0;
for (ValueSetLink<K, V> entry = firstEntry;
entry != this;
entry = entry.getSuccessorInValueSet()) {
ValueEntry<K, V> valueEntry = (ValueEntry<K, V>) entry;
deleteFromMultimap(valueEntry);
}
succeedsInValueSet(this, this);
modCount++;
}
}
@Override
Iterator<Entry<K, V>> entryIterator() {
return new Iterator<Entry<K, V>>() {
ValueEntry<K, V> nextEntry = multimapHeaderEntry.getSuccessorInMultimap();
@CheckForNull ValueEntry<K, V> toRemove;
@Override
public boolean hasNext() {
return nextEntry != multimapHeaderEntry;
}
@Override
public Entry<K, V> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
ValueEntry<K, V> result = nextEntry;
toRemove = result;
nextEntry = nextEntry.getSuccessorInMultimap();
return result;
}
@Override
public void remove() {
checkState(toRemove != null, "no calls to next() since the last call to remove()");
LinkedHashMultimap.this.remove(toRemove.getKey(), toRemove.getValue());
toRemove = null;
}
};
}
@Override
Iterator<V> valueIterator() {
return Maps.valueIterator(entryIterator());
}
@Override
public void clear() {
super.clear();
succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry);
}
/**
* @serialData the expected values per key, the number of distinct keys, the number of entries,
* and the entries in order
*/
@GwtIncompatible // java.io.ObjectOutputStream
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
stream.writeInt(keySet().size());
for (K key : keySet()) {
stream.writeObject(key);
}
stream.writeInt(size());
for (Entry<K, V> entry : entries()) {
stream.writeObject(entry.getKey());
stream.writeObject(entry.getValue());
}
}
@GwtIncompatible // java.io.ObjectInputStream
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
stream.defaultReadObject();
multimapHeaderEntry = ValueEntry.newHeader();
succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry);
valueSetCapacity = DEFAULT_VALUE_SET_CAPACITY;
int distinctKeys = stream.readInt();
Map<K, Collection<V>> map = Platform.newLinkedHashMapWithExpectedSize(12);
for (int i = 0; i < distinctKeys; i++) {
@SuppressWarnings("unchecked")
K key = (K) stream.readObject();
map.put(key, createCollection(key));
}
int entries = stream.readInt();
for (int i = 0; i < entries; i++) {
@SuppressWarnings("unchecked")
K key = (K) stream.readObject();
@SuppressWarnings("unchecked")
V value = (V) stream.readObject();
/*
* requireNonNull is safe for a properly serialized multimap: We've already inserted a
* collection for each key that we expect.
*/
requireNonNull(map.get(key)).add(value);
}
setMap(map);
}
@GwtIncompatible // java serialization not supported
private static final long serialVersionUID = 1;
}
| |
/*
* 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.igfs;
import org.apache.ignite.IgniteFileSystem;
import org.apache.ignite.cache.CacheRebalanceMode;
import org.apache.ignite.cache.CacheWriteSynchronizationMode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.FileSystemConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.igfs.IgfsBlockLocation;
import org.apache.ignite.igfs.IgfsFile;
import org.apache.ignite.igfs.IgfsGroupDataBlocksKeyMapper;
import org.apache.ignite.igfs.IgfsInputStream;
import org.apache.ignite.igfs.IgfsOutputStream;
import org.apache.ignite.igfs.IgfsPath;
import org.apache.ignite.internal.IgniteKernal;
import org.apache.ignite.internal.processors.cache.GridCacheAdapter;
import org.apache.ignite.internal.util.typedef.CAX;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteUuid;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder;
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder;
import org.apache.ignite.testframework.GridTestUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
import static org.apache.ignite.cache.CacheMode.REPLICATED;
import static org.apache.ignite.testframework.GridTestUtils.getFieldValue;
import static org.apache.ignite.testframework.GridTestUtils.runMultiThreaded;
/**
* Tests for IGFS streams content.
*/
public class IgfsStreamsSelfTest extends IgfsCommonAbstractTest {
/** Test IP finder. */
private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true);
/** Group size. */
public static final int CFG_GRP_SIZE = 128;
/** Pre-configured block size. */
private static final int CFG_BLOCK_SIZE = 64000;
/** Number of threads to test parallel readings. */
private static final int WRITING_THREADS_CNT = 5;
/** Number of threads to test parallel readings. */
private static final int READING_THREADS_CNT = 5;
/** Test nodes count. */
private static final int NODES_CNT = 4;
/** Number of retries for async ops. */
public static final int ASSERT_RETRIES = 100;
/** Delay between checks for async ops. */
public static final int ASSERT_RETRY_INTERVAL = 100;
/** File system to test. */
private IgniteFileSystem fs;
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
startGrids(NODES_CNT);
}
/** {@inheritDoc} */
@Override protected void afterTestsStopped() throws Exception {
stopAllGrids();
}
/** {@inheritDoc} */
@Override protected void beforeTest() throws Exception {
if (NODES_CNT <= 0)
return;
// Initialize FS.
fs = grid(0).fileSystem("igfs");
// Cleanup FS.
fs.clear();
}
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
cfg.setLateAffinityAssignment(false);
cfg.setCacheConfiguration();
TcpDiscoverySpi discoSpi = new TcpDiscoverySpi();
discoSpi.setIpFinder(IP_FINDER);
cfg.setDiscoverySpi(discoSpi);
FileSystemConfiguration igfsCfg = new FileSystemConfiguration();
igfsCfg.setMetaCacheConfiguration(cacheConfiguration("meta"));
igfsCfg.setDataCacheConfiguration(cacheConfiguration("data"));
igfsCfg.setName("igfs");
igfsCfg.setBlockSize(CFG_BLOCK_SIZE);
igfsCfg.setFragmentizerEnabled(true);
cfg.setFileSystemConfiguration(igfsCfg);
return cfg;
}
/** {@inheritDoc} */
protected CacheConfiguration cacheConfiguration(@NotNull String cacheName) {
CacheConfiguration cacheCfg = defaultCacheConfiguration();
cacheCfg.setName(cacheName);
if ("meta".equals(cacheName))
cacheCfg.setCacheMode(REPLICATED);
else {
cacheCfg.setCacheMode(PARTITIONED);
cacheCfg.setNearConfiguration(null);
cacheCfg.setBackups(0);
cacheCfg.setAffinityMapper(new IgfsGroupDataBlocksKeyMapper(CFG_GRP_SIZE));
}
cacheCfg.setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC);
cacheCfg.setAtomicityMode(TRANSACTIONAL);
cacheCfg.setRebalanceMode(CacheRebalanceMode.SYNC);
return cacheCfg;
}
/**
* Test file creation.
*
* @throws Exception In case of exception.
*/
public void testCreateFile() throws Exception {
IgfsPath path = new IgfsPath("/asdf");
long max = 100L * CFG_BLOCK_SIZE / WRITING_THREADS_CNT;
for (long size = 0; size <= max; size = size * 15 / 10 + 1) {
assertTrue(F.isEmpty(fs.listPaths(IgfsPath.ROOT)));
testCreateFile(path, size, new Random().nextInt());
}
}
/** @throws Exception If failed. */
public void testCreateFileColocated() throws Exception {
IgfsPath path = new IgfsPath("/colocated");
UUID uuid = UUID.randomUUID();
IgniteUuid affKey;
long idx = 0;
while (true) {
affKey = new IgniteUuid(uuid, idx);
if (grid(0).affinity(grid(0).igfsx("igfs").configuration().getDataCacheConfiguration()
.getName()).mapKeyToNode(affKey).id().equals(grid(0).localNode().id()))
break;
idx++;
}
try (IgfsOutputStream out = fs.create(path, 1024, true, affKey, 0, 1024, null)) {
// Write 5M, should be enough to test distribution.
for (int i = 0; i < 15; i++)
out.write(new byte[1024 * 1024]);
}
IgfsFile info = fs.info(path);
Collection<IgfsBlockLocation> affNodes = fs.affinity(path, 0, info.length());
assertEquals(1, affNodes.size());
Collection<UUID> nodeIds = F.first(affNodes).nodeIds();
assertEquals(1, nodeIds.size());
assertEquals(grid(0).localNode().id(), F.first(nodeIds));
}
/** @throws Exception If failed. */
public void testCreateFileFragmented() throws Exception {
IgfsEx impl = (IgfsEx)grid(0).fileSystem("igfs");
String metaCacheName = grid(0).igfsx("igfs").configuration().getMetaCacheConfiguration().getName();
final String dataCacheName = grid(0).igfsx("igfs").configuration().getDataCacheConfiguration()
.getName();
IgfsFragmentizerManager fragmentizer = impl.context().fragmentizer();
GridTestUtils.setFieldValue(fragmentizer, "fragmentizerEnabled", false);
IgfsPath path = new IgfsPath("/file");
try {
IgniteFileSystem fs0 = grid(0).fileSystem("igfs");
IgniteFileSystem fs1 = grid(1).fileSystem("igfs");
IgniteFileSystem fs2 = grid(2).fileSystem("igfs");
try (IgfsOutputStream out = fs0.create(path, 128, false, 1, CFG_GRP_SIZE,
F.asMap(IgfsUtils.PROP_PREFER_LOCAL_WRITES, "true"))) {
// 1.5 blocks
byte[] data = new byte[CFG_BLOCK_SIZE * 3 / 2];
Arrays.fill(data, (byte)1);
out.write(data);
}
try (IgfsOutputStream out = fs1.append(path, false)) {
// 1.5 blocks.
byte[] data = new byte[CFG_BLOCK_SIZE * 3 / 2];
Arrays.fill(data, (byte)2);
out.write(data);
}
// After this we should have first two block colocated with grid 0 and last block colocated with grid 1.
IgfsFileImpl fileImpl = (IgfsFileImpl)fs.info(path);
GridCacheAdapter<Object, Object> metaCache = ((IgniteKernal)grid(0)).internalCache(metaCacheName);
IgfsEntryInfo fileInfo = (IgfsEntryInfo)metaCache.get(fileImpl.fileId());
IgfsFileMap map = fileInfo.fileMap();
List<IgfsFileAffinityRange> ranges = map.ranges();
assertEquals(2, ranges.size());
assertTrue(ranges.get(0).startOffset() == 0);
assertTrue(ranges.get(0).endOffset() == 2 * CFG_BLOCK_SIZE - 1);
assertTrue(ranges.get(1).startOffset() == 2 * CFG_BLOCK_SIZE);
assertTrue(ranges.get(1).endOffset() == 3 * CFG_BLOCK_SIZE - 1);
// Validate data read after colocated writes.
try (IgfsInputStream in = fs2.open(path)) {
// Validate first part of file.
for (int i = 0; i < CFG_BLOCK_SIZE * 3 / 2; i++)
assertEquals((byte)1, in.read());
// Validate second part of file.
for (int i = 0; i < CFG_BLOCK_SIZE * 3 / 2; i++)
assertEquals((byte)2, in.read());
assertEquals(-1, in.read());
}
}
finally {
GridTestUtils.setFieldValue(fragmentizer, "fragmentizerEnabled", true);
boolean hasData = false;
for (int i = 0; i < NODES_CNT; i++)
hasData |= !grid(i).cachex(dataCacheName).isEmpty();
assertTrue(hasData);
fs.delete(path, true);
}
GridTestUtils.retryAssert(log, ASSERT_RETRIES, ASSERT_RETRY_INTERVAL, new CAX() {
@Override public void applyx() {
for (int i = 0; i < NODES_CNT; i++)
assertTrue(grid(i).cachex(dataCacheName).isEmpty());
}
});
}
/**
* Test file creation.
*
* @param path Path to file to store.
* @param size Size of file to store.
* @param salt Salt for file content generation.
* @throws Exception In case of any exception.
*/
private void testCreateFile(final IgfsPath path, final long size, final int salt) throws Exception {
info("Create file [path=" + path + ", size=" + size + ", salt=" + salt + ']');
final AtomicInteger cnt = new AtomicInteger(0);
final Collection<IgfsPath> cleanUp = new ConcurrentLinkedQueue<>();
long time = runMultiThreaded(new Callable<Object>() {
@Override public Object call() throws Exception {
int id = cnt.incrementAndGet();
IgfsPath f = new IgfsPath(path.parent(), "asdf" + (id > 1 ? "-" + id : ""));
try (IgfsOutputStream out = fs.create(f, 0, true, null, 0, 1024, null)) {
assertNotNull(out);
cleanUp.add(f); // Add all created into cleanup list.
U.copy(new IgfsTestInputStream(size, salt), out);
}
return null;
}
}, WRITING_THREADS_CNT, "perform-multi-thread-writing");
if (time > 0) {
double rate = size * 1000. / time / 1024 / 1024;
info(String.format("Write file [path=%s, size=%d kB, rate=%2.1f MB/s]", path,
WRITING_THREADS_CNT * size / 1024, WRITING_THREADS_CNT * rate));
}
info("Read and validate saved file: " + path);
final InputStream expIn = new IgfsTestInputStream(size, salt);
final IgfsInputStream actIn = fs.open(path, CFG_BLOCK_SIZE * READING_THREADS_CNT * 11 / 10);
// Validate continuous reading of whole file.
assertEqualStreams(expIn, actIn, size, null);
// Validate random seek and reading.
final Random rnd = new Random();
runMultiThreaded(new Callable<Object>() {
@Override public Object call() throws Exception {
long skip = Math.abs(rnd.nextLong() % (size + 1));
long range = Math.min(size - skip, rnd.nextInt(CFG_BLOCK_SIZE * 400));
assertEqualStreams(new IgfsTestInputStream(size, salt), actIn, range, skip);
return null;
}
}, READING_THREADS_CNT, "validate-multi-thread-reading");
expIn.close();
actIn.close();
info("Get stored file info: " + path);
IgfsFile desc = fs.info(path);
info("Validate stored file info: " + desc);
assertNotNull(desc);
if (log.isDebugEnabled())
log.debug("File descriptor: " + desc);
Collection<IgfsBlockLocation> aff = fs.affinity(path, 0, desc.length());
assertFalse("Affinity: " + aff, desc.length() != 0 && aff.isEmpty());
int blockSize = desc.blockSize();
assertEquals("File size", size, desc.length());
assertEquals("Binary block size", CFG_BLOCK_SIZE, blockSize);
//assertEquals("Permission", "rwxr-xr-x", desc.getPermission().toString());
//assertEquals("Permission sticky bit marks this is file", false, desc.getPermission().getStickyBit());
assertEquals("Type", true, desc.isFile());
assertEquals("Type", false, desc.isDirectory());
info("Cleanup files: " + cleanUp);
for (IgfsPath f : cleanUp) {
fs.delete(f, true);
assertNull(fs.info(f));
}
}
/**
* Validate streams generate the same output.
*
* @param expIn Expected input stream.
* @param actIn Actual input stream.
* @param expSize Expected size of the streams.
* @param seek Seek to use async position-based reading or {@code null} to use simple continuous reading.
* @throws IOException In case of any IO exception.
*/
private void assertEqualStreams(InputStream expIn, IgfsInputStream actIn,
@Nullable Long expSize, @Nullable Long seek) throws IOException {
if (seek != null)
expIn.skip(seek);
int bufSize = 2345;
byte buf1[] = new byte[bufSize];
byte buf2[] = new byte[bufSize];
long pos = 0;
long start = System.currentTimeMillis();
while (true) {
int read = (int)Math.min(bufSize, expSize - pos);
int i1;
if (seek == null)
i1 = actIn.read(buf1, 0, read);
else if (seek % 2 == 0)
i1 = actIn.read(pos + seek, buf1, 0, read);
else {
i1 = read;
actIn.readFully(pos + seek, buf1, 0, read);
}
// Read at least 0 byte, but don't read more then 'i1' or 'read'.
int i2 = expIn.read(buf2, 0, Math.max(0, Math.min(i1, read)));
if (i1 != i2) {
fail("Expects the same data [read=" + read + ", pos=" + pos + ", seek=" + seek +
", i1=" + i1 + ", i2=" + i2 + ']');
}
if (i1 == -1)
break; // EOF
// i1 == bufSize => compare buffers.
// i1 < bufSize => Compare part of buffers, rest of buffers are equal from previous iteration.
assertTrue("Expects the same data [read=" + read + ", pos=" + pos + ", seek=" + seek +
", i1=" + i1 + ", i2=" + i2 + ']', Arrays.equals(buf1, buf2));
if (read == 0)
break; // Nothing more to read.
pos += i1;
}
if (expSize != null)
assertEquals(expSize.longValue(), pos);
long time = System.currentTimeMillis() - start;
if (time != 0 && log.isInfoEnabled()) {
log.info(String.format("Streams were compared in continuous reading " +
"[size=%7d, rate=%3.1f MB/sec]", expSize, expSize * 1000. / time / 1024 / 1024));
}
}
}
| |
/*
* Copyright (C) 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.example.games.basegameutils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Vector;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import com.google.android.gms.appstate.AppStateClient;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.games.GamesActivityResultCodes;
import com.google.android.gms.games.GamesClient;
import com.google.android.gms.games.multiplayer.Invitation;
import com.google.android.gms.plus.PlusClient;
public class GameHelper implements GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
/** Listener for sign-in success or failure events. */
public interface GameHelperListener {
/**
* Called when sign-in fails. As a result, a "Sign-In" button can be
* shown to the user; when that button is clicked, call
* @link{GamesHelper#beginUserInitiatedSignIn}. Note that not all calls to this
* method mean an error; it may be a result of the fact that automatic
* sign-in could not proceed because user interaction was required
* (consent dialogs). So implementations of this method should NOT
* display an error message unless a call to @link{GamesHelper#hasSignInError}
* indicates that an error indeed occurred.
*/
void onSignInFailed();
/** Called when sign-in succeeds. */
void onSignInSucceeded();
}
// States we can be in
public static final int STATE_UNCONFIGURED = 0;
public static final int STATE_DISCONNECTED = 1;
public static final int STATE_CONNECTING = 2;
public static final int STATE_CONNECTED = 3;
// State names (for debug logging, etc)
public static final String[] STATE_NAMES = {
"UNCONFIGURED", "DISCONNECTED", "CONNECTING", "CONNECTED"
};
// State we are in right now
int mState = STATE_UNCONFIGURED;
// Are we expecting the result of a resolution flow?
boolean mExpectingResolution = false;
/**
* The Activity we are bound to. We need to keep a reference to the Activity
* because some games methods require an Activity (a Context won't do). We
* are careful not to leak these references: we release them on onStop().
*/
Activity mActivity = null;
// OAuth scopes required for the clients. Initialized in setup().
String mScopes[];
// Request code we use when invoking other Activities to complete the
// sign-in flow.
final static int RC_RESOLVE = 9001;
// Request code when invoking Activities whose result we don't care about.
final static int RC_UNUSED = 9002;
// Client objects we manage. If a given client is not enabled, it is null.
GamesClient mGamesClient = null;
PlusClient mPlusClient = null;
AppStateClient mAppStateClient = null;
// What clients we manage (OR-able values, can be combined as flags)
public final static int CLIENT_NONE = 0x00;
public final static int CLIENT_GAMES = 0x01;
public final static int CLIENT_PLUS = 0x02;
public final static int CLIENT_APPSTATE = 0x04;
public final static int CLIENT_ALL = CLIENT_GAMES | CLIENT_PLUS | CLIENT_APPSTATE;
// What clients were requested? (bit flags)
int mRequestedClients = CLIENT_NONE;
// What clients are currently connected? (bit flags)
int mConnectedClients = CLIENT_NONE;
// What client are we currently connecting?
int mClientCurrentlyConnecting = CLIENT_NONE;
// Whether to automatically try to sign in on onStart().
boolean mAutoSignIn = true;
/*
* Whether user has specifically requested that the sign-in process begin.
* If mUserInitiatedSignIn is false, we're in the automatic sign-in attempt
* that we try once the Activity is started -- if true, then the user has
* already clicked a "Sign-In" button or something similar
*/
boolean mUserInitiatedSignIn = false;
// The connection result we got from our last attempt to sign-in.
ConnectionResult mConnectionResult = null;
// The error that happened during sign-in.
SignInFailureReason mSignInFailureReason = null;
// Print debug logs?
boolean mDebugLog = false;
String mDebugTag = "GameHelper";
/*
* If we got an invitation id when we connected to the games client, it's
* here. Otherwise, it's null.
*/
String mInvitationId;
// Listener
GameHelperListener mListener = null;
/**
* Construct a GameHelper object, initially tied to the given Activity.
* After constructing this object, call @link{setup} from the onCreate()
* method of your Activity.
*/
public GameHelper(Activity activity) {
mActivity = activity;
}
static private final int TYPE_DEVELOPER_ERROR = 1001;
static private final int TYPE_GAMEHELPER_BUG = 1002;
boolean checkState(int type, String operation, String warning, int... expectedStates) {
for (int expectedState : expectedStates) {
if (mState == expectedState) {
return true;
}
}
StringBuilder sb = new StringBuilder();
if (type == TYPE_DEVELOPER_ERROR) {
sb.append("GameHelper: you attempted an operation at an invalid. ");
} else {
sb.append("GameHelper: bug detected. Please report it at our bug tracker ");
sb.append("https://github.com/playgameservices/android-samples/issues. ");
sb.append("Please include the last couple hundred lines of logcat output ");
sb.append("and describe the operation that caused this. ");
}
sb.append("Explanation: ").append(warning);
sb.append("Operation: ").append(operation).append(". ");
sb.append("State: ").append(STATE_NAMES[mState]).append(". ");
if (expectedStates.length == 1) {
sb.append("Expected state: ").append(STATE_NAMES[expectedStates[0]]).append(".");
} else {
sb.append("Expected states:");
for (int expectedState : expectedStates) {
sb.append(" " ).append(STATE_NAMES[expectedState]);
}
sb.append(".");
}
logWarn(sb.toString());
return false;
}
void assertConfigured(String operation) {
if (mState == STATE_UNCONFIGURED) {
String error = "GameHelper error: Operation attempted without setup: " + operation +
". The setup() method must be called before attempting any other operation.";
logError(error);
throw new IllegalStateException(error);
}
}
/**
* Same as calling @link{setup(GameHelperListener, int)} requesting only the
* CLIENT_GAMES client.
*/
public void setup(GameHelperListener listener) {
setup(listener, CLIENT_GAMES);
}
/**
* Performs setup on this GameHelper object. Call this from the onCreate()
* method of your Activity. This will create the clients and do a few other
* initialization tasks. Next, call @link{#onStart} from the onStart()
* method of your Activity.
*
* @param listener The listener to be notified of sign-in events.
* @param clientsToUse The clients to use. Use a combination of
* CLIENT_GAMES, CLIENT_PLUS and CLIENT_APPSTATE, or CLIENT_ALL
* to request all clients.
* @param additionalScopes Any scopes to be used that are outside of the ones defined
* in the Scopes class.
* I.E. for YouTube uploads one would add
* "https://www.googleapis.com/auth/youtube.upload"
*/
public void setup(GameHelperListener listener, int clientsToUse, String ... additionalScopes) {
if (mState != STATE_UNCONFIGURED) {
String error = "GameHelper: you called GameHelper.setup() twice. You can only call " +
"it once.";
logError(error);
throw new IllegalStateException(error);
}
mListener = listener;
mRequestedClients = clientsToUse;
debugLog("Setup: requested clients: " + mRequestedClients);
Vector<String> scopesVector = new Vector<String>();
if (0 != (clientsToUse & CLIENT_GAMES)) {
scopesVector.add(Scopes.GAMES);
}
if (0 != (clientsToUse & CLIENT_PLUS)) {
scopesVector.add(Scopes.PLUS_LOGIN);
}
if (0 != (clientsToUse & CLIENT_APPSTATE)) {
scopesVector.add(Scopes.APP_STATE);
}
if (null != additionalScopes) {
for (String scope : additionalScopes) {
scopesVector.add(scope);
}
}
mScopes = new String[scopesVector.size()];
scopesVector.copyInto(mScopes);
debugLog("setup: scopes:");
for (String scope : mScopes) {
debugLog(" - " + scope);
}
if (0 != (clientsToUse & CLIENT_GAMES)) {
debugLog("setup: creating GamesClient");
mGamesClient = new GamesClient.Builder(getContext(), this, this)
.setGravityForPopups(Gravity.TOP | Gravity.CENTER_HORIZONTAL)
.setScopes(mScopes)
.create();
}
if (0 != (clientsToUse & CLIENT_PLUS)) {
debugLog("setup: creating GamesPlusClient");
mPlusClient = new PlusClient.Builder(getContext(), this, this)
.setScopes(mScopes)
.build();
}
if (0 != (clientsToUse & CLIENT_APPSTATE)) {
debugLog("setup: creating AppStateClient");
mAppStateClient = new AppStateClient.Builder(getContext(), this, this)
.setScopes(mScopes)
.create();
}
setState(STATE_DISCONNECTED);
}
void setState(int newState) {
String oldStateName = STATE_NAMES[mState];
String newStateName = STATE_NAMES[newState];
mState = newState;
debugLog("State change " + oldStateName + " -> " + newStateName);
}
/**
* Returns the GamesClient object. In order to call this method, you must have
* called @link{setup} with a set of clients that includes CLIENT_GAMES.
*/
public GamesClient getGamesClient() {
if (mGamesClient == null) {
throw new IllegalStateException("No GamesClient. Did you request it at setup?");
}
return mGamesClient;
}
/**
* Returns the AppStateClient object. In order to call this method, you must have
* called @link{#setup} with a set of clients that includes CLIENT_APPSTATE.
*/
public AppStateClient getAppStateClient() {
if (mAppStateClient == null) {
throw new IllegalStateException("No AppStateClient. Did you request it at setup?");
}
return mAppStateClient;
}
/**
* Returns the PlusClient object. In order to call this method, you must have
* called @link{#setup} with a set of clients that includes CLIENT_PLUS.
*/
public PlusClient getPlusClient() {
if (mPlusClient == null) {
throw new IllegalStateException("No PlusClient. Did you request it at setup?");
}
return mPlusClient;
}
/** Returns whether or not the user is signed in. */
public boolean isSignedIn() {
return mState == STATE_CONNECTED;
}
/**
* Returns whether or not there was a (non-recoverable) error during the
* sign-in process.
*/
public boolean hasSignInError() {
return mSignInFailureReason != null;
}
/**
* Returns the error that happened during the sign-in process, null if no
* error occurred.
*/
public SignInFailureReason getSignInError() {
return mSignInFailureReason;
}
/** Call this method from your Activity's onStart(). */
public void onStart(Activity act) {
mActivity = act;
debugLog("onStart, state = " + STATE_NAMES[mState]);
assertConfigured("onStart");
switch (mState) {
case STATE_DISCONNECTED:
// we are not connected, so attempt to connect
if (mAutoSignIn) {
debugLog("onStart: Now connecting clients.");
startConnections();
} else {
debugLog("onStart: Not connecting (user specifically signed out).");
}
break;
case STATE_CONNECTING:
// connection process is in progress; no action required
debugLog("onStart: connection process in progress, no action taken.");
break;
case STATE_CONNECTED:
// already connected (for some strange reason). No complaints :-)
debugLog("onStart: already connected (unusual, but ok).");
break;
default:
String msg = "onStart: BUG: unexpected state " + STATE_NAMES[mState];
logError(msg);
throw new IllegalStateException(msg);
}
}
/** Call this method from your Activity's onStop(). */
public void onStop() {
debugLog("onStop, state = " + STATE_NAMES[mState]);
assertConfigured("onStop");
switch (mState) {
case STATE_CONNECTED:
case STATE_CONNECTING:
// kill connections
debugLog("onStop: Killing connections");
killConnections();
break;
case STATE_DISCONNECTED:
debugLog("onStop: not connected, so no action taken.");
break;
default:
String msg = "onStop: BUG: unexpected state " + STATE_NAMES[mState];
logError(msg);
throw new IllegalStateException(msg);
}
// let go of the Activity reference
mActivity = null;
}
/** Convenience method to show an alert dialog. */
public void showAlert(String title, String message) {
(new AlertDialog.Builder(getContext())).setTitle(title).setMessage(message)
.setNeutralButton(android.R.string.ok, null).create().show();
}
/** Convenience method to show an alert dialog. */
public void showAlert(String message) {
(new AlertDialog.Builder(getContext())).setMessage(message)
.setNeutralButton(android.R.string.ok, null).create().show();
}
/**
* Returns the invitation ID received through an invitation notification.
* This should be called from your GameHelperListener's
*
* @link{GameHelperListener#onSignInSucceeded} method, to check if there's an
* invitation available. In that case, accept the invitation.
* @return The id of the invitation, or null if none was received.
*/
public String getInvitationId() {
if (!checkState(TYPE_DEVELOPER_ERROR, "getInvitationId",
"Invitation ID is only available when connected " +
"(after getting the onSignInSucceeded callback).", STATE_CONNECTED)) {
return null;
}
return mInvitationId;
}
/** Enables debug logging */
public void enableDebugLog(boolean enabled, String tag) {
mDebugLog = enabled;
mDebugTag = tag;
if (enabled) {
debugLog("Debug log enabled, tag: " + tag);
}
}
/**
* Returns the current requested scopes. This is not valid until setup() has
* been called.
*
* @return the requested scopes, including the oauth2: prefix
*/
public String getScopes() {
StringBuilder scopeStringBuilder = new StringBuilder();
if (null != mScopes) {
for (String scope: mScopes) {
addToScope(scopeStringBuilder, scope);
}
}
return scopeStringBuilder.toString();
}
/**
* Returns an array of the current requested scopes. This is not valid until
* setup() has been called
*
* @return the requested scopes, including the oauth2: prefix
*/
public String[] getScopesArray() {
return mScopes;
}
/** Sign out and disconnect from the APIs. */
public void signOut() {
if (mState == STATE_DISCONNECTED) {
// nothing to do
debugLog("signOut: state was already DISCONNECTED, ignoring.");
return;
}
// for the PlusClient, "signing out" means clearing the default account and
// then disconnecting
if (mPlusClient != null && mPlusClient.isConnected()) {
debugLog("Clearing default account on PlusClient.");
mPlusClient.clearDefaultAccount();
}
// For the games client, signing out means calling signOut and disconnecting
if (mGamesClient != null && mGamesClient.isConnected()) {
debugLog("Signing out from GamesClient.");
mGamesClient.signOut();
}
// Ready to disconnect
debugLog("Proceeding with disconnection.");
killConnections();
}
void killConnections() {
if (!checkState(TYPE_GAMEHELPER_BUG, "killConnections", "killConnections() should only " +
"get called while connected or connecting.", STATE_CONNECTED, STATE_CONNECTING)) {
return;
}
debugLog("killConnections: killing connections.");
mConnectionResult = null;
mSignInFailureReason = null;
if (mGamesClient != null && mGamesClient.isConnected()) {
debugLog("Disconnecting GamesClient.");
mGamesClient.disconnect();
}
if (mPlusClient != null && mPlusClient.isConnected()) {
debugLog("Disconnecting PlusClient.");
mPlusClient.disconnect();
}
if (mAppStateClient != null && mAppStateClient.isConnected()) {
debugLog("Disconnecting AppStateClient.");
mAppStateClient.disconnect();
}
mConnectedClients = CLIENT_NONE;
debugLog("killConnections: all clients disconnected.");
setState(STATE_DISCONNECTED);
}
static String activityResponseCodeToString(int respCode) {
switch (respCode) {
case Activity.RESULT_OK:
return "RESULT_OK";
case Activity.RESULT_CANCELED:
return "RESULT_CANCELED";
case GamesActivityResultCodes.RESULT_APP_MISCONFIGURED:
return "RESULT_APP_MISCONFIGURED";
case GamesActivityResultCodes.RESULT_LEFT_ROOM:
return "RESULT_LEFT_ROOM";
case GamesActivityResultCodes.RESULT_LICENSE_FAILED:
return "RESULT_LICENSE_FAILED";
case GamesActivityResultCodes.RESULT_RECONNECT_REQUIRED:
return "RESULT_RECONNECT_REQUIRED";
case GamesActivityResultCodes.RESULT_SIGN_IN_FAILED:
return "SIGN_IN_FAILED";
default:
return String.valueOf(respCode);
}
}
/**
* Handle activity result. Call this method from your Activity's
* onActivityResult callback. If the activity result pertains to the sign-in
* process, processes it appropriately.
*/
public void onActivityResult(int requestCode, int responseCode, Intent intent) {
debugLog("onActivityResult: req=" + (requestCode == RC_RESOLVE ? "RC_RESOLVE" :
String.valueOf(requestCode)) + ", resp=" +
activityResponseCodeToString(responseCode));
if (requestCode != RC_RESOLVE) {
debugLog("onActivityResult: request code not meant for us. Ignoring.");
return;
}
// no longer expecting a resolution
mExpectingResolution = false;
if (mState != STATE_CONNECTING) {
debugLog("onActivityResult: ignoring because state isn't STATE_CONNECTING (" +
"it's " + STATE_NAMES[mState] + ")");
return;
}
// We're coming back from an activity that was launched to resolve a
// connection problem. For example, the sign-in UI.
if (responseCode == Activity.RESULT_OK) {
// Ready to try to connect again.
debugLog("onAR: Resolution was RESULT_OK, so connecting current client again.");
connectCurrentClient();
} else if (responseCode == GamesActivityResultCodes.RESULT_RECONNECT_REQUIRED) {
debugLog("onAR: Resolution was RECONNECT_REQUIRED, so reconnecting.");
connectCurrentClient();
} else if (responseCode == Activity.RESULT_CANCELED) {
// User cancelled.
debugLog("onAR: Got a cancellation result, so disconnecting.");
mAutoSignIn = false;
mUserInitiatedSignIn = false;
mSignInFailureReason = null; // cancelling is not a failure!
killConnections();
notifyListener(false);
} else {
// Whatever the problem we were trying to solve, it was not
// solved. So give up and show an error message.
debugLog("onAR: responseCode=" + activityResponseCodeToString(responseCode) +
", so giving up.");
giveUp(new SignInFailureReason(mConnectionResult.getErrorCode(), responseCode));
}
}
void notifyListener(boolean success) {
debugLog("Notifying LISTENER of sign-in " + (success ? "SUCCESS" :
mSignInFailureReason != null ? "FAILURE (error)" : "FAILURE (no error)"));
if (mListener != null) {
if (success) {
mListener.onSignInSucceeded();
} else {
mListener.onSignInFailed();
}
}
}
/**
* Starts a user-initiated sign-in flow. This should be called when the user
* clicks on a "Sign In" button. As a result, authentication/consent dialogs
* may show up. At the end of the process, the GameHelperListener's
* onSignInSucceeded() or onSignInFailed() methods will be called.
*/
public void beginUserInitiatedSignIn() {
if (mState == STATE_CONNECTED) {
// nothing to do
logWarn("beginUserInitiatedSignIn() called when already connected. " +
"Calling listener directly to notify of success.");
notifyListener(true);
return;
} else if (mState == STATE_CONNECTING) {
logWarn("beginUserInitiatedSignIn() called when already connecting. " +
"Be patient! You can only call this method after you get an " +
"onSignInSucceeded() or onSignInFailed() callback. Suggestion: disable " +
"the sign-in button on startup and also when it's clicked, and re-enable " +
"when you get the callback.");
// ignore call (listener will get a callback when the connection process finishes)
return;
}
debugLog("Starting USER-INITIATED sign-in flow.");
// sign in automatically on onStart()
mAutoSignIn = true;
// Is Google Play services available?
int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
debugLog("isGooglePlayServicesAvailable returned " + result);
if (result != ConnectionResult.SUCCESS) {
// Google Play services is not available.
debugLog("Google Play services not available. Show error dialog.");
mSignInFailureReason = new SignInFailureReason(result, 0);
showFailureDialog();
notifyListener(false);
return;
}
// indicate that user is actively trying to sign in (so we know to resolve
// connection problems by showing dialogs)
mUserInitiatedSignIn = true;
if (mConnectionResult != null) {
// We have a pending connection result from a previous failure, so
// start with that.
debugLog("beginUserInitiatedSignIn: continuing pending sign-in flow.");
setState(STATE_CONNECTING);
resolveConnectionResult();
} else {
// We don't have a pending connection result, so start anew.
debugLog("beginUserInitiatedSignIn: starting new sign-in flow.");
startConnections();
}
}
Context getContext() {
return mActivity;
}
void addToScope(StringBuilder scopeStringBuilder, String scope) {
if (scopeStringBuilder.length() == 0) {
scopeStringBuilder.append("oauth2:");
} else {
scopeStringBuilder.append(" ");
}
scopeStringBuilder.append(scope);
}
void startConnections() {
if (!checkState(TYPE_GAMEHELPER_BUG, "startConnections", "startConnections should " +
"only get called when disconnected.", STATE_DISCONNECTED)) {
return;
}
debugLog("Starting connections.");
setState(STATE_CONNECTING);
mInvitationId = null;
connectNextClient();
}
void connectNextClient() {
// do we already have all the clients we need?
debugLog("connectNextClient: requested clients: " + mRequestedClients +
", connected clients: " + mConnectedClients);
// failsafe, in case we somehow lost track of what clients are connected or not.
if (mGamesClient != null && mGamesClient.isConnected() &&
(0 == (mConnectedClients & CLIENT_GAMES))) {
logWarn("GamesClient was already connected. Fixing.");
mConnectedClients |= CLIENT_GAMES;
}
if (mPlusClient != null && mPlusClient.isConnected() &&
(0 == (mConnectedClients & CLIENT_PLUS))) {
logWarn("PlusClient was already connected. Fixing.");
mConnectedClients |= CLIENT_PLUS;
}
if (mAppStateClient != null && mAppStateClient.isConnected() &&
(0 == (mConnectedClients & CLIENT_APPSTATE))) {
logWarn("AppStateClient was already connected. Fixing");
mConnectedClients |= CLIENT_APPSTATE;
}
int pendingClients = mRequestedClients & ~mConnectedClients;
debugLog("Pending clients: " + pendingClients);
if (pendingClients == 0) {
debugLog("All clients now connected. Sign-in successful!");
succeedSignIn();
return;
}
// which client should be the next one to connect?
if (mGamesClient != null && (0 != (pendingClients & CLIENT_GAMES))) {
debugLog("Connecting GamesClient.");
mClientCurrentlyConnecting = CLIENT_GAMES;
} else if (mPlusClient != null && (0 != (pendingClients & CLIENT_PLUS))) {
debugLog("Connecting PlusClient.");
mClientCurrentlyConnecting = CLIENT_PLUS;
} else if (mAppStateClient != null && (0 != (pendingClients & CLIENT_APPSTATE))) {
debugLog("Connecting AppStateClient.");
mClientCurrentlyConnecting = CLIENT_APPSTATE;
} else {
// hmmm, getting here would be a bug.
throw new AssertionError("Not all clients connected, yet no one is next. R="
+ mRequestedClients + ", C=" + mConnectedClients);
}
connectCurrentClient();
}
void connectCurrentClient() {
if (mState == STATE_DISCONNECTED) {
// we got disconnected during the connection process, so abort
logWarn("GameHelper got disconnected during connection process. Aborting.");
return;
}
if (!checkState(TYPE_GAMEHELPER_BUG, "connectCurrentClient", "connectCurrentClient " +
"should only get called when connecting.", STATE_CONNECTING)) {
return;
}
switch (mClientCurrentlyConnecting) {
case CLIENT_GAMES:
mGamesClient.connect();
break;
case CLIENT_APPSTATE:
mAppStateClient.connect();
break;
case CLIENT_PLUS:
mPlusClient.connect();
break;
}
}
/**
* Disconnects the indicated clients, then connects them again.
* @param whatClients Indicates which clients to reconnect.
*/
public void reconnectClients(int whatClients) {
checkState(TYPE_DEVELOPER_ERROR, "reconnectClients", "reconnectClients should " +
"only be called when connected. Proceeding anyway.", STATE_CONNECTED);
boolean actuallyReconnecting = false;
if ((whatClients & CLIENT_GAMES) != 0 && mGamesClient != null
&& mGamesClient.isConnected()) {
debugLog("Reconnecting GamesClient.");
actuallyReconnecting = true;
mConnectedClients &= ~CLIENT_GAMES;
mGamesClient.reconnect();
}
if ((whatClients & CLIENT_APPSTATE) != 0 && mAppStateClient != null
&& mAppStateClient.isConnected()) {
debugLog("Reconnecting AppStateClient.");
actuallyReconnecting = true;
mConnectedClients &= ~CLIENT_APPSTATE;
mAppStateClient.reconnect();
}
if ((whatClients & CLIENT_PLUS) != 0 && mPlusClient != null
&& mPlusClient.isConnected()) {
// PlusClient doesn't need reconnections.
logWarn("GameHelper is ignoring your request to reconnect " +
"PlusClient because this is unnecessary.");
}
if (actuallyReconnecting) {
setState(STATE_CONNECTING);
} else {
// No reconnections are to take place, so for consistency we call the listener
// as if sign in had just succeeded.
debugLog("No reconnections needed, so behaving as if sign in just succeeded");
notifyListener(true);
}
}
/** Called when we successfully obtain a connection to a client. */
@Override
public void onConnected(Bundle connectionHint) {
debugLog("onConnected: connected! client=" + mClientCurrentlyConnecting);
// Mark the current client as connected
mConnectedClients |= mClientCurrentlyConnecting;
debugLog("Connected clients updated to: " + mConnectedClients);
// If this was the games client and it came with an invite, store it for
// later retrieval.
if (mClientCurrentlyConnecting == CLIENT_GAMES && connectionHint != null) {
debugLog("onConnected: connection hint provided. Checking for invite.");
Invitation inv = connectionHint.getParcelable(GamesClient.EXTRA_INVITATION);
if (inv != null && inv.getInvitationId() != null) {
// accept invitation
debugLog("onConnected: connection hint has a room invite!");
mInvitationId = inv.getInvitationId();
debugLog("Invitation ID: " + mInvitationId);
}
}
// connect the next client in line, if any.
connectNextClient();
}
void succeedSignIn() {
checkState(TYPE_GAMEHELPER_BUG, "succeedSignIn", "succeedSignIn should only " +
"get called in the connecting or connected state. Proceeding anyway.",
STATE_CONNECTING, STATE_CONNECTED);
debugLog("All requested clients connected. Sign-in succeeded!");
setState(STATE_CONNECTED);
mSignInFailureReason = null;
mAutoSignIn = true;
mUserInitiatedSignIn = false;
notifyListener(true);
}
/** Handles a connection failure reported by a client. */
@Override
public void onConnectionFailed(ConnectionResult result) {
// save connection result for later reference
debugLog("onConnectionFailed");
mConnectionResult = result;
debugLog("Connection failure:");
debugLog(" - code: " + errorCodeToString(mConnectionResult.getErrorCode()));
debugLog(" - resolvable: " + mConnectionResult.hasResolution());
debugLog(" - details: " + mConnectionResult.toString());
if (!mUserInitiatedSignIn) {
// If the user didn't initiate the sign-in, we don't try to resolve
// the connection problem automatically -- instead, we fail and wait
// for the user to want to sign in. That way, they won't get an
// authentication (or other) popup unless they are actively trying
// to
// sign in.
debugLog("onConnectionFailed: since user didn't initiate sign-in, failing now.");
mConnectionResult = result;
setState(STATE_DISCONNECTED);
notifyListener(false);
return;
}
debugLog("onConnectionFailed: since user initiated sign-in, resolving problem.");
// Resolve the connection result. This usually means showing a dialog or
// starting an Activity that will allow the user to give the appropriate
// consents so that sign-in can be successful.
resolveConnectionResult();
}
/**
* Attempts to resolve a connection failure. This will usually involve
* starting a UI flow that lets the user give the appropriate consents
* necessary for sign-in to work.
*/
void resolveConnectionResult() {
// Try to resolve the problem
checkState(TYPE_GAMEHELPER_BUG, "resolveConnectionResult",
"resolveConnectionResult should only be called when connecting. Proceeding anyway.",
STATE_CONNECTING);
if (mExpectingResolution) {
debugLog("We're already expecting the result of a previous resolution.");
return;
}
debugLog("resolveConnectionResult: trying to resolve result: " + mConnectionResult);
if (mConnectionResult.hasResolution()) {
// This problem can be fixed. So let's try to fix it.
debugLog("Result has resolution. Starting it.");
try {
// launch appropriate UI flow (which might, for example, be the
// sign-in flow)
mExpectingResolution = true;
mConnectionResult.startResolutionForResult(mActivity, RC_RESOLVE);
} catch (SendIntentException e) {
// Try connecting again
debugLog("SendIntentException, so connecting again.");
connectCurrentClient();
}
} else {
// It's not a problem what we can solve, so give up and show an
// error.
debugLog("resolveConnectionResult: result has no resolution. Giving up.");
giveUp(new SignInFailureReason(mConnectionResult.getErrorCode()));
}
}
/**
* Give up on signing in due to an error. Shows the appropriate error
* message to the user, using a standard error dialog as appropriate to the
* cause of the error. That dialog will indicate to the user how the problem
* can be solved (for example, re-enable Google Play Services, upgrade to a
* new version, etc).
*/
void giveUp(SignInFailureReason reason) {
checkState(TYPE_GAMEHELPER_BUG, "giveUp", "giveUp should only be called when " +
"connecting. Proceeding anyway.", STATE_CONNECTING);
mAutoSignIn = false;
killConnections();
mSignInFailureReason = reason;
showFailureDialog();
notifyListener(false);
}
/** Called when we are disconnected from a client. */
@Override
public void onDisconnected() {
debugLog("onDisconnected.");
if (mState == STATE_DISCONNECTED) {
// This is expected.
debugLog("onDisconnected is expected, so no action taken.");
return;
}
// Unexpected disconnect (rare!)
logWarn("Unexpectedly disconnected. Severing remaining connections.");
// kill the other connections too, and revert to DISCONNECTED state.
killConnections();
mSignInFailureReason = null;
// call the sign in failure callback
debugLog("Making extraordinary call to onSignInFailed callback");
notifyListener(false);
}
/** Shows an error dialog that's appropriate for the failure reason. */
void showFailureDialog() {
Context ctx = getContext();
if (ctx == null) {
debugLog("*** No context. Can't show failure dialog.");
return;
}
debugLog("Making error dialog for failure: " + mSignInFailureReason);
Dialog errorDialog = null;
int errorCode = mSignInFailureReason.getServiceErrorCode();
int actResp = mSignInFailureReason.getActivityResultCode();
switch (actResp) {
case GamesActivityResultCodes.RESULT_APP_MISCONFIGURED:
errorDialog = makeSimpleDialog(ctx.getString(
R.string.gamehelper_app_misconfigured));
printMisconfiguredDebugInfo();
break;
case GamesActivityResultCodes.RESULT_SIGN_IN_FAILED:
errorDialog = makeSimpleDialog(ctx.getString(
R.string.gamehelper_sign_in_failed));
break;
case GamesActivityResultCodes.RESULT_LICENSE_FAILED:
errorDialog = makeSimpleDialog(ctx.getString(
R.string.gamehelper_license_failed));
break;
default:
// No meaningful Activity response code, so generate default Google
// Play services dialog
errorDialog = GooglePlayServicesUtil.getErrorDialog(errorCode, mActivity,
RC_UNUSED, null);
if (errorDialog == null) {
// get fallback dialog
debugLog("No standard error dialog available. Making fallback dialog.");
errorDialog = makeSimpleDialog(ctx.getString(R.string.gamehelper_unknown_error)
+ " " + errorCodeToString(errorCode));
}
}
debugLog("Showing error dialog.");
errorDialog.show();
}
Dialog makeSimpleDialog(String text) {
return (new AlertDialog.Builder(getContext())).setMessage(text)
.setNeutralButton(android.R.string.ok, null).create();
}
void debugLog(String message) {
if (mDebugLog) {
Log.d(mDebugTag, "GameHelper: " + message);
}
}
void logWarn(String message) {
Log.w(mDebugTag, "!!! GameHelper WARNING: " + message);
}
void logError(String message) {
Log.e(mDebugTag, "*** GameHelper ERROR: " + message);
}
static String errorCodeToString(int errorCode) {
switch (errorCode) {
case ConnectionResult.DEVELOPER_ERROR:
return "DEVELOPER_ERROR(" + errorCode + ")";
case ConnectionResult.INTERNAL_ERROR:
return "INTERNAL_ERROR(" + errorCode + ")";
case ConnectionResult.INVALID_ACCOUNT:
return "INVALID_ACCOUNT(" + errorCode + ")";
case ConnectionResult.LICENSE_CHECK_FAILED:
return "LICENSE_CHECK_FAILED(" + errorCode + ")";
case ConnectionResult.NETWORK_ERROR:
return "NETWORK_ERROR(" + errorCode + ")";
case ConnectionResult.RESOLUTION_REQUIRED:
return "RESOLUTION_REQUIRED(" + errorCode + ")";
case ConnectionResult.SERVICE_DISABLED:
return "SERVICE_DISABLED(" + errorCode + ")";
case ConnectionResult.SERVICE_INVALID:
return "SERVICE_INVALID(" + errorCode + ")";
case ConnectionResult.SERVICE_MISSING:
return "SERVICE_MISSING(" + errorCode + ")";
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
return "SERVICE_VERSION_UPDATE_REQUIRED(" + errorCode + ")";
case ConnectionResult.SIGN_IN_REQUIRED:
return "SIGN_IN_REQUIRED(" + errorCode + ")";
case ConnectionResult.SUCCESS:
return "SUCCESS(" + errorCode + ")";
default:
return "Unknown error code " + errorCode;
}
}
// Represents the reason for a sign-in failure
public static class SignInFailureReason {
public static final int NO_ACTIVITY_RESULT_CODE = -100;
int mServiceErrorCode = 0;
int mActivityResultCode = NO_ACTIVITY_RESULT_CODE;
public int getServiceErrorCode() {
return mServiceErrorCode;
}
public int getActivityResultCode() {
return mActivityResultCode;
}
public SignInFailureReason(int serviceErrorCode, int activityResultCode) {
mServiceErrorCode = serviceErrorCode;
mActivityResultCode = activityResultCode;
}
public SignInFailureReason(int serviceErrorCode) {
this(serviceErrorCode, NO_ACTIVITY_RESULT_CODE);
}
@Override
public String toString() {
return "SignInFailureReason(serviceErrorCode:" +
errorCodeToString(mServiceErrorCode) +
((mActivityResultCode == NO_ACTIVITY_RESULT_CODE) ? ")" :
(",activityResultCode:" +
activityResponseCodeToString(mActivityResultCode) + ")"));
}
}
void printMisconfiguredDebugInfo() {
debugLog("****");
debugLog("****");
debugLog("**** APP NOT CORRECTLY CONFIGURED TO USE GOOGLE PLAY GAME SERVICES");
debugLog("**** This is usually caused by one of these reasons:");
debugLog("**** (1) Your package name and certificate fingerprint do not match");
debugLog("**** the client ID you registered in Developer Console.");
debugLog("**** (2) Your App ID was incorrectly entered.");
debugLog("**** (3) Your game settings have not been published and you are ");
debugLog("**** trying to log in with an account that is not listed as");
debugLog("**** a test account.");
debugLog("****");
Context ctx = getContext();
if (ctx == null) {
debugLog("*** (no Context, so can't print more debug info)");
return;
}
debugLog("**** To help you debug, here is the information about this app");
debugLog("**** Package name : " + getContext().getPackageName());
debugLog("**** Cert SHA1 fingerprint: " + getSHA1CertFingerprint());
debugLog("**** App ID from : " + getAppIdFromResource());
debugLog("****");
debugLog("**** Check that the above information matches your setup in ");
debugLog("**** Developer Console. Also, check that you're logging in with the");
debugLog("**** right account (it should be listed in the Testers section if");
debugLog("**** your project is not yet published).");
debugLog("****");
debugLog("**** For more information, refer to the troubleshooting guide:");
debugLog("**** http://developers.google.com/games/services/android/troubleshooting");
}
String getAppIdFromResource() {
try {
Resources res = getContext().getResources();
String pkgName = getContext().getPackageName();
int res_id = res.getIdentifier("app_id", "string", pkgName);
return res.getString(res_id);
} catch (Exception ex) {
ex.printStackTrace();
return "??? (failed to retrieve APP ID)";
}
}
String getSHA1CertFingerprint() {
try {
Signature[] sigs = getContext().getPackageManager().getPackageInfo(
getContext().getPackageName(), PackageManager.GET_SIGNATURES).signatures;
if (sigs.length == 0) {
return "ERROR: NO SIGNATURE.";
} else if (sigs.length > 1) {
return "ERROR: MULTIPLE SIGNATURES";
}
byte[] digest = MessageDigest.getInstance("SHA1").digest(sigs[0].toByteArray());
StringBuilder hexString = new StringBuilder();
for (int i = 0; i < digest.length; ++i) {
if (i > 0) {
hexString.append(":");
}
byteToString(hexString, digest[i]);
}
return hexString.toString();
} catch (PackageManager.NameNotFoundException ex) {
ex.printStackTrace();
return "(ERROR: package not found)";
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
return "(ERROR: SHA1 algorithm not found)";
}
}
void byteToString(StringBuilder sb, byte b) {
int unsigned_byte = b < 0 ? b + 256 : b;
int hi = unsigned_byte / 16;
int lo = unsigned_byte % 16;
sb.append("0123456789ABCDEF".substring(hi, hi + 1));
sb.append("0123456789ABCDEF".substring(lo, lo + 1));
}
}
| |
package com.quollwriter.data;
import java.io.*;
import java.lang.ref.*;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.WeakHashMap;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
import com.gentlyweb.properties.*;
import com.gentlyweb.xml.*;
import com.quollwriter.*;
import com.quollwriter.events.*;
import org.jdom.*;
public abstract class DataObject
{
private String objType = null;
protected Properties props = new Properties ();
protected Long key = null;
private String id = null;
private String version = null;
private boolean latest = true;
// protected Date lastModified = null;
private Date dateCreated = new Date ();
protected DataObject parent = null;
private Map<PropertyChangedListener, Object> listeners = null;
// Just used in the maps above as a placeholder for the listeners.
private static final Object listenerFillObj = new Object ();
public DataObject(String objType)
{
// We use a synchronized weak hash map here so that we don't have to worry about all the
// references since they will be transient compared to the potential lifespan of the object.
// Where possible listeners should de-register as normal but this just ensure that objects
// that don't have a controlled pre-defined lifecycle.
this.listeners = Collections.synchronizedMap (new WeakHashMap ());
if (objType != null)
{
if (objType.equals ("outline-item"))
{
objType = OutlineItem.OBJECT_TYPE;
}
if (objType.indexOf ("-") != -1)
{
throw new IllegalArgumentException ("Object type: " +
objType +
" cannot contain the character '-'");
}
}
this.setObjectType (objType);
}
@Override
public String toString ()
{
return Environment.formatObjectToStringProperties (this);
}
protected void addToStringProperties (Map<String, Object> props,
String name,
Object value)
{
if (props.containsKey (name))
{
throw new IllegalArgumentException ("Already have a toString property with name: " +
name +
", props: " +
props);
}
props.put (name,
value);
}
public void fillToStringProperties (Map<String, Object> props)
{
this.addToStringProperties (props,
"objType",
this.objType);
this.addToStringProperties (props,
"key",
this.key);
this.addToStringProperties (props,
"id",
this.id);
this.addToStringProperties (props,
"version",
this.version);
this.addToStringProperties (props,
"latest",
this.latest);
this.addToStringProperties (props,
"dateCreated",
this.dateCreated);
this.addToStringProperties (props,
"parent",
this.parent);
}
public abstract DataObject getObjectForReference (ObjectReference r);
public void setLatest (boolean v)
{
this.latest = v;
}
public boolean isLatest ()
{
return this.latest;
}
public void setVersion (String v)
{
this.version = v;
}
public String getVersion ()
{
return this.version;
}
public void setId (String id)
{
if ((this.id != null)
&&
(id != null)
)
{
throw new IllegalStateException ("Once the id for an object is set it cannot be set again.");
}
this.id = id;
}
public String getId ()
{
return this.id;
}
public Date getDateCreated ()
{
if (this.dateCreated == null)
{
this.dateCreated = new Date ();
}
return this.dateCreated;
}
public void setDateCreated (Date d)
{
this.dateCreated = d;
}
protected synchronized void firePropertyChangedEvent (String type,
Object oldValue,
Object newValue)
{
if ((oldValue == null) &&
(newValue == null))
{
return;
}
boolean changed = false;
if ((oldValue != null) &&
(newValue == null))
{
changed = true;
}
if ((oldValue == null) &&
(newValue != null))
{
changed = true;
}
if ((oldValue != null) &&
(newValue != null))
{
if (!oldValue.equals (newValue))
{
changed = true;
}
}
if (!changed)
{
return;
}
Object o = new Object ();
Set<PropertyChangedListener> ls = null;
// Get a copy of the current valid listeners.
synchronized (this.listeners)
{
ls = new HashSet (this.listeners.keySet ());
}
PropertyChangedEvent ev = new PropertyChangedEvent (this,
type,
oldValue,
newValue);
for (PropertyChangedListener l : ls)
{
if (l == null)
{
continue;
}
l.propertyChanged (ev);
}
}
public void removePropertyChangedListener (PropertyChangedListener l)
{
this.listeners.remove (l);
}
/**
* Adds a property changed listener to the object.
*
* Warning! The listeners use a weak hash map structure so it is up to the caller to ensure that
* the listener has the relevant lifespan to be called.
* For example, this will cause the listener to be removed:
*
* <code>
* // Don't do this, the reference isn't strong and the inner object will be garbage collected once
* // it falls out of scope.
* myObj.addPropertyChangedListener (new PropertyChangedListener ()
* {
*
* public void propertyChanged (PropertyChangedEvent ev) {}
*
* });
* </code>
*
* Instead ensure that the listener is tied to the transient object (with the variable lifespan) instead, i.e.
* use "implements PropertyChangedListener" or keep a reference to the listener, thus:
*
* <code>
* this.propListener = new PropertyChangedListener ()
* {
*
* public void propertyChanged (PropertyChangedEvent ev) {}
*
* };
* </code>
*
* Note: this makes sense anyway since otherwise it would lead to a memory leak and potentially dangling references.
*
* For clarity, the weak map structure is used because the caller may not have a well defined lifespan/lifecycle, that
* is you may not be able to remove the listener at the time the enclosing class falls out of use. Consider a box that
* displays information about this DataObject and listens for changes to the object and then updates as necessary. If
* a standard map (with strong references) is used then it forces the box to have a well defined lifecycle that is managed by the class using
* the box, the user of the box would need to be aware of the internals of the box and its behaviour. This is a huge
* burden and not always possible since java does not guarantee that an object is ever "finalized" unless it is no longer
* references, but this would never happen because of the strong reference to the listener in the map.
*
* @param l The listener.
*/
public void addPropertyChangedListener (PropertyChangedListener l)
{
this.listeners.put (l,
this.listenerFillObj);
}
public DataObject getParent ()
{
return this.parent;
}
public void setParent (DataObject d)
{
if (d == null)
{
this.parent = null;
//this.props.setParentProperties (null);
return;
}
this.parent = d;
// Get the properties parent.
Properties pp = this.props;
if (pp.getId ().equals (this.objType + "-" + this.key))
{
pp = pp.getParentProperties ();
}
pp.setParentProperties (d.getProperties ());
}
public String getPropertiesAsString ()
throws Exception
{
// Conver the properties to a string.
return JDOMUtils.getElementAsString (this.props.getAsJDOMElement ());
}
public void setPropertiesAsString (String p)
throws Exception
{
if (p == null)
{
return;
}
// Convert to XML, convert to Properties.
Element root = JDOMUtils.getStringAsElement (p);
if (this.props == null)
{
throw new IllegalStateException ("The object should have some properties: " +
p);
}
Properties pr = this.props;
this.props = new Properties (root);
this.props.setId (this.objType + "-" + this.key);
this.props.setParentProperties (pr);
}
void setObjectType (String objType)
{
this.objType = objType;
this.props = new Properties ();
this.props.setId (this.objType + "-" + this.key);
this.props.setParentProperties (Environment.getDefaultProperties (this.objType));
}
public void setKey (Long k)
{
this.key = k;
}
public Long getKey ()
{
return this.key;
}
public void setProperty (String name,
String value)
throws IOException
{
StringProperty p = new StringProperty (name,
value);
p.setDescription ("N/A");
this.props.setProperty (name,
p);
}
public void setProperty (String name,
int value)
throws IOException
{
IntegerProperty p = new IntegerProperty (name,
value);
p.setDescription ("N/A");
this.props.setProperty (name,
p);
}
public void removeProperty (String name)
{
this.props.removeProperty (name);
}
public void setProperty (String name,
boolean value)
throws IOException
{
BooleanProperty p = new BooleanProperty (name,
value);
p.setDescription ("N/A");
this.props.setProperty (name,
p);
}
public String getProperty (String name,
String defName)
{
AbstractProperty ap = this.props.getPropertyObj (name);
if (ap == null)
{
return this.getProperty (defName);
}
return this.getProperty (name);
}
public String getProperty (String name)
{
return this.props.getProperty (name);
}
public boolean getPropertyAsBoolean (String name,
String defName)
{
AbstractProperty ap = this.props.getPropertyObj (name);
if (ap == null)
{
return this.getPropertyAsBoolean (defName);
}
return this.getPropertyAsBoolean (name);
}
public boolean getPropertyAsBoolean (String name)
{
return this.props.getPropertyAsBoolean (name);
}
public int getPropertyAsInt (String name,
String defName)
{
AbstractProperty ap = this.props.getPropertyObj (name);
if (ap == null)
{
return this.getPropertyAsInt (defName);
}
return this.getPropertyAsInt (name);
}
public int getPropertyAsInt (String name)
{
return this.props.getPropertyAsInt (name);
}
public float getPropertyAsFloat (String name,
String defName)
{
AbstractProperty ap = this.props.getPropertyObj (name);
if (ap == null)
{
return this.getPropertyAsFloat (defName);
}
return this.props.getPropertyAsFloat (name);
}
public float getPropertyAsFloat (String name)
{
return this.props.getPropertyAsFloat (name);
}
public Properties getProperties ()
{
return this.props;
}
public String getObjectType ()
{
return this.objType;
}
@Override
public int hashCode ()
{
if (this.key == null)
{
return super.hashCode ();
}
int hash = 7;
hash = (31 * hash) + ((null == this.objType) ? 0 : this.objType.hashCode ());
hash = (31 * hash) + ((null == this.key) ? 0 : key.hashCode ());
return hash;
}
@Override
public boolean equals (Object o)
{
if ((o == null) || (!(o instanceof DataObject)))
{
return false;
}
DataObject d = (DataObject) o;
if ((d.key == null) ||
(this.key == null))
{
return d.hashCode () == this.hashCode ();
//return false;
}
if ((d.key.equals (this.key)) &&
(d.objType.equals (this.objType)))
{
return true;
}
return false;
}
public ObjectReference getObjectReference ()
{
return new ObjectReference (this.getObjectType (),
this.getKey (),
((this.parent == null) ? null : this.parent.getObjectReference ()));
}
}
| |
/*
* Copyright (C) 2017 FormKiQ Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.formkiq.forms;
import static com.formkiq.forms.FormFieldMapper.extractLabelAndValue;
import static com.formkiq.forms.FormFinder.findField;
import static com.formkiq.forms.FormFinder.findValueByKey;
import static com.formkiq.forms.TestDataBuilder.createSimpleForm;
import static com.formkiq.forms.TestDataBuilder.createStoreReceipt;
import static com.formkiq.forms.TestDataBuilder.createWorkflow;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.Test;
import com.formkiq.forms.dto.FormJSON;
import com.formkiq.forms.dto.FormJSONField;
import com.formkiq.forms.dto.FormJSONFieldType;
import com.formkiq.forms.dto.FormJSONRequiredType;
import com.formkiq.forms.dto.Workflow;
/**
* {@link FormFieldMapper} Unit Tests.
*
*/
public class FormFieldMapperTest {
/** {@link JSONService}. */
private JSONService jsonService = new JSONService();
/**
* testMap01().
*/
@Test
public void testMap01() {
// given
FormJSON source = createSimpleForm();
findField(source, 1).get().setValue("dummyval");
FormJSON dest = createStoreReceipt();
findField(dest, 1).get().setValue("100");
Map<String, String> mapping = new HashMap<>();
mapping.put("1", "2");
// when
FormFieldMapper.map(source, dest, mapping);
// then
assertEquals("100", findField(dest, 1).get().getValue());
assertEquals("dummyval", findField(dest, 2).get().getValue());
}
/**
* testMapByValue01().
* @throws Exception Exception
*/
@Test
public void testMapByValue01() throws Exception {
// given
FormJSON source = createSimpleForm();
FormJSONField field = source.getSections().get(0).getFields().get(0);
field.setOptions(Arrays.asList("option1", "option2"));
field.setType(FormJSONFieldType.SWITCH);
field.setRequired(FormJSONRequiredType.IMMEDIATE);
FormJSON dest = this.jsonService.loadForm(FormJSONField.class);
// when
FormFieldMapper.mapByValue(field, dest);
// then
assertEquals("Checkbox[Switch]",
findValueByKey(dest, "type").get().getValue());
assertEquals("Total ($)",
findValueByKey(dest, "label").get().getValue());
assertEquals("Immediate[immediate]",
findValueByKey(dest, "required").get().getValue());
assertEquals("option1\noption2",
findValueByKey(dest, "options").get().getValue());
}
/**
* testMapByValue02().
* map {@link FormJSON} to {@link FormJSONField}
* @throws Exception Exception
*/
@Test
public void testMapByValue02() throws Exception {
// given
final int labelId = 20;
final int requiredId = 40;
FormJSON source = this.jsonService.loadForm(FormJSONField.class);
findField(source, labelId).get().setValue("sample");
findField(source, requiredId).get().setValue("Immediate[immediate]");
FormJSONField dest = new FormJSONField();
// when
FormFieldMapper.mapByValue(source, dest);
// then
assertEquals("sample", dest.getLabel());
assertEquals(FormJSONRequiredType.IMMEDIATE, dest.getRequired());
}
/**
* Workflow.
* @throws Exception Exception
*/
@Test
public void testMapByValue03() throws Exception {
// given
FormJSON f = createSimpleForm();
Workflow source = createWorkflow(f);
source.setAllowinprocess(true);
FormJSON dest = this.jsonService.loadForm(Workflow.class);
// when
FormFieldMapper.mapByValue(source, dest);
// then
assertEquals(source.getName(),
findValueByKey(dest, "name").get().getValue());
assertEquals("true",
findValueByKey(dest, "allowinprocess").get().getValue());
assertEquals(f.getName() + "[" + f.getUUID() + "]",
findValueByKey(dest, "label1form").get().getValue());
assertEquals("Total ($)[1]",
findValueByKey(dest, "label1field").get().getValue());
assertEquals("", findValueByKey(dest, "label2form").get().getValue());
assertNull(findValueByKey(dest, "label2field").get().getValue());
assertEquals("", findValueByKey(dest, "label3form").get().getValue());
assertNull(findValueByKey(dest, "label3field").get().getValue());
// given
Workflow wf = new Workflow();
// when
FormFieldMapper.mapByValue(dest, wf);
// then
assertEquals("Sample WF", wf.getName());
assertTrue(wf.isAllowinprocess());
assertEquals(f.getName() + "[" + f.getUUID() + "]", wf.getLabel1form());
assertEquals("Total ($)[1]", wf.getLabel1field());
assertEquals("", wf.getLabel2form());
assertNull(wf.getLabel2field());
assertEquals("", wf.getLabel3form());
assertNull(wf.getLabel3field());
}
/**
* testExtractLabelAndValue01().
*/
@Test
public void testExtractLabelAndValue01() {
// given
String s = "name[1]";
// when
Pair<String, String> results = extractLabelAndValue(s);
// then
assertEquals("name", results.getLeft());
assertEquals("1", results.getRight());
}
/**
* testExtractLabelAndValue02().
*/
@Test
public void testExtractLabelAndValue02() {
// given
String s = "name";
// when
Pair<String, String> results = extractLabelAndValue(s);
// then
assertEquals("name", results.getLeft());
assertEquals("name", results.getRight());
}
/**
* testExtractLabelAndValue03().
*/
@Test
public void testExtractLabelAndValue03() {
// given
String s = null;
// when
Pair<String, String> results = extractLabelAndValue(s);
// then
assertEquals("", results.getLeft());
assertEquals("", results.getRight());
}
}
| |
/*
* Copyright (C) 2015 Peter Gregus for GravityBox Project (C3C076@xda)
* 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.ceco.marshmallow.gravitybox.managers;
import java.util.ArrayList;
import java.util.List;
import com.ceco.marshmallow.gravitybox.BroadcastSubReceiver;
import com.ceco.marshmallow.gravitybox.GravityBoxSettings;
import com.ceco.marshmallow.gravitybox.ModPower;
import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.PowerManager;
import android.os.SystemClock;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XSharedPreferences;
public class KeyguardStateMonitor implements BroadcastSubReceiver {
public static final String TAG="GB:KeyguardStateMonitor";
public static final String CLASS_KG_MONITOR =
"com.android.systemui.statusbar.policy.KeyguardMonitor";
public static final String CLASS_KG_UPDATE_MONITOR =
"com.android.keyguard.KeyguardUpdateMonitor";
public static final String CLASS_KG_VIEW_MEDIATOR =
"com.android.systemui.keyguard.KeyguardViewMediator";
private static boolean DEBUG = false;
private static enum ImprintMode { DEFAULT, WAKE_ONLY };
private static void log(String msg) {
XposedBridge.log(TAG + ": " + msg);
}
public interface Listener {
void onKeyguardStateChanged();
}
private XSharedPreferences mPrefs;
private Context mContext;
private boolean mIsShowing;
private boolean mIsSecured;
private boolean mIsLocked;
private boolean mIsTrustManaged;
private boolean mIsKeyguardDisabled;
private Object mMonitor;
private Object mUpdateMonitor;
private Object mMediator;
private boolean mProxWakeupEnabled;
private PowerManager mPm;
private Handler mHandler;
private boolean mFpAuthOnNextScreenOn;
private ImprintMode mImprintMode = ImprintMode.DEFAULT;
private List<Listener> mListeners = new ArrayList<>();
protected KeyguardStateMonitor(Context context, XSharedPreferences prefs) {
mContext = context;
mPrefs = prefs;
mPm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
mHandler = new Handler();
mProxWakeupEnabled = prefs.getBoolean(
GravityBoxSettings.PREF_KEY_POWER_PROXIMITY_WAKE, false);
mImprintMode = ImprintMode.valueOf(prefs.getString(
GravityBoxSettings.PREF_KEY_LOCKSCREEN_IMPRINT_MODE, "DEFAULT"));
createHooks();
}
public void setMediator(Object mediator) {
mMediator = mediator;
}
private void createHooks() {
try {
ClassLoader cl = mContext.getClassLoader();
Class<?> monitorClass = XposedHelpers.findClass(CLASS_KG_MONITOR, cl);
XposedBridge.hookAllConstructors(monitorClass, new XC_MethodHook() {
@Override
protected void afterHookedMethod(final MethodHookParam param) throws Throwable {
mMonitor = param.thisObject;
mUpdateMonitor = XposedHelpers.getObjectField(mMonitor, "mKeyguardUpdateMonitor");
}
});
XposedHelpers.findAndHookMethod(CLASS_KG_MONITOR, cl,
"notifyKeyguardChanged", new XC_MethodHook() {
@Override
protected void afterHookedMethod(final MethodHookParam param) throws Throwable {
boolean showing = XposedHelpers.getBooleanField(param.thisObject, "mShowing");
boolean secured = XposedHelpers.getBooleanField(param.thisObject, "mSecure");
boolean locked = !XposedHelpers.getBooleanField(param.thisObject, "mCanSkipBouncer");
boolean managed = getIsTrustManaged();
if (showing != mIsShowing || secured != mIsSecured ||
locked != mIsLocked || managed != mIsTrustManaged) {
mIsShowing = showing;
mIsSecured = secured;
mIsLocked = locked;
mIsTrustManaged = managed;
notifyStateChanged();
}
}
});
XposedHelpers.findAndHookMethod(CLASS_KG_VIEW_MEDIATOR, cl,
"setKeyguardEnabled", boolean.class, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(final MethodHookParam param) throws Throwable {
if (mIsKeyguardDisabled && (boolean)param.args[0] &&
!keyguardEnforcedByDevicePolicy()) {
param.setResult(null);
}
}
});
XposedBridge.hookAllMethods(XposedHelpers.findClass(CLASS_KG_UPDATE_MONITOR, cl),
"handleFingerprintAuthenticated", new XC_MethodHook() {
@Override
protected void beforeHookedMethod(final MethodHookParam param) throws Throwable {
if ((mProxWakeupEnabled || mImprintMode == ImprintMode.WAKE_ONLY) &&
!XposedHelpers.getBooleanField(param.thisObject, "mDeviceInteractive")) {
mFpAuthOnNextScreenOn = mProxWakeupEnabled && mImprintMode == ImprintMode.DEFAULT;
XposedHelpers.callMethod(mPm, "wakeUp", SystemClock.uptimeMillis());
if (mFpAuthOnNextScreenOn) {
mHandler.postDelayed(mResetFpRunnable, ModPower.MAX_PROXIMITY_WAIT + 200);
} else {
mResetFpRunnable.run();
}
param.setResult(null);
}
}
});
} catch (Throwable t) {
XposedBridge.log(t);
}
}
private boolean getIsTrustManaged() {
return (boolean) XposedHelpers.callMethod(mUpdateMonitor,
"getUserTrustIsManaged", getCurrentUserId());
}
public boolean keyguardEnforcedByDevicePolicy() {
DevicePolicyManager dpm = (DevicePolicyManager)
mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
if (dpm != null) {
int passwordQuality = dpm.getPasswordQuality(null);
switch (passwordQuality) {
case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
return true;
}
}
return false;
}
private void notifyStateChanged() {
if (DEBUG) log("showing:" + mIsShowing + "; secured:" + mIsSecured +
"; locked:" + mIsLocked + "; trustManaged:" + mIsTrustManaged);
synchronized (mListeners) {
for (Listener l : mListeners) {
l.onKeyguardStateChanged();
}
}
}
public void registerListener(Listener l) {
if (l == null) return;
synchronized (mListeners) {
if (!mListeners.contains(l)) {
mListeners.add(l);
}
}
}
public void unregisterListener(Listener l) {
if (l == null) return;
synchronized (mListeners) {
if (mListeners.contains(l)) {
mListeners.remove(l);
}
}
}
public int getCurrentUserId() {
try {
return XposedHelpers.getIntField(mMonitor, "mCurrentUser");
} catch (Throwable t) {
return 0;
}
}
public boolean isShowing() {
return mIsShowing;
}
public boolean isSecured() {
return mIsSecured;
}
public boolean isLocked() {
return (mIsSecured && mIsLocked);
}
public boolean isTrustManaged() {
return mIsTrustManaged;
}
public void dismissKeyguard() {
if (mMediator != null) {
try {
XposedHelpers.callMethod(mMediator, "dismiss");
} catch (Throwable t) {
XposedBridge.log(t);
}
}
}
public void setKeyguardDisabled(boolean disabled) {
try {
mIsKeyguardDisabled = disabled;
XposedHelpers.callMethod(mMediator, "setKeyguardEnabled", !disabled);
if (mIsKeyguardDisabled) {
XposedHelpers.setBooleanField(mMediator, "mNeedToReshowWhenReenabled", false);
}
} catch (Throwable t) {
XposedBridge.log(t);
}
}
public boolean isKeyguardDisabled() {
return mIsKeyguardDisabled;
}
private Runnable mResetFpRunnable = new Runnable() {
@Override
public void run() {
mFpAuthOnNextScreenOn = false;
try {
XposedHelpers.setBooleanField(mUpdateMonitor, "mFingerprintAlreadyAuthenticated", false);
} catch (Throwable t) { /* ignore */ }
try {
XposedHelpers.callMethod(mUpdateMonitor, "setFingerprintRunningState", 0);
} catch (Throwable t) {
try {
XposedHelpers.callMethod(mUpdateMonitor, "setFingerprintRunningDetectionRunning", false);
} catch (Throwable t2) {
XposedBridge.log(t2);
}
}
try {
XposedHelpers.callMethod(mUpdateMonitor, "updateFingerprintListeningState");
} catch (Throwable t) {
XposedBridge.log(t);
}
}
};
private void handleFingerprintAuthenticated() {
try {
XposedHelpers.callMethod(mUpdateMonitor, "handleFingerprintAuthenticated");
} catch (Throwable t) {
XposedBridge.log(t);
}
}
@Override
public void onBroadcastReceived(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_SCREEN_ON)) {
if (mFpAuthOnNextScreenOn) {
mHandler.removeCallbacks(mResetFpRunnable);
mFpAuthOnNextScreenOn = false;
handleFingerprintAuthenticated();
}
} else if (action.equals(GravityBoxSettings.ACTION_PREF_POWER_CHANGED) &&
intent.hasExtra(GravityBoxSettings.EXTRA_POWER_PROXIMITY_WAKE)) {
mProxWakeupEnabled = intent.getBooleanExtra(
GravityBoxSettings.EXTRA_POWER_PROXIMITY_WAKE, false);
} else if (action.equals(GravityBoxSettings.ACTION_LOCKSCREEN_SETTINGS_CHANGED)) {
mPrefs.reload();
mImprintMode = ImprintMode.valueOf(mPrefs.getString(
GravityBoxSettings.PREF_KEY_LOCKSCREEN_IMPRINT_MODE, "DEFAULT"));
}
}
}
| |
/*
* Copyright 2014 Alexey Andreev.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* 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.teavm.classlib.java.util;
import java.util.Arrays;
import org.teavm.classlib.impl.unicode.CLDRHelper;
import org.teavm.classlib.java.io.TSerializable;
import org.teavm.classlib.java.lang.TCloneable;
import org.teavm.platform.metadata.ResourceArray;
import org.teavm.platform.metadata.ResourceMap;
import org.teavm.platform.metadata.StringResource;
public final class TLocale implements TCloneable, TSerializable {
private static TLocale defaultLocale;
public static final TLocale CANADA = new TLocale("en", "CA");
public static final TLocale CANADA_FRENCH = new TLocale("fr", "CA");
public static final TLocale CHINA = new TLocale("zh", "CN");
public static final TLocale CHINESE = new TLocale("zh", "");
public static final TLocale ENGLISH = new TLocale("en", "");
public static final TLocale FRANCE = new TLocale("fr", "FR");
public static final TLocale FRENCH = new TLocale("fr", "");
public static final TLocale GERMAN = new TLocale("de", "");
public static final TLocale GERMANY = new TLocale("de", "DE");
public static final TLocale ITALIAN = new TLocale("it", "");
public static final TLocale ITALY = new TLocale("it", "IT");
public static final TLocale JAPAN = new TLocale("ja", "JP");
public static final TLocale JAPANESE = new TLocale("ja", "");
public static final TLocale KOREA = new TLocale("ko", "KR");
public static final TLocale KOREAN = new TLocale("ko", "");
public static final TLocale PRC = new TLocale("zh", "CN");
public static final TLocale SIMPLIFIED_CHINESE = new TLocale("zh", "CN");
public static final TLocale TAIWAN = new TLocale("zh", "TW");
public static final TLocale TRADITIONAL_CHINESE = new TLocale("zh", "TW");
public static final TLocale UK = new TLocale("en", "GB");
public static final TLocale US = new TLocale("en", "US");
public static final TLocale ROOT = new TLocale("", "");
private static TLocale[] availableLocales;
static {
String localeName = CLDRHelper.getDefaultLocale().getValue();
int countryIndex = localeName.indexOf('_');
defaultLocale = new TLocale(localeName.substring(0, countryIndex), localeName.substring(countryIndex + 1), "");
}
private transient String countryCode;
private transient String languageCode;
private transient String variantCode;
public TLocale(String language) {
this(language, "", "");
}
public TLocale(String language, String country) {
this(language, country, "");
}
public TLocale(String language, String country, String variant) {
if (language == null || country == null || variant == null) {
throw new NullPointerException();
}
if (language.length() == 0 && country.length() == 0) {
languageCode = "";
countryCode = "";
variantCode = variant;
return;
}
languageCode = language;
countryCode = country;
variantCode = variant;
}
@Override
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
@Override
public boolean equals(Object object) {
if (object == this) {
return true;
}
if (object instanceof TLocale) {
TLocale o = (TLocale) object;
return languageCode.equals(o.languageCode) && countryCode.equals(o.countryCode)
&& variantCode.equals(o.variantCode);
}
return false;
}
public static TLocale[] getAvailableLocales() {
if (availableLocales == null) {
ResourceArray<StringResource> strings = CLDRHelper.getAvailableLocales();
availableLocales = new TLocale[strings.size()];
for (int i = 0; i < strings.size(); ++i) {
String string = strings.get(i).getValue();
int countryIndex = string.indexOf('-');
if (countryIndex > 0) {
availableLocales[i] = new TLocale(string.substring(0, countryIndex),
string.substring(countryIndex + 1));
} else {
availableLocales[i] = new TLocale(string);
}
}
}
return Arrays.copyOf(availableLocales, availableLocales.length);
}
public String getCountry() {
return countryCode;
}
public static TLocale getDefault() {
return defaultLocale;
}
public String getDisplayCountry() {
return getDisplayCountry(getDefault());
}
public String getDisplayCountry(TLocale locale) {
String result = getDisplayCountry(locale.getLanguage() + "-" + locale.getCountry(), countryCode);
if (result == null) {
result = getDisplayCountry(locale.getLanguage(), countryCode);
}
return result != null ? result : countryCode;
}
private static String getDisplayCountry(String localeName, String country) {
if (!CLDRHelper.getCountriesMap().has(localeName)) {
return null;
}
ResourceMap<StringResource> countries = CLDRHelper.getCountriesMap().get(localeName);
if (!countries.has(country)) {
return null;
}
return countries.get(country).getValue();
}
public String getDisplayLanguage() {
return getDisplayLanguage(getDefault());
}
public String getDisplayLanguage(TLocale locale) {
String result = getDisplayLanguage(locale.getLanguage() + "-" + locale.getCountry(), languageCode);
if (result == null) {
result = getDisplayLanguage(locale.getLanguage(), languageCode);
}
return result != null ? result : languageCode;
}
private static String getDisplayLanguage(String localeName, String language) {
if (!CLDRHelper.getLanguagesMap().has(localeName)) {
return null;
}
ResourceMap<StringResource> languages = CLDRHelper.getLanguagesMap().get(localeName);
if (!languages.has(language)) {
return null;
}
return languages.get(language).getValue();
}
public String getDisplayName() {
return getDisplayName(getDefault());
}
public String getDisplayName(TLocale locale) {
int count = 0;
StringBuilder buffer = new StringBuilder();
if (languageCode.length() > 0) {
buffer.append(getDisplayLanguage(locale));
count++;
}
if (countryCode.length() > 0) {
if (count == 1) {
buffer.append(" (");
}
buffer.append(getDisplayCountry(locale));
count++;
}
if (variantCode.length() > 0) {
if (count == 1) {
buffer.append(" (");
} else if (count == 2) {
buffer.append(",");
}
buffer.append(getDisplayVariant(locale));
count++;
}
if (count > 1) {
buffer.append(")");
}
return buffer.toString();
}
public String getDisplayVariant() {
return getDisplayVariant(getDefault());
}
public String getDisplayVariant(TLocale locale) {
// TODO: use CLDR
return locale.getVariant();
}
public String getLanguage() {
return languageCode;
}
public String getVariant() {
return variantCode;
}
@Override
public int hashCode() {
return countryCode.hashCode() + languageCode.hashCode() + variantCode.hashCode();
}
public static void setDefault(TLocale locale) {
if (locale != null) {
defaultLocale = locale;
} else {
throw new NullPointerException();
}
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(languageCode);
if (countryCode.length() > 0) {
result.append('_');
result.append(countryCode);
}
if (variantCode.length() > 0 && result.length() > 0) {
if (0 == countryCode.length()) {
result.append("__");
} else {
result.append('_');
}
result.append(variantCode);
}
return result.toString();
}
}
| |
/*
* 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/iot/v1/device_manager.proto
package com.google.cloud.iot.v1;
/**
*
*
* <pre>
* Request for `GetDeviceRegistry`.
* </pre>
*
* Protobuf type {@code google.cloud.iot.v1.GetDeviceRegistryRequest}
*/
public final class GetDeviceRegistryRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.iot.v1.GetDeviceRegistryRequest)
GetDeviceRegistryRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use GetDeviceRegistryRequest.newBuilder() to construct.
private GetDeviceRegistryRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GetDeviceRegistryRequest() {
name_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new GetDeviceRegistryRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private GetDeviceRegistryRequest(
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 10:
{
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
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.iot.v1.DeviceManagerProto
.internal_static_google_cloud_iot_v1_GetDeviceRegistryRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.iot.v1.DeviceManagerProto
.internal_static_google_cloud_iot_v1_GetDeviceRegistryRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.iot.v1.GetDeviceRegistryRequest.class,
com.google.cloud.iot.v1.GetDeviceRegistryRequest.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object name_;
/**
*
*
* <pre>
* Required. The name of the device registry. For example,
* `projects/example-project/locations/us-central1/registries/my-registry`.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
@java.lang.Override
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The name of the device registry. For example,
* `projects/example-project/locations/us-central1/registries/my-registry`.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
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 (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
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.iot.v1.GetDeviceRegistryRequest)) {
return super.equals(obj);
}
com.google.cloud.iot.v1.GetDeviceRegistryRequest other =
(com.google.cloud.iot.v1.GetDeviceRegistryRequest) obj;
if (!getName().equals(other.getName())) 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) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.iot.v1.GetDeviceRegistryRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iot.v1.GetDeviceRegistryRequest 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.iot.v1.GetDeviceRegistryRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iot.v1.GetDeviceRegistryRequest 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.iot.v1.GetDeviceRegistryRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iot.v1.GetDeviceRegistryRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iot.v1.GetDeviceRegistryRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.iot.v1.GetDeviceRegistryRequest 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.iot.v1.GetDeviceRegistryRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.iot.v1.GetDeviceRegistryRequest 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.iot.v1.GetDeviceRegistryRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.iot.v1.GetDeviceRegistryRequest 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.iot.v1.GetDeviceRegistryRequest 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>
* Request for `GetDeviceRegistry`.
* </pre>
*
* Protobuf type {@code google.cloud.iot.v1.GetDeviceRegistryRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.iot.v1.GetDeviceRegistryRequest)
com.google.cloud.iot.v1.GetDeviceRegistryRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.iot.v1.DeviceManagerProto
.internal_static_google_cloud_iot_v1_GetDeviceRegistryRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.iot.v1.DeviceManagerProto
.internal_static_google_cloud_iot_v1_GetDeviceRegistryRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.iot.v1.GetDeviceRegistryRequest.class,
com.google.cloud.iot.v1.GetDeviceRegistryRequest.Builder.class);
}
// Construct using com.google.cloud.iot.v1.GetDeviceRegistryRequest.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();
name_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.iot.v1.DeviceManagerProto
.internal_static_google_cloud_iot_v1_GetDeviceRegistryRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.iot.v1.GetDeviceRegistryRequest getDefaultInstanceForType() {
return com.google.cloud.iot.v1.GetDeviceRegistryRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.iot.v1.GetDeviceRegistryRequest build() {
com.google.cloud.iot.v1.GetDeviceRegistryRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.iot.v1.GetDeviceRegistryRequest buildPartial() {
com.google.cloud.iot.v1.GetDeviceRegistryRequest result =
new com.google.cloud.iot.v1.GetDeviceRegistryRequest(this);
result.name_ = name_;
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.iot.v1.GetDeviceRegistryRequest) {
return mergeFrom((com.google.cloud.iot.v1.GetDeviceRegistryRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.iot.v1.GetDeviceRegistryRequest other) {
if (other == com.google.cloud.iot.v1.GetDeviceRegistryRequest.getDefaultInstance())
return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
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.iot.v1.GetDeviceRegistryRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.iot.v1.GetDeviceRegistryRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object name_ = "";
/**
*
*
* <pre>
* Required. The name of the device registry. For example,
* `projects/example-project/locations/us-central1/registries/my-registry`.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the device registry. For example,
* `projects/example-project/locations/us-central1/registries/my-registry`.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the device registry. For example,
* `projects/example-project/locations/us-central1/registries/my-registry`.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the device registry. For example,
* `projects/example-project/locations/us-central1/registries/my-registry`.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the device registry. For example,
* `projects/example-project/locations/us-central1/registries/my-registry`.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
@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.iot.v1.GetDeviceRegistryRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.iot.v1.GetDeviceRegistryRequest)
private static final com.google.cloud.iot.v1.GetDeviceRegistryRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.iot.v1.GetDeviceRegistryRequest();
}
public static com.google.cloud.iot.v1.GetDeviceRegistryRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GetDeviceRegistryRequest> PARSER =
new com.google.protobuf.AbstractParser<GetDeviceRegistryRequest>() {
@java.lang.Override
public GetDeviceRegistryRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new GetDeviceRegistryRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<GetDeviceRegistryRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GetDeviceRegistryRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.iot.v1.GetDeviceRegistryRequest 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.kafka.common.security.authenticator;
import org.apache.kafka.common.config.SaslConfigs;
import org.apache.kafka.common.config.internals.BrokerSecurityConfigs;
import org.apache.kafka.common.errors.SaslAuthenticationException;
import org.apache.kafka.common.network.CertStores;
import org.apache.kafka.common.network.ChannelBuilder;
import org.apache.kafka.common.network.ChannelBuilders;
import org.apache.kafka.common.network.ChannelState;
import org.apache.kafka.common.network.ListenerName;
import org.apache.kafka.common.network.NetworkTestUtils;
import org.apache.kafka.common.network.NioEchoServer;
import org.apache.kafka.common.network.Selector;
import org.apache.kafka.common.security.JaasContext;
import org.apache.kafka.common.security.TestSecurityConfig;
import org.apache.kafka.common.security.auth.SecurityProtocol;
import org.apache.kafka.common.utils.MockTime;
import org.apache.kafka.test.TestUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@RunWith(value = Parameterized.class)
public class SaslAuthenticatorFailureDelayTest {
private static final int BUFFER_SIZE = 4 * 1024;
private static MockTime time = new MockTime(50);
private NioEchoServer server;
private Selector selector;
private ChannelBuilder channelBuilder;
private CertStores serverCertStores;
private CertStores clientCertStores;
private Map<String, Object> saslClientConfigs;
private Map<String, Object> saslServerConfigs;
private CredentialCache credentialCache;
private long startTimeMs;
private final int failedAuthenticationDelayMs;
public SaslAuthenticatorFailureDelayTest(int failedAuthenticationDelayMs) {
this.failedAuthenticationDelayMs = failedAuthenticationDelayMs;
}
@Parameterized.Parameters(name = "failedAuthenticationDelayMs={0}")
public static Collection<Object[]> data() {
List<Object[]> values = new ArrayList<>();
values.add(new Object[]{0});
values.add(new Object[]{200});
return values;
}
@Before
public void setup() throws Exception {
LoginManager.closeAll();
serverCertStores = new CertStores(true, "localhost");
clientCertStores = new CertStores(false, "localhost");
saslServerConfigs = serverCertStores.getTrustingConfig(clientCertStores);
saslClientConfigs = clientCertStores.getTrustingConfig(serverCertStores);
credentialCache = new CredentialCache();
SaslAuthenticatorTest.TestLogin.loginCount.set(0);
startTimeMs = time.milliseconds();
}
@After
public void teardown() throws Exception {
long now = time.milliseconds();
if (server != null)
this.server.close();
if (selector != null)
this.selector.close();
if (failedAuthenticationDelayMs != -1)
assertTrue("timeSpent: " + (now - startTimeMs), now - startTimeMs >= failedAuthenticationDelayMs);
}
/**
* Tests that SASL/PLAIN clients with invalid password fail authentication.
*/
@Test
public void testInvalidPasswordSaslPlain() throws Exception {
String node = "0";
SecurityProtocol securityProtocol = SecurityProtocol.SASL_SSL;
TestJaasConfig jaasConfig = configureMechanisms("PLAIN", Arrays.asList("PLAIN"));
jaasConfig.setClientOptions("PLAIN", TestJaasConfig.USERNAME, "invalidpassword");
server = createEchoServer(securityProtocol);
createAndCheckClientAuthenticationFailure(securityProtocol, node, "PLAIN",
"Authentication failed: Invalid username or password");
server.verifyAuthenticationMetrics(0, 1);
}
/**
* Tests client connection close before response for authentication failure is sent.
*/
@Test
public void testClientConnectionClose() throws Exception {
String node = "0";
SecurityProtocol securityProtocol = SecurityProtocol.SASL_SSL;
TestJaasConfig jaasConfig = configureMechanisms("PLAIN", Arrays.asList("PLAIN"));
jaasConfig.setClientOptions("PLAIN", TestJaasConfig.USERNAME, "invalidpassword");
server = createEchoServer(securityProtocol);
createClientConnection(securityProtocol, node);
Map<?, ?> delayedClosingChannels = NetworkTestUtils.delayedClosingChannels(server.selector());
// Wait until server has established connection with client and has processed the auth failure
TestUtils.waitForCondition(() -> {
poll(selector);
return !server.selector().channels().isEmpty();
}, "Timeout waiting for connection");
TestUtils.waitForCondition(() -> {
poll(selector);
return failedAuthenticationDelayMs == 0 || !delayedClosingChannels.isEmpty();
}, "Timeout waiting for auth failure");
selector.close();
selector = null;
// Now that client connection is closed, wait until server notices the disconnection and removes it from the
// list of connected channels and from delayed response for auth failure
TestUtils.waitForCondition(() -> failedAuthenticationDelayMs == 0 || delayedClosingChannels.isEmpty(),
"Timeout waiting for delayed response remove");
TestUtils.waitForCondition(() -> server.selector().channels().isEmpty(),
"Timeout waiting for connection close");
// Try forcing completion of delayed channel close
TestUtils.waitForCondition(() -> time.milliseconds() > startTimeMs + failedAuthenticationDelayMs + 1,
"Timeout when waiting for auth failure response timeout to elapse");
NetworkTestUtils.completeDelayedChannelClose(server.selector(), time.nanoseconds());
}
private void poll(Selector selector) {
try {
selector.poll(50);
} catch (IOException e) {
Assert.fail("Caught unexpected exception " + e);
}
}
private TestJaasConfig configureMechanisms(String clientMechanism, List<String> serverMechanisms) {
saslClientConfigs.put(SaslConfigs.SASL_MECHANISM, clientMechanism);
saslServerConfigs.put(BrokerSecurityConfigs.SASL_ENABLED_MECHANISMS_CONFIG, serverMechanisms);
if (serverMechanisms.contains("DIGEST-MD5")) {
saslServerConfigs.put("digest-md5." + BrokerSecurityConfigs.SASL_SERVER_CALLBACK_HANDLER_CLASS,
TestDigestLoginModule.DigestServerCallbackHandler.class.getName());
}
return TestJaasConfig.createConfiguration(clientMechanism, serverMechanisms);
}
private void createSelector(SecurityProtocol securityProtocol, Map<String, Object> clientConfigs) {
if (selector != null) {
selector.close();
selector = null;
}
String saslMechanism = (String) saslClientConfigs.get(SaslConfigs.SASL_MECHANISM);
this.channelBuilder = ChannelBuilders.clientChannelBuilder(securityProtocol, JaasContext.Type.CLIENT,
new TestSecurityConfig(clientConfigs), null, saslMechanism, true);
this.selector = NetworkTestUtils.createSelector(channelBuilder, time);
}
private NioEchoServer createEchoServer(SecurityProtocol securityProtocol) throws Exception {
return createEchoServer(ListenerName.forSecurityProtocol(securityProtocol), securityProtocol);
}
private NioEchoServer createEchoServer(ListenerName listenerName, SecurityProtocol securityProtocol) throws Exception {
if (failedAuthenticationDelayMs != -1)
return NetworkTestUtils.createEchoServer(listenerName, securityProtocol,
new TestSecurityConfig(saslServerConfigs), credentialCache, failedAuthenticationDelayMs, time);
else
return NetworkTestUtils.createEchoServer(listenerName, securityProtocol,
new TestSecurityConfig(saslServerConfigs), credentialCache, time);
}
private void createClientConnection(SecurityProtocol securityProtocol, String node) throws Exception {
createSelector(securityProtocol, saslClientConfigs);
InetSocketAddress addr = new InetSocketAddress("127.0.0.1", server.port());
selector.connect(node, addr, BUFFER_SIZE, BUFFER_SIZE);
}
private void createAndCheckClientAuthenticationFailure(SecurityProtocol securityProtocol, String node,
String mechanism, String expectedErrorMessage) throws Exception {
ChannelState finalState = createAndCheckClientConnectionFailure(securityProtocol, node);
Exception exception = finalState.exception();
assertTrue("Invalid exception class " + exception.getClass(), exception instanceof SaslAuthenticationException);
if (expectedErrorMessage == null)
expectedErrorMessage = "Authentication failed due to invalid credentials with SASL mechanism " + mechanism;
assertEquals(expectedErrorMessage, exception.getMessage());
}
private ChannelState createAndCheckClientConnectionFailure(SecurityProtocol securityProtocol, String node)
throws Exception {
createClientConnection(securityProtocol, node);
ChannelState finalState = NetworkTestUtils.waitForChannelClose(selector, node,
ChannelState.State.AUTHENTICATION_FAILED, time);
selector.close();
selector = null;
return finalState;
}
}
| |
package org.basex.gui.layout;
import static org.basex.core.Text.*;
import static org.basex.gui.layout.BaseXKeys.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.*;
import org.basex.core.*;
import org.basex.gui.*;
import org.basex.gui.GUIConstants.*;
import org.basex.gui.dialog.*;
import org.basex.gui.listener.*;
import org.basex.util.*;
/**
* This superclass in inherited by all dialog windows.
*
* @author BaseX Team 2005-22, BSD License
* @author Christian Gruen
*/
public abstract class BaseXDialog extends JDialog implements BaseXWindow {
/** Reference to the main window. */
public GUI gui;
/** Used mnemonics. */
final StringBuilder mnem = new StringBuilder();
/** Remembers if the window was correctly closed. */
protected boolean ok;
/** Reference to the root panel. */
protected BaseXBack panel;
/** Key listener, triggering an action with each click. */
public final KeyListener keys = (KeyReleasedListener) e -> {
// don't trigger any action for modifier keys
if(!modifier(e) && e.getKeyChar() != KeyEvent.CHAR_UNDEFINED) action(e.getSource());
};
/**
* Constructor, called from a dialog window.
* @param dialog calling dialog
* @param title dialog title
*/
protected BaseXDialog(final BaseXDialog dialog, final String title) {
super(dialog, title, true);
gui = dialog.gui;
init();
}
/**
* Constructor, called from the main window.
* @param gui reference to the main window
* @param title dialog title
*/
protected BaseXDialog(final GUI gui, final String title) {
this(gui, title, true);
}
/**
* Constructor, called from the main window.
* @param gui reference to the main window
* @param title dialog title
* @param modal modal flag
*/
protected BaseXDialog(final GUI gui, final String title, final boolean modal) {
super(gui, title, modal);
this.gui = gui;
init();
}
/**
* Initializes the dialog.
*/
private void init() {
panel = new BaseXBack(new BorderLayout()).border(10, 10, 10, 10);
add(panel, BorderLayout.CENTER);
setResizable(false);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
cancel();
}
});
}
/**
* Sets a component at the specified {@link BorderLayout} position.
* @param comp component to be added
* @param pos layout position
*/
protected final void set(final Component comp, final String pos) {
panel.add(comp, pos);
}
/**
* Finalizes the dialog layout and sets it visible.
*/
protected final void finish() {
pack();
setMinimumSize(getPreferredSize());
setLocationRelativeTo(gui);
setVisible(true);
}
/**
* Reacts on user input; can be overwritten.
* @param source source
*/
@SuppressWarnings("unused")
public void action(final Object source) { }
/**
* Cancels the dialog; can be overwritten.
*/
public void cancel() {
ok = false;
dispose();
}
/**
* Closes the dialog and stores the location of the dialog window; can be overwritten.
*/
public void close() {
ok = true;
dispose();
}
@Override
public void dispose() {
// modal dialog: save options, remove GUI reference
if(gui != null && modal()) {
gui.saveOptions();
gui = null;
}
super.dispose();
}
/**
* Indicates if this is a modal dialog.
* @return result of check
*/
public final boolean modal() {
return getModalityType() != ModalityType.MODELESS;
}
/**
* States if the dialog window was confirmed or canceled.
* @return true when dialog was confirmed
*/
public final boolean ok() {
return ok;
}
/**
* Creates a OK and CANCEL button.
* @return button list
*/
protected final BaseXBack okCancel() {
return newButtons(B_OK, B_CANCEL);
}
/**
* Creates a new button list.
* @param buttons button names or objects
* @return button list
*/
public final BaseXBack newButtons(final Object... buttons) {
// horizontal/vertical layout
final BaseXBack pnl = new BaseXBack(false).
border(12, 0, 0, 0).layout(new TableLayout(1, buttons.length, 8, 0));
for(final Object obj : buttons) {
pnl.add(obj instanceof BaseXButton ? (BaseXButton) obj :
new BaseXButton(this, obj.toString()));
}
final BaseXBack but = new BaseXBack(false).layout(new BorderLayout());
but.add(pnl, BorderLayout.EAST);
return but;
}
/**
* Enables/disables a button in the specified panel.
* @param panel button panel
* @param label button label
* @param enabled enabled/disabled
*/
protected static void enableOK(final JComponent panel, final String label,
final boolean enabled) {
for(final Component c : panel.getComponents()) {
if(c instanceof BaseXButton) {
final BaseXButton b = (BaseXButton) c;
if(b.getText().equals(label)) b.setEnabled(enabled);
} else if(c instanceof JComponent) {
enableOK((JComponent) c, label, enabled);
}
}
}
/**
* Static yes/no/cancel dialog. Returns {@code null} if the dialog was canceled.
* @param gui parent reference
* @param text text
* @param buttons additional buttons
* @return chosen action ({@link Text#B_YES}, {@link Text#B_NO}, {@link Text#B_CANCEL})
*/
public static String yesNoCancel(final GUI gui, final String text, final String... buttons) {
return new DialogMessage(gui, text.trim(), Msg.YESNOCANCEL, buttons).action();
}
/**
* Static yes/no dialog.
* @param gui parent reference
* @param text text
* @return {@code true} if dialog was confirmed
*/
public static boolean confirm(final GUI gui, final String text) {
return B_YES.equals(new DialogMessage(gui, text.trim(), Msg.QUESTION).action());
}
/**
* Static error dialog.
* @param gui parent reference
* @param text text
*/
public static void error(final GUI gui, final String text) {
new DialogMessage(gui, text.trim(), Msg.ERROR);
}
/**
* Browses the specified url.
* @param gui parent reference
* @param url url to be browsed
*/
public static void browse(final GUI gui, final String url) {
try {
Desktop.getDesktop().browse(new URI(url));
} catch(final Exception ex) {
Util.debug(ex);
error(gui, Util.info(H_BROWSER_ERROR_X, PUBLIC_URL));
}
}
@Override
public GUI gui() {
return gui;
}
@Override
public BaseXDialog dialog() {
return this;
}
@Override
public BaseXDialog component() {
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.mrql;
import org.apache.mrql.gen.VariableLeaf;
import java.util.ArrayList;
import java.io.FileInputStream;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
/** MRQL configuration parameters */
final public class Config {
// true for using Hadoop HDFS file-system
public static boolean hadoop_mode = false;
// true for local execution (one node)
public static boolean local_mode = false;
// true for local execution (one node)
public static boolean distributed_mode = false;
// true for Hadoop map-reduce mode
public static boolean map_reduce_mode = false;
// true, for BSP mode using Hama
public static boolean bsp_mode = false;
// true, for Spark mode
public static boolean spark_mode = false;
// true, for Flink mode
public static boolean flink_mode = false;
// true, for Storm mode
public static boolean storm_mode = false;
// if true, it process the input interactively
public static boolean interactive = true;
// compile the MR functional arguments to Java bytecode at run-time
// (each task-tracker repeats the compilation at the MR setup time)
public static boolean compile_functional_arguments = true;
// if true, generates info about all compilation and optimization steps
public static boolean trace = false;
// number of worker nodes
public static int nodes = 2;
// true, to disable mapJoin
public static boolean noMapJoin = false;
// max distributed cache size for MapJoin (fragment-replicate join) in MBs
public static int mapjoin_size = 50;
// max entries for in-mapper combiner before they are flushed out
public static int map_cache_size = 100000;
// max number of bag elements to print
public static int max_bag_size_print = 20;
// max size of materialized vector before is spilled to a file:
public static long max_materialized_bag = 500000L;
// max number of incoming messages before a sub-sync()
public static int bsp_msg_size = Integer.MAX_VALUE;
// number of elements per mapper to process the range min...max
public static long range_split_size = -1;
// max number of streams to merge simultaneously
public static int max_merged_streams = 100;
// the directory for temporary files and spilled bags
public static String tmpDirectory = "/tmp/mrql_"+System.getProperty("user.name");
// true, if we want to derive a combine function for MapReduce
public static boolean use_combiner = true;
// true, if we can use the rule that fuses a groupBy with a join over the same key
public static boolean groupJoinOpt = true;
// true, if we can use the rule that converts a self-join into a simple mapreduce
public static boolean selfJoinOpt = true;
// true for run-time trace of plans
public static boolean trace_execution = false;
// true for extensive run-time trace of expressions & plans
public static boolean trace_exp_execution = false;
// true if you don't want to print statistics
public static boolean quiet_execution = false;
// true if this is during testing
public static boolean testing = false;
// true to display INFO log messages
public static boolean info = false;
// for streaming, stream_window > 0 is the stream window duration in milliseconds
public static int stream_window = 0;
public static int stream_tries = 100;
// if true and stream_window > 0, then incremental streaming
public static boolean incremental = false;
// if true, generate provenance tracing
public static boolean lineage = false;
public static boolean debug = false;
/** store the configuration parameters */
public static void write ( Configuration conf ) {
conf.setBoolean("mrql.hadoop.mode",hadoop_mode);
conf.setBoolean("mrql.local.mode",local_mode);
conf.setBoolean("mrql.distributed.mode",distributed_mode);
conf.setBoolean("mrql.map.reduce.mode",map_reduce_mode);
conf.setBoolean("mrql.bsp.mode",bsp_mode);
conf.setBoolean("mrql.spark.mode",spark_mode);
conf.setBoolean("mrql.flink.mode",flink_mode);
conf.setBoolean("mrql.interactive",interactive);
conf.setBoolean("mrql.compile.functional.arguments",compile_functional_arguments);
conf.setBoolean("mrql.trace",trace);
conf.setInt("mrql.nodes",nodes);
conf.setInt("mrql.mapjoin.size",mapjoin_size);
conf.setInt("mrql.in.mapper.size",map_cache_size);
conf.setInt("mrql.max.bag.size.print",max_bag_size_print);
conf.setLong("mrql.max.materialized.bag",max_materialized_bag);
conf.setInt("mrql.bsp.msg.size",bsp_msg_size);
conf.setLong("mrql.range.split.size",range_split_size);
conf.setInt("mrql.max.merged.streams",max_merged_streams);
conf.set("mrql.tmp.directory",tmpDirectory);
conf.setBoolean("mrql.use.combiner",use_combiner);
conf.setBoolean("mrql.group.join.opt",groupJoinOpt);
conf.setBoolean("mrql.self.join.opt",selfJoinOpt);
conf.setBoolean("mrql.trace.execution",trace_execution);
conf.setBoolean("mrql.trace.exp.execution",trace_exp_execution);
conf.setBoolean("mrql.quiet.execution",quiet_execution);
conf.setBoolean("mrql.testing",testing);
conf.setBoolean("mrql.info",info);
conf.setInt("mrql.stream.window",stream_window);
conf.setBoolean("mrql.incremental",incremental);
conf.setBoolean("mrql.lineage",lineage);
conf.setBoolean("mrql.debug",debug);
}
/** load the configuration parameters */
public static void read ( Configuration conf ) {
hadoop_mode = conf.getBoolean("mrql.hadoop.mode",hadoop_mode);
local_mode = conf.getBoolean("mrql.local.mode",local_mode);
distributed_mode = conf.getBoolean("mrql.distributed.mode",distributed_mode);
map_reduce_mode = conf.getBoolean("mrql.map.reduce.mode",map_reduce_mode);
bsp_mode = conf.getBoolean("mrql.bsp.mode",bsp_mode);
spark_mode = conf.getBoolean("mrql.spark.mode",spark_mode);
flink_mode = conf.getBoolean("mrql.flink.mode",flink_mode);
interactive = conf.getBoolean("mrql.interactive",interactive);
compile_functional_arguments = conf.getBoolean("mrql.compile.functional.arguments",compile_functional_arguments);
trace = conf.getBoolean("mrql.trace",trace);
nodes = conf.getInt("mrql.nodes",nodes);
mapjoin_size = conf.getInt("mrql.mapjoin.size",mapjoin_size);
map_cache_size = conf.getInt("mrql.in.mapper.size",map_cache_size);
max_bag_size_print = conf.getInt("mrql.max.bag.size.print",max_bag_size_print);
max_materialized_bag = conf.getLong("mrql.max.materialized.bag",max_materialized_bag);
bsp_msg_size = conf.getInt("mrql.bsp.msg.size",bsp_msg_size);
range_split_size = conf.getLong("mrql.range.split.size",range_split_size);
max_merged_streams = conf.getInt("mrql.max.merged.streams",max_merged_streams);
tmpDirectory = conf.get("mrql.tmp.directory");
use_combiner = conf.getBoolean("mrql.use.combiner",use_combiner);
groupJoinOpt = conf.getBoolean("mrql.group.join.opt",groupJoinOpt);
selfJoinOpt = conf.getBoolean("mrql.self.join.opt",selfJoinOpt);
trace_execution = conf.getBoolean("mrql.trace.execution",trace_execution);
trace_exp_execution = conf.getBoolean("mrql.trace.exp.execution",trace_exp_execution);
quiet_execution = conf.getBoolean("mrql.quiet.execution",quiet_execution);
testing = conf.getBoolean("mrql.testing",testing);
info = conf.getBoolean("mrql.info",info);
stream_window = conf.getInt("mrql.stream.window",stream_window);
incremental = conf.getBoolean("mrql.incremental",incremental);
lineage = conf.getBoolean("mrql.lineage",lineage);
debug = conf.getBoolean("mrql.debug",debug);
}
public static ArrayList<String> extra_args = new ArrayList<String>();
/** read configuration parameters from the Main args */
public static Bag parse_args ( String args[], Configuration conf ) throws Exception {
int i = 0;
int iargs = 0;
extra_args = new ArrayList<String>();
ClassImporter.load_classes();
interactive = true;
while (i < args.length) {
if (args[i].equals("-local")) {
local_mode = true;
i++;
} else if (args[i].equals("-dist")) {
distributed_mode = true;
i++;
} else if (args[i].equals("-reducers")) {
if (++i >= args.length)
throw new Error("Expected number of reductions");
nodes = Integer.parseInt(args[i]);
i++;
} else if (args[i].equals("-bsp")) {
bsp_mode = true;
i++;
} else if (args[i].equals("-spark")) {
spark_mode = true;
i++;
} else if (args[i].equals("-flink")) {
flink_mode = true;
i++;
}else if (args[i].equals("-storm")) {
storm_mode = true;
i++;
}
else if (args[i].equals("-bsp_tasks")) {
if (++i >= args.length && Integer.parseInt(args[i]) < 1)
throw new Error("Expected max number of bsp tasks > 1");
nodes = Integer.parseInt(args[i]);
i++;
} else if (args[i].equals("-nodes")) {
if (++i >= args.length && Integer.parseInt(args[i]) < 1)
throw new Error("Expected number of nodes > 1");
nodes = Integer.parseInt(args[i]);
i++;
} else if (args[i].equals("-bsp_msg_size")) {
if (++i >= args.length && Integer.parseInt(args[i]) < 10000)
throw new Error("Expected max number of bsp messages before subsync() > 10000");
bsp_msg_size = Integer.parseInt(args[i]);
i++;
} else if (args[i].equals("-mapjoin_size")) {
if (++i >= args.length)
throw new Error("Expected number of MBs");
mapjoin_size = Integer.parseInt(args[i]);
i++;
} else if (args[i].equals("-cache_size")) {
if (++i >= args.length)
throw new Error("Expected number of entries");
map_cache_size = Integer.parseInt(args[i]);
i++;
} else if (args[i].equals("-tmp")) {
if (++i >= args.length)
throw new Error("Expected a temporary directory");
tmpDirectory = args[i];
i++;
} else if (args[i].equals("-bag_size")) {
if (++i >= args.length && Integer.parseInt(args[i]) < 10000)
throw new Error("Expected max size of materialized bag > 10000");
max_materialized_bag = Long.parseLong(args[i]);
i++;
} else if (args[i].equals("-bag_print")) {
if (++i >= args.length)
throw new Error("Expected number of bag elements to print");
max_bag_size_print = Integer.parseInt(args[i]);
i++;
} else if (args[i].equals("-split_size")) {
if (++i >= args.length)
throw new Error("Expected a split size");
range_split_size = Long.parseLong(args[i]);
i++;
} else if (args[i].equals("-max_merged")) {
if (++i >= args.length)
throw new Error("Expected a max number of merged streams");
max_merged_streams = Integer.parseInt(args[i]);
i++;
} else if (args[i].equals("-trace")) {
trace = true;
i++;
} else if (args[i].equals("-C")) {
compile_functional_arguments = true;
i++;
} else if (args[i].equals("-NC")) {
compile_functional_arguments = false;
i++;
} else if (args[i].equals("-P")) {
trace_execution = true;
i++;
} else if (args[i].equals("-quiet")) {
quiet_execution = true;
i++;
} else if (args[i].equals("-info")) {
info = true;
i++;
} else if (args[i].equals("-trace_execution")) {
trace_execution = true;
trace_exp_execution = true;
compile_functional_arguments = false;
i++;
} else if (args[i].equals("-methods")) {
System.out.print("\nImported methods: ");
ClassImporter.print_methods();
System.out.println();
System.out.print("\nAggregations:");
Translator.print_aggregates();
System.out.println();
i++;
} else if (args[i].equals("-stream")) {
if (++i >= args.length)
throw new Error("Expected a stream window duration");
stream_window = Integer.parseInt(args[i]);
i++;
} else if (args[i].equals("-stream_tries")) {
if (++i >= args.length)
throw new Error("Expected a stream window tries");
stream_tries = Integer.parseInt(args[i]);
i++;
} else if (args[i].charAt(0) == '-')
throw new Error("Unknown MRQL parameter: "+args[i]);
else {
if (interactive) {
Main.query_file = args[i++];
interactive = false;
} else extra_args.add(args[i++]);
}
};
if (hadoop_mode)
write(conf);
Plan.conf = conf;
Bag b = new Bag();
for ( String s: extra_args )
b.add(new MR_string(s));
Interpreter.new_distributed_binding(new VariableLeaf("args").value(),b);
return b;
}
}
| |
/**
* Copyright (C) 2015 The Authors.
*/
package dk.itu.kelvin.util;
// General utilities
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
// I/O utilities
import java.io.Serializable;
// Math
import dk.itu.kelvin.math.Epsilon;
import dk.itu.kelvin.math.Geometry;
// Functional utilities
import dk.itu.kelvin.util.function.Filter;
/**
* Rectangle tree class.
*
* @see <a href="http://en.wikipedia.org/wiki/R-tree">
* http://en.wikipedia.org/wiki/R-tree</a>
*
* @see <a href="http://www-db.deis.unibo.it/courses/SI-LS/papers/Gut84.pdf">
* http://www-db.deis.unibo.it/courses/SI-LS/papers/Gut84.pdf</a>
*
* @param <E> The type of elements stored within the rectangle tree.
*/
public class RectangleTree<E extends RectangleTree.Index>
implements SpatialIndex<E> {
/**
* UID for identifying serialized objects.
*/
private static final long serialVersionUID = 848;
/**
* The maximum size of rectangle pages.
*/
private static final int PAGE_MAXIMUM = 4096;
/**
* The minimum size of rectangle pages.
*/
private static final int PAGE_MINIMUM = PAGE_MAXIMUM / 2;
/**
* The maximum size of rectangle buckets.
*/
private static final int BUCKET_MAXIMUM = 512;
/**
* The minimum size of rectangle buckets.
*/
private static final int BUCKET_MINIMUM = BUCKET_MAXIMUM / 2;
/**
* The size of the rectangle tree.
*/
private int size;
/**
* The root node of the rectangle tree.
*/
private Node<E> root;
/**
* Initialize a new rectangle tree bulk-loaded with the specified list of
* elements.
*
* @param elements The elements to add to the tree.
*/
public RectangleTree(final Collection<E> elements) {
this.root = this.partition(new ArrayList<>(elements));
this.size = elements.size();
}
/**
* Get the size of the rectangle tree.
*
* @return The size of the rectangle tree.
*/
public final int size() {
return this.size;
}
/**
* Check if the rectangle tree is empty.
*
* @return A boolean indicating whether or not the rectangle tree is empty.
*/
public final boolean isEmpty() {
return this.size == 0;
}
/**
* Check if the rectangle tree contains the specified element.
*
* @param element The element to search for.
* @return A boolean indicating whether or not the rectangle tree
* contains the specified element.
*/
public final boolean contains(final E element) {
if (this.root == null || element == null) {
return false;
}
return this.root.contains(element);
}
/**
* Find all elements within the range of the specified bounds.
*
* @param bounds The bounds to search for elements within.
* @return A list of elements contained within the range of the
* specified bounds.
*/
public final List<E> range(final Bounds bounds) {
if (this.root == null || bounds == null) {
return null;
}
return this.range(bounds, (element) -> {
return true;
});
}
/**
* Find all elements included in the filter and within the range of the
* specified bounds.
*
* @param bounds The bounds to search for elements within.
* @param filter The filter to apply to the range search.
* @return A list of elements contained within the range of the
* specified bounds.
*/
public final List<E> range(final Bounds bounds, final Filter<E> filter) {
if (bounds == null || filter == null) {
return null;
}
return this.root.range(bounds, filter);
}
/**
* Find the element closest to the specified point.
*
* @param point The point to look for elements near.
* @return The element closest to the specified point.
*/
public final E nearest(final Point point) {
if (point == null) {
return null;
}
return this.nearest(point, (element) -> {
return true;
});
}
/**
* Find the element included in the filter closest to the specified point.
*
* @param point The point to look for elements near.
* @param filter The filter to apply to the search.
* @return The element closest to the specified point.
*/
public final E nearest(final Point point, final Filter<E> filter) {
if (this.root == null || point == null || filter == null) {
return null;
}
return this.root.nearest(point, filter);
}
/**
* Partition the specified list of elements using the Sort-Tile-Recursive
* (STR) algorithm.
*
* @see <a href="http://www.dtic.mil/dtic/tr/fulltext/u2/a324493.pdf">
* http://www.dtic.mil/dtic/tr/fulltext/u2/a324493.pdf</a>
*
* @param elements The elements to partition.
* @return A partitioned {@link Node} instance.
*/
private Node<E> partition(final List<E> elements) {
if (elements == null || elements.isEmpty()) {
return null;
}
if (elements.size() <= BUCKET_MAXIMUM) {
return new Bucket<E>(elements);
}
Collections.sort(elements, (a, b) -> {
return Double.compare(
a.minX() - ((a.maxX() - a.minX()) / 2),
b.minX() - ((b.maxX() - b.minX()) / 2)
);
});
// Compute the number of leaves.
int l = (int) Math.ceil(elements.size() / (double) BUCKET_MAXIMUM);
// Compute the number of slices.
int s = (int) Math.ceil(Math.sqrt(l));
for (int i = 0; i < s; i++) {
int slice = s * BUCKET_MAXIMUM;
int start = i * slice;
int end = start + slice;
if (start > elements.size()) {
break;
}
if (end > elements.size()) {
end = elements.size();
}
Collections.sort(elements.subList(start, end), (a, b) -> {
return Double.compare(
a.minY() - ((a.maxY() - a.minY()) / 2),
b.minY() - ((b.maxY() - b.minY()) / 2)
);
});
}
// Can the elements fit on a single page?
boolean singlePage = l <= PAGE_MAXIMUM;
// Compute the number of elements per page.
int n = (singlePage) ? l : (int) Math.ceil(l / (double) PAGE_MAXIMUM);
List<Node<E>> nodes = new ArrayList<>();
for (int i = 0; i < n; i++) {
int start;
int end;
if (singlePage) {
start = i * BUCKET_MAXIMUM;
end = start + BUCKET_MAXIMUM;
}
else {
start = i * BUCKET_MAXIMUM * PAGE_MAXIMUM;
end = start + i * BUCKET_MAXIMUM * PAGE_MAXIMUM;
}
if (start > elements.size()) {
break;
}
if (end > elements.size()) {
end = elements.size();
}
// If the elements can fit on a single page, create a bucket.
if (singlePage) {
nodes.add(new Bucket<E>(elements.subList(start, end)));
}
// Otherwise, continue recursively partioning the elements.
else {
nodes.add(this.partition(new ArrayList<>(elements.subList(
start, end
))));
}
}
return new Page<E>(nodes);
}
/**
* Check if an element intersects the specified bounds.
*
* @param <E> The type of elements to check intersection of.
* @param element The element.
* @param bounds The bounds.
* @return A boolean indicating whether or not the element intersects
* the specified bounds.
*/
private static <E extends Index> boolean intersects(
final E element,
final Bounds bounds
) {
if (element == null || bounds == null) {
return false;
}
return bounds.intersects(element.bounds());
}
/**
* @see <a href="http://www.cs.umd.edu/~nick/papers/nnpaper.pdf">
* http://www.cs.umd.edu/~nick/papers/nnpaper.pdf</a>
*
* @param point The point to calculate the minimum distance to.
* @param bounds The bounds to calculate the minimum distance from.
* @return The minimum distance between the specified bounds and the
* given point.
*/
private static double minimumDistance(
final Point point,
final Bounds bounds
) {
if (point == null || bounds == null) {
return Double.POSITIVE_INFINITY;
}
double r1 = point.x();
if (Epsilon.less(point.x(), bounds.min().x())) {
r1 = bounds.min().x();
}
else if (Epsilon.greater(point.x(), bounds.max().x())) {
r1 = bounds.max().x();
}
double r2 = point.y();
if (Epsilon.less(point.y(), bounds.min().y())) {
r2 = bounds.min().y();
}
else if (Epsilon.greater(point.y(), bounds.max().y())) {
r2 = bounds.max().y();
}
return Geometry.distance(point, new Point(r1, r2));
}
/**
* @see <a href="http://www.cs.umd.edu/~nick/papers/nnpaper.pdf">
* http://www.cs.umd.edu/~nick/papers/nnpaper.pdf</a>
*
* @param point The point to calculate the minimax distance to.
* @param bounds The bounds to calculate the minimax distance from.
* @return The minimax distance between the specified bounds and the
* given point.
*/
private static double minimaxDistance(
final Point point,
final Bounds bounds
) {
if (point == null || bounds == null) {
return Double.POSITIVE_INFINITY;
}
double rm1;
double rm2;
if (Epsilon.lessOrEqual(
point.x(), (bounds.min().x() + bounds.max().x()) / 2.0
)) {
rm1 = bounds.min().x();
}
else {
rm1 = bounds.max().x();
}
if (Epsilon.lessOrEqual(
point.y(), (bounds.min().y() + bounds.max().y()) / 2.0
)) {
rm2 = bounds.min().y();
}
else {
rm2 = bounds.max().y();
}
double rM1;
double rM2;
if (Epsilon.greaterOrEqual(
point.x(), (bounds.min().x() + bounds.max().x()) / 2.0
)) {
rM1 = bounds.min().x();
}
else {
rM1 = bounds.max().x();
}
if (Epsilon.greaterOrEqual(
point.y(), (bounds.min().y() + bounds.max().y()) / 2.0
)) {
rM2 = bounds.min().y();
}
else {
rM2 = bounds.max().x();
}
double s = Geometry.distance(point, new Point(rM1, rM2));
double distance = Math.min(
Math.pow(Math.abs(point.x() - rm1), 2) + s,
Math.pow(Math.abs(point.y() - rm2), 2) + s
);
return Math.sqrt(distance);
}
/**
* The {@link Index} interface describes an object that is indexable by the
* rectangle tree.
*/
public interface Index extends Serializable {
/**
* Get the smallest x-coordinate of the object.
*
* @return The smallest x-coordinate of the object.
*/
float minX();
/**
* Get the smallest y-coordinate of the object.
*
* @return The smallest y-coordinate of the object.
*/
float minY();
/**
* Get the largest x-coordinate of the object.
*
* @return The largest x-coordinate of the object.
*/
float maxX();
/**
* Ger the largest y-coordinate of the object.
*
* @return The largest y-coordinate of the object.
*/
float maxY();
/**
* Get the actual distance to the specified point from the index.
*
* @param point The point to find the distance to.
* @return The distance to the specified point from the index.
*/
double distance(final Point point);
/**
* Get the bounds of the object.
*
* @return The bounds of the object.
*/
default Bounds bounds() {
return new Bounds(this.minX(), this.minY(), this.maxX(), this.maxY());
}
}
/**
* The {@link Node} class describes a node within a rectangle tree.
*
* @param <E> The type of elements stored within the node.
*/
private abstract static class Node<E extends Index> implements Serializable {
/**
* UID for identifying serialized objects.
*/
private static final long serialVersionUID = 849;
/**
* The smallest x-coordinate of the nodes or elements contained within this
* node.
*/
private float minX;
/**
* The smallest y-coordinate of the nodes or elements contained within this
* node.
*/
private float minY;
/**
* The largest x-coordinate of the nodes or elements contained within this
* node.
*/
private float maxX;
/**
* The largest y-coordinate of the nodes or elements contained within this
* node.
*/
private float maxY;
/**
* Get the bounds of the node.
*
* @return The bounds of the node.
*/
public final Bounds bounds() {
return new Bounds(this.minX, this.minY, this.maxX, this.maxY);
}
/**
* Check if the node intersects the specified bounds.
*
* @param bounds The bounds to check intersection of.
* @return A boolean indicating whether or not the node intersects
* the specified bounds.
*/
public final boolean intersects(final Bounds bounds) {
return bounds.intersects(this.bounds());
}
/**
* Check if the node intersects the specified element.
*
* @param element The element to check intersection of.
* @return A boolean indicating whether or not the node intersects
* the specified element.
*/
public final boolean intersects(final E element) {
return RectangleTree.intersects(element, this.bounds());
}
/**
* Get the size of the node.
*
* @return The size of the node.
*/
public abstract int size();
/**
* Check if the node is empty.
*
* @return A boolean indicating whether or not the node is empty.
*/
public final boolean isEmpty() {
return this.size() == 0;
}
/**
* Check if the node contains the specified element.
*
* @param element The element to look for.
* @return A boolean indicating whether or not the node contains the
* specified element.
*/
public abstract boolean contains(final E element);
/**
* Find all elements within the range of the specified bounds.
*
* @param bounds The bounds to search for elements within.
* @param filter The filter to apply to the range search.
* @return All elements within the range of the specified bounds.
*/
public abstract List<E> range(final Bounds bounds, final Filter<E> filter);
/**
* Find the element in the node closest to the specified point.
*
* @param point The point to look for elements near.
* @param filter The filter to apply to the search.
* @return The element closest to the specified point.
*/
public abstract E nearest(final Point point, final Filter<E> filter);
/**
* Union the bounds of the current node with the bounds of the specified
* element.
*
* @param element The element whose bounds to union with the bounds of the
* current node.
*/
protected void union(final E element) {
if (element == null) {
return;
}
boolean empty = this.isEmpty();
this.minX = !empty ? Math.min(this.minX, element.minX()) : element.minX();
this.minY = !empty ? Math.min(this.minY, element.minY()) : element.minY();
this.maxX = !empty ? Math.max(this.maxX, element.maxX()) : element.maxX();
this.maxY = !empty ? Math.max(this.maxY, element.maxY()) : element.maxY();
}
/**
* Union the bounds of the current node with the bounds of the specified
* node.
*
* @param node The node whose bounds to union with the bounds of the
* current node.
*/
protected void union(final Node node) {
if (node == null) {
return;
}
boolean empty = this.isEmpty();
this.minX = !empty ? Math.min(this.minX, node.minX) : node.minX;
this.minY = !empty ? Math.min(this.minY, node.minY) : node.minY;
this.maxX = !empty ? Math.max(this.maxX, node.maxX) : node.maxX;
this.maxY = !empty ? Math.max(this.maxY, node.maxY) : node.maxY;
}
}
/**
* A {@link Page} is a {@link Node} that contains references to other
* {@link Node Nodes}.
*
* @param <E> The type of elements stored within the page.
*/
private static final class Page<E extends Index> extends Node<E> {
/**
* UID for identifying serialized objects.
*/
private static final long serialVersionUID = 850;
/**
* The nodes associated with the branch.
*/
private List<Node<E>> nodes;
/**
* Initialize a new page.
*
* @param nodes The nodes associated with the page.
*/
public Page(final List<Node<E>> nodes) {
this.nodes = nodes;
for (Node<E> node: nodes) {
if (node == null) {
continue;
}
this.union(node);
}
}
/**
* Get the size of the page.
*
* @return The size of the page.
*/
public int size() {
return this.nodes.size();
}
/**
* Check if the page contains the specified element.
*
* @param element The element to look for.
* @return A boolean indicating whether or not the page contains the
* specified element.
*/
public boolean contains(final E element) {
if (element == null || this.size() == 0) {
return false;
}
if (!this.intersects(element)) {
return false;
}
for (Node<E> node: this.nodes) {
if (node.contains(element)) {
return true;
}
}
return false;
}
/**
* Find all elements within the range of the specified bounds.
*
* @param bounds The bounds to search for elements within.
* @param filter The filter to apply to the range search.
* @return All elements with range of the specified bounds.
*/
public List<E> range(final Bounds bounds, final Filter<E> filter) {
List<E> elements = new ArrayList<>();
if (
this.size() == 0
|| bounds == null
|| filter == null
|| !this.intersects(bounds)
) {
return elements;
}
for (Node<E> node: this.nodes) {
if (node == null) {
continue;
}
elements.addAll(node.range(bounds, filter));
}
return elements;
}
/**
* Find the element in the page closest to the specified point.
*
* @param point The point to look for elements near.
* @param filter The filter to apply to the search.
* @return The element closest to the specified point.
*/
public E nearest(final Point point, final Filter<E> filter) {
if (point == null || filter == null) {
return null;
}
// "During the descending phase, at each newly visited nonleaf node, the
// algorithm computes the ordering metric bounds (e.g. MINDIST, Definition
// 2) for all its MBRs and sorts them (associated with their corresponding
// node) into an Active Branch List (ABL).
List<Node<E>> abl = new ArrayList<>(this.nodes);
Collections.sort(abl, (a, b) -> {
if (a == b) {
return 0;
}
if (a == null) {
return -1;
}
if (b == null) {
return 1;
}
return Double.compare(
RectangleTree.minimumDistance(point, a.bounds()),
RectangleTree.minimumDistance(point, b.bounds())
);
});
// Keep track of the smallest minimax distance.
double minimumMinimaxDistance = Double.POSITIVE_INFINITY;
for (Node<E> node: abl) {
double minimaxDistance = RectangleTree.minimaxDistance(
point, node.bounds()
);
if (minimumMinimaxDistance > minimaxDistance) {
minimumMinimaxDistance = minimaxDistance;
}
}
// Search pruning, strategy 1: "an MBR M with MINDIST(P,M) greater than
// the MINMAXDIST(P,M') of another MBR M' is discarded because it cannot
// contain the NN (theorems 1 and 2). We use this in downward pruning."
for (int i = 0; i < abl.size(); i++) {
double minimumDistance = RectangleTree.minimumDistance(
point, abl.get(i).bounds()
);
if (minimumDistance > minimumMinimaxDistance) {
abl.remove(i--);
}
}
E nearest = null;
while (abl.size() > 0) {
Node<E> next = abl.remove(0);
if (next == null) {
continue;
}
E estimate = next.nearest(point, filter);
if (estimate == null) {
continue;
}
if (nearest == null) {
nearest = estimate;
}
else {
double distNearest = nearest.distance(point);
double distEstimate = estimate.distance(point);
if (distNearest > distEstimate) {
nearest = estimate;
}
}
}
return nearest;
}
}
/**
* A {@link Bucket} is a {@link Node} that contains a list of elements rather
* than just a single element.
*
* @param <E> The type of elements stored within the bucket.
*/
private final class Bucket<E extends Index> extends Node<E> {
/**
* UID for identifying serialized objects.
*/
private static final long serialVersionUID = 851;
/**
* The elements associated with the bucket.
*/
private List<E> elements;
/**
* Initialize a new bucket.
*
* @param elements The elements associated with the bucket.
*/
public Bucket(final List<E> elements) {
this.elements = new ArrayList<>(elements);
for (E element: this.elements) {
if (element == null) {
continue;
}
this.union(element);
}
}
/**
* Get the size of the bucket.
*
* @return The size of the bucket.
*/
public int size() {
return this.elements.size();
}
/**
* Check if the bucket contains the specified element.
*
* @param element The element to look for.
* @return A boolean indicating whether or not the bucket contains
* the specified element.
*/
public boolean contains(final E element) {
if (element == null || this.size() == 0) {
return false;
}
for (E found: this.elements) {
if (found == null) {
continue;
}
if (element.equals(found)) {
return true;
}
}
return false;
}
/**
* Find all elements within the range of the specified bounds.
*
* @param bounds The bounds to search for elements within.
* @param filter The filter to apply to the range search.
* @return All elements within range of the specified bounds.
*/
public List<E> range(final Bounds bounds, final Filter<E> filter) {
List<E> elements = new ArrayList<>();
if (
this.size() == 0
|| bounds == null
|| filter == null
|| !this.intersects(bounds)
) {
return elements;
}
for (E element: this.elements) {
if (!filter.include(element)) {
continue;
}
if (RectangleTree.intersects(element, bounds)) {
elements.add(element);
}
}
return elements;
}
/**
* Find the element in the bucket closest to the specified point.
*
* @param point The point to look for elements near.
* @param filter The filter to apply to the search.
* @return The element closest to the specified point.
*/
public E nearest(final Point point, final Filter<E> filter) {
if (this.size() == 0 || point == null || filter == null) {
return null;
}
E nearest = null;
for (E element: this.elements) {
if (element == null || !filter.include(element)) {
continue;
}
if (nearest == null) {
nearest = element;
}
else {
double distNearest = nearest.distance(point);
double distElement = element.distance(point);
if (distNearest > distElement) {
nearest = element;
}
}
}
return nearest;
}
}
}
| |
/*
* Copyright 2019 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.gradle.api.internal.provider;
import org.gradle.api.Action;
import org.gradle.api.GradleException;
import org.gradle.api.NonExtensible;
import org.gradle.api.internal.properties.GradleProperties;
import org.gradle.api.internal.tasks.TaskDependencyResolveContext;
import org.gradle.api.provider.Provider;
import org.gradle.api.provider.ValueSource;
import org.gradle.api.provider.ValueSourceParameters;
import org.gradle.api.provider.ValueSourceSpec;
import org.gradle.internal.Cast;
import org.gradle.internal.Try;
import org.gradle.internal.event.AnonymousListenerBroadcast;
import org.gradle.internal.event.ListenerManager;
import org.gradle.internal.instantiation.InstanceGenerator;
import org.gradle.internal.instantiation.InstantiatorFactory;
import org.gradle.internal.isolated.IsolationScheme;
import org.gradle.internal.isolation.IsolatableFactory;
import org.gradle.internal.logging.text.TreeFormatter;
import org.gradle.internal.service.DefaultServiceRegistry;
import org.gradle.internal.service.ServiceLookup;
import org.gradle.process.ExecOperations;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class DefaultValueSourceProviderFactory implements ValueSourceProviderFactory {
private final InstantiatorFactory instantiatorFactory;
private final IsolatableFactory isolatableFactory;
private final GradleProperties gradleProperties;
private final ExecOperations execOperations;
private final AnonymousListenerBroadcast<Listener> broadcaster;
private final IsolationScheme<ValueSource, ValueSourceParameters> isolationScheme = new IsolationScheme<>(ValueSource.class, ValueSourceParameters.class, ValueSourceParameters.None.class);
private final InstanceGenerator paramsInstantiator;
private final InstanceGenerator specInstantiator;
public DefaultValueSourceProviderFactory(
ListenerManager listenerManager,
InstantiatorFactory instantiatorFactory,
IsolatableFactory isolatableFactory,
GradleProperties gradleProperties,
ExecOperations execOperations,
ServiceLookup services
) {
this.broadcaster = listenerManager.createAnonymousBroadcaster(ValueSourceProviderFactory.Listener.class);
this.instantiatorFactory = instantiatorFactory;
this.isolatableFactory = isolatableFactory;
this.gradleProperties = gradleProperties;
this.execOperations = execOperations;
// TODO - dedupe logic copied from DefaultBuildServicesRegistry
this.paramsInstantiator = instantiatorFactory.decorateScheme().withServices(services).instantiator();
this.specInstantiator = instantiatorFactory.decorateLenientScheme().withServices(services).instantiator();
}
@Override
public <T, P extends ValueSourceParameters> Provider<T> createProviderOf(Class<? extends ValueSource<T, P>> valueSourceType, Action<? super ValueSourceSpec<P>> configureAction) {
try {
Class<P> parametersType = extractParametersTypeOf(valueSourceType);
P parameters = parametersType != null
? paramsInstantiator.newInstance(parametersType)
: null;
// TODO - consider deferring configuration
configureParameters(parameters, configureAction);
return instantiateValueSourceProvider(valueSourceType, parametersType, parameters);
} catch (GradleException e) {
throw e;
} catch (Exception e) {
throw new GradleException(couldNotCreateProviderOf(valueSourceType), e);
}
}
@Override
public void addListener(Listener listener) {
broadcaster.add(listener);
}
@Override
public void removeListener(Listener listener) {
broadcaster.remove(listener);
}
@Override
@Nonnull
public <T, P extends ValueSourceParameters> Provider<T> instantiateValueSourceProvider(
Class<? extends ValueSource<T, P>> valueSourceType,
@Nullable Class<P> parametersType,
@Nullable P parameters
) {
return new ValueSourceProvider<>(
new LazilyObtainedValue<>(valueSourceType, parametersType, parameters)
);
}
@Nonnull
public <T, P extends ValueSourceParameters> ValueSource<T, P> instantiateValueSource(
Class<? extends ValueSource<T, P>> valueSourceType,
@Nullable Class<P> parametersType,
@Nullable P isolatedParameters
) {
DefaultServiceRegistry services = new DefaultServiceRegistry();
services.add(GradleProperties.class, gradleProperties);
services.add(ExecOperations.class, execOperations);
if (isolatedParameters != null) {
services.add(parametersType, isolatedParameters);
}
return instantiatorFactory
.injectScheme()
.withServices(services)
.instantiator()
.newInstance(valueSourceType);
}
@Nullable
private <T, P extends ValueSourceParameters> Class<P> extractParametersTypeOf(Class<? extends ValueSource<T, P>> valueSourceType) {
return isolationScheme.parameterTypeFor(valueSourceType, 1);
}
private <P extends ValueSourceParameters> void configureParameters(@Nullable P parameters, Action<? super ValueSourceSpec<P>> configureAction) {
DefaultValueSourceSpec<P> valueSourceSpec = Cast.uncheckedNonnullCast(specInstantiator.newInstance(
DefaultValueSourceSpec.class,
parameters
));
configureAction.execute(valueSourceSpec);
}
@Nullable
private <P extends ValueSourceParameters> P isolateParameters(@Nullable P parameters) {
// TODO - consider if should hold the project lock to do the isolation
return isolatableFactory.isolate(parameters).isolate();
}
private String couldNotCreateProviderOf(Class<?> valueSourceType) {
TreeFormatter formatter = new TreeFormatter();
formatter.node("Could not create provider for value source ");
formatter.appendType(valueSourceType);
formatter.append(".");
return formatter.toString();
}
@NonExtensible
public abstract static class DefaultValueSourceSpec<P extends ValueSourceParameters>
implements ValueSourceSpec<P> {
private final P parameters;
public DefaultValueSourceSpec(P parameters) {
this.parameters = parameters;
}
@Override
public P getParameters() {
return parameters;
}
@Override
public void parameters(Action<? super P> configureAction) {
configureAction.execute(parameters);
}
}
public static class ValueSourceProvider<T, P extends ValueSourceParameters> extends AbstractMinimalProvider<T> {
protected final LazilyObtainedValue<T, P> value;
public ValueSourceProvider(LazilyObtainedValue<T, P> value) {
this.value = value;
}
public Class<? extends ValueSource<T, P>> getValueSourceType() {
return value.sourceType;
}
@Override
public String toString() {
return String.format("valueof(%s)", getValueSourceType().getSimpleName());
}
@Nullable
public Class<P> getParametersType() {
return value.parametersType;
}
@Nullable
public P getParameters() {
return value.parameters;
}
@Override
public ValueProducer getProducer() {
return ValueProducer.externalValue();
}
@Override
public void visitDependencies(TaskDependencyResolveContext context) {
}
@Override
public boolean isImmutable() {
return true;
}
@Nullable
public Try<T> getObtainedValueOrNull() {
return value.value;
}
@Nullable
@Override
public Class<T> getType() {
return null;
}
@Override
public ExecutionTimeValue<T> calculateExecutionTimeValue() {
if (value.hasBeenObtained()) {
return ExecutionTimeValue.ofNullable(value.obtain().get());
} else {
return ExecutionTimeValue.changingValue(this);
}
}
@Override
protected Value<? extends T> calculateOwnValue(ValueConsumer consumer) {
return Value.ofNullable(value.obtain().get());
}
}
private class LazilyObtainedValue<T, P extends ValueSourceParameters> {
public final Class<? extends ValueSource<T, P>> sourceType;
@Nullable
public final Class<P> parametersType;
@Nullable
public final P parameters;
@Nullable
private volatile Try<T> value = null;
private LazilyObtainedValue(
Class<? extends ValueSource<T, P>> sourceType,
@Nullable Class<P> parametersType,
@Nullable P parameters
) {
this.sourceType = sourceType;
this.parametersType = parametersType;
this.parameters = parameters;
}
public boolean hasBeenObtained() {
return value != null;
}
public Try<T> obtain() {
ValueSource<T, P> source;
// Return value from local to avoid nullability warnings when returning value from the field directly.
Try<T> obtained;
synchronized (this) {
Try<T> cached = value;
if (cached != null) {
return cached;
}
// TODO - add more information to exceptions
// Fail fast when source can't be instantiated.
source = source();
value = obtained = Try.ofFailable(source::obtain);
}
// Value obtained for the 1st time, notify listeners.
broadcaster.getSource().valueObtained(obtainedValue(obtained), source);
return obtained;
}
@Nonnull
private ValueSource<T, P> source() {
return instantiateValueSource(
sourceType,
parametersType,
isolateParameters(parameters)
);
}
@Nonnull
private DefaultObtainedValue<T, P> obtainedValue(Try<T> obtained) {
return new DefaultObtainedValue<>(
obtained,
sourceType,
parametersType,
parameters
);
}
}
private static class DefaultObtainedValue<T, P extends ValueSourceParameters> implements Listener.ObtainedValue<T, P> {
private final Try<T> value;
private final Class<? extends ValueSource<T, P>> valueSourceType;
private final Class<P> parametersType;
@Nullable
private final P parameters;
public DefaultObtainedValue(
Try<T> value,
Class<? extends ValueSource<T, P>> valueSourceType,
Class<P> parametersType,
@Nullable P parameters
) {
this.value = value;
this.valueSourceType = valueSourceType;
this.parametersType = parametersType;
this.parameters = parameters;
}
@Override
public Try<T> getValue() {
return value;
}
@Override
public Class<? extends ValueSource<T, P>> getValueSourceType() {
return valueSourceType;
}
@Override
public Class<P> getValueSourceParametersType() {
return parametersType;
}
@Override
public P getValueSourceParameters() {
return parameters;
}
}
}
| |
/*
* Copyright (c) 2010-2015 Evolveum
*
* 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.evolveum.midpoint.repo.sql.query2;
import com.evolveum.midpoint.prism.Containerable;
import com.evolveum.midpoint.prism.ItemDefinition;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.query.*;
import com.evolveum.midpoint.repo.sql.ObjectPagingAfterOid;
import com.evolveum.midpoint.repo.sql.SqlRepositoryConfiguration;
import com.evolveum.midpoint.repo.sql.data.common.embedded.RPolyString;
import com.evolveum.midpoint.repo.sql.query.QueryException;
import com.evolveum.midpoint.repo.sql.query2.definition.*;
import com.evolveum.midpoint.repo.sql.query2.hqm.ProjectionElement;
import com.evolveum.midpoint.repo.sql.query2.hqm.RootHibernateQuery;
import com.evolveum.midpoint.repo.sql.query2.hqm.condition.Condition;
import com.evolveum.midpoint.repo.sql.query2.matcher.DefaultMatcher;
import com.evolveum.midpoint.repo.sql.query2.matcher.Matcher;
import com.evolveum.midpoint.repo.sql.query2.matcher.PolyStringMatcher;
import com.evolveum.midpoint.repo.sql.query2.matcher.StringMatcher;
import com.evolveum.midpoint.repo.sql.query2.resolution.ItemPathResolver;
import com.evolveum.midpoint.repo.sql.query2.resolution.ProperDataSearchResult;
import com.evolveum.midpoint.repo.sql.query2.restriction.*;
import com.evolveum.midpoint.repo.sql.util.GetContainerableResult;
import com.evolveum.midpoint.repo.sql.util.GetObjectResult;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import org.apache.commons.lang.Validate;
import org.hibernate.Session;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Interprets midPoint queries by translating them to hibernate (HQL) ones.
* <p/>
* There are two parts:
* - filter translation,
* - paging translation.
* <p/>
* As for filter translation, we traverse the filter depth-first, creating an isomorphic structure of Restrictions.
* While creating them, we continually build a set of entity references that are necessary to evaluate the query;
* these references are in the form of cartesian join of entities from which each one can have a set of entities
* connected to it via left outer join. An example:
* <p/>
* from
* RUser u
* left join u.assignments a with ...
* left join u.organization o,
* RRole r
* left join r.assignments a2 with ...
* <p/>
* This structure is maintained in InterpretationContext, namely in the HibernateQuery being prepared. (In order to
* produce HQL, we use ad-hoc "hibernate query model" in hqm package, rooted in HibernateQuery class.)
* <p/>
* Paging translation is done after filters are translated. It may add some entity references as well, if they are not
* already present.
*
* @author lazyman
* @author mederly
*/
public class QueryInterpreter2 {
private static final Trace LOGGER = TraceManager.getTrace(QueryInterpreter2.class);
private static final Map<Class, Matcher> AVAILABLE_MATCHERS;
static {
Map<Class, Matcher> matchers = new HashMap<>();
//default matcher with null key
matchers.put(null, new DefaultMatcher());
matchers.put(PolyString.class, new PolyStringMatcher());
matchers.put(String.class, new StringMatcher());
AVAILABLE_MATCHERS = Collections.unmodifiableMap(matchers);
}
private SqlRepositoryConfiguration repoConfiguration;
public QueryInterpreter2(SqlRepositoryConfiguration repoConfiguration) {
this.repoConfiguration = repoConfiguration;
}
public SqlRepositoryConfiguration getRepoConfiguration() {
return repoConfiguration;
}
public RootHibernateQuery interpret(ObjectQuery query, Class<? extends Containerable> type,
Collection<SelectorOptions<GetOperationOptions>> options, PrismContext prismContext,
boolean countingObjects, Session session) throws QueryException {
Validate.notNull(type, "Type must not be null.");
Validate.notNull(session, "Session must not be null.");
Validate.notNull(prismContext, "Prism context must not be null.");
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Interpreting query for type '{}', query:\n{}", new Object[]{type, query});
}
InterpretationContext context = new InterpretationContext(this, type, prismContext, session);
interpretQueryFilter(context, query);
interpretPagingAndSorting(context, query, countingObjects);
RootHibernateQuery hibernateQuery = context.getHibernateQuery();
if (countingObjects) {
hibernateQuery.addProjectionElement(new ProjectionElement("count(*)"));
} else {
String rootAlias = hibernateQuery.getPrimaryEntityAlias();
hibernateQuery.addProjectionElement(new ProjectionElement(rootAlias + ".fullObject"));
// TODO other objects if parent is requested?
if (context.isObject()) {
hibernateQuery.addProjectionElement(new ProjectionElement(rootAlias + ".stringsCount"));
hibernateQuery.addProjectionElement(new ProjectionElement(rootAlias + ".longsCount"));
hibernateQuery.addProjectionElement(new ProjectionElement(rootAlias + ".datesCount"));
hibernateQuery.addProjectionElement(new ProjectionElement(rootAlias + ".referencesCount"));
hibernateQuery.addProjectionElement(new ProjectionElement(rootAlias + ".polysCount"));
hibernateQuery.addProjectionElement(new ProjectionElement(rootAlias + ".booleansCount"));
hibernateQuery.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER);
} else {
hibernateQuery.addProjectionElement(new ProjectionElement(rootAlias + ".ownerOid"));
hibernateQuery.setResultTransformer(GetContainerableResult.RESULT_TRANSFORMER);
}
}
return hibernateQuery;
}
private void interpretQueryFilter(InterpretationContext context, ObjectQuery query) throws QueryException {
if (query != null && query.getFilter() != null) {
Condition c = interpretFilter(context, query.getFilter(), null);
context.getHibernateQuery().addCondition(c);
}
}
public Condition interpretFilter(InterpretationContext context, ObjectFilter filter, Restriction parent) throws QueryException {
Restriction restriction = findAndCreateRestriction(filter, context, parent);
Condition condition = restriction.interpret();
return condition;
}
private <T extends ObjectFilter> Restriction findAndCreateRestriction(T filter, InterpretationContext context,
Restriction parent) throws QueryException {
Validate.notNull(filter, "filter");
Validate.notNull(context, "context");
LOGGER.trace("Determining restriction for filter {}", filter);
ItemPathResolver helper = context.getItemPathResolver();
JpaEntityDefinition baseEntityDefinition;
if (parent != null) {
baseEntityDefinition = parent.getBaseHqlEntityForChildren().getJpaDefinition();
} else {
baseEntityDefinition = context.getRootEntityDefinition();
}
Restriction restriction = findAndCreateRestrictionInternal(filter, context, parent, helper, baseEntityDefinition);
LOGGER.trace("Restriction for {} is {}", filter.getClass().getSimpleName(), restriction);
return restriction;
}
private <T extends ObjectFilter>
Restriction findAndCreateRestrictionInternal(T filter, InterpretationContext context, Restriction parent,
ItemPathResolver resolver, JpaEntityDefinition baseEntityDefinition) throws QueryException {
// the order of processing restrictions can be important, so we do the selection via handwritten code
if (filter instanceof AndFilter) {
return new AndRestriction(context, (AndFilter) filter, baseEntityDefinition, parent);
} else if (filter instanceof OrFilter) {
return new OrRestriction(context, (OrFilter) filter, baseEntityDefinition, parent);
} else if (filter instanceof NotFilter) {
return new NotRestriction(context, (NotFilter) filter, baseEntityDefinition, parent);
} else if (filter instanceof InOidFilter) {
return new InOidRestriction(context, (InOidFilter) filter, baseEntityDefinition, parent);
} else if (filter instanceof OrgFilter) {
return new OrgRestriction(context, (OrgFilter) filter, baseEntityDefinition, parent);
} else if (filter instanceof TypeFilter) {
TypeFilter typeFilter = (TypeFilter) filter;
JpaEntityDefinition refinedEntityDefinition = resolver.findRestrictedEntityDefinition(baseEntityDefinition, typeFilter.getType());
return new TypeRestriction(context, typeFilter, refinedEntityDefinition, parent);
} else if (filter instanceof ExistsFilter) {
ExistsFilter existsFilter = (ExistsFilter) filter;
ItemPath path = existsFilter.getFullPath();
ItemDefinition definition = existsFilter.getDefinition();
ProperDataSearchResult<JpaEntityDefinition> searchResult = resolver.findProperDataDefinition(
baseEntityDefinition, path, definition, JpaEntityDefinition.class);
if (searchResult == null) {
throw new QueryException("Path for ExistsFilter (" + path + ") doesn't point to a hibernate entity within " + baseEntityDefinition);
}
return new ExistsRestriction(context, existsFilter, searchResult.getEntityDefinition(), parent);
} else if (filter instanceof RefFilter) {
RefFilter refFilter = (RefFilter) filter;
ItemPath path = refFilter.getFullPath();
ItemDefinition definition = refFilter.getDefinition();
ProperDataSearchResult<JpaReferenceDefinition> searchResult = resolver.findProperDataDefinition(
baseEntityDefinition, path, definition, JpaReferenceDefinition.class);
if (searchResult == null) {
throw new QueryException("Path for RefFilter (" + path + ") doesn't point to a reference item within " + baseEntityDefinition);
}
return new ReferenceRestriction(context, refFilter, searchResult.getEntityDefinition(),
parent, searchResult.getLinkDefinition());
} else if (filter instanceof PropertyValueFilter) {
PropertyValueFilter valFilter = (PropertyValueFilter) filter;
ItemPath path = valFilter.getFullPath();
ItemDefinition definition = valFilter.getDefinition();
ProperDataSearchResult<JpaPropertyDefinition> propDefRes = resolver.findProperDataDefinition(baseEntityDefinition, path, definition, JpaPropertyDefinition.class);
if (propDefRes == null) {
throw new QueryException("Couldn't find a proper restriction for a ValueFilter: " + valFilter.debugDump());
}
// TODO can't be unified?
if (propDefRes.getTargetDefinition() instanceof JpaAnyPropertyDefinition) {
return new AnyPropertyRestriction(context, valFilter, propDefRes.getEntityDefinition(), parent, propDefRes.getLinkDefinition());
} else {
return new PropertyRestriction(context, valFilter, propDefRes.getEntityDefinition(), parent, propDefRes.getLinkDefinition());
}
} else if (filter instanceof NoneFilter || filter instanceof AllFilter || filter instanceof UndefinedFilter) {
// these should be filtered out by the client
throw new IllegalStateException("Trivial filters are not supported by QueryInterpreter: " + filter.debugDump());
} else {
throw new IllegalStateException("Unknown filter: " + filter.debugDump());
}
}
private void interpretPagingAndSorting(InterpretationContext context, ObjectQuery query, boolean countingObjects) throws QueryException {
RootHibernateQuery hibernateQuery = context.getHibernateQuery();
String rootAlias = hibernateQuery.getPrimaryEntityAlias();
if (query != null && query.getPaging() instanceof ObjectPagingAfterOid) {
ObjectPagingAfterOid paging = (ObjectPagingAfterOid) query.getPaging();
if (paging.getOidGreaterThan() != null) {
Condition c = hibernateQuery.createSimpleComparisonCondition(rootAlias + ".oid", paging.getOidGreaterThan(), ">");
hibernateQuery.addCondition(c);
}
}
if (!countingObjects && query != null && query.getPaging() != null) {
if (query.getPaging() instanceof ObjectPagingAfterOid) {
updatePagingAndSortingByOid(hibernateQuery, (ObjectPagingAfterOid) query.getPaging()); // very special case - ascending ordering by OID (nothing more)
} else {
updatePagingAndSorting(context, query.getPaging());
}
}
}
protected void updatePagingAndSortingByOid(RootHibernateQuery hibernateQuery, ObjectPagingAfterOid paging) {
String rootAlias = hibernateQuery.getPrimaryEntityAlias();
if (paging.getOrderBy() != null || paging.getDirection() != null || paging.getOffset() != null) {
throw new IllegalArgumentException("orderBy, direction nor offset is allowed on ObjectPagingAfterOid");
}
hibernateQuery.addOrdering(rootAlias + ".oid", OrderDirection.ASCENDING);
if (paging.getMaxSize() != null) {
hibernateQuery.setMaxResults(paging.getMaxSize());
}
}
public <T extends Containerable> void updatePagingAndSorting(InterpretationContext context,
ObjectPaging paging) throws QueryException {
if (paging == null) {
return;
}
RootHibernateQuery hibernateQuery = context.getHibernateQuery();
if (paging.getOffset() != null) {
hibernateQuery.setFirstResult(paging.getOffset());
}
if (paging.getMaxSize() != null) {
hibernateQuery.setMaxResults(paging.getMaxSize());
}
if (!paging.hasOrdering()) {
return;
}
for (ObjectOrdering ordering : paging.getOrderingInstructions()) {
addOrdering(context, ordering);
}
}
private void addOrdering(InterpretationContext context, ObjectOrdering ordering) throws QueryException {
ItemPath orderByPath = ordering.getOrderBy();
// TODO if we'd like to have order-by extension properties, we'd need to provide itemDefinition for them
ProperDataSearchResult<JpaDataNodeDefinition> result = context.getItemPathResolver().findProperDataDefinition(
context.getRootEntityDefinition(), orderByPath, null, JpaDataNodeDefinition.class);
if (result == null) {
LOGGER.error("Unknown path '" + orderByPath + "', couldn't find definition for it, "
+ "list will not be ordered by it.");
return;
}
JpaDataNodeDefinition targetDefinition = result.getLinkDefinition().getTargetDefinition();
if (targetDefinition instanceof JpaAnyContainerDefinition) {
throw new QueryException("Sorting based on extension item or attribute is not supported yet: " + orderByPath);
} else if (targetDefinition instanceof JpaReferenceDefinition) {
throw new QueryException("Sorting based on reference is not supported: " + orderByPath);
} else if (result.getLinkDefinition().isMultivalued()) {
throw new QueryException("Sorting based on multi-valued item is not supported: " + orderByPath);
} else if (targetDefinition instanceof JpaEntityDefinition) {
throw new QueryException("Sorting based on entity is not supported: " + orderByPath);
} else if (!(targetDefinition instanceof JpaPropertyDefinition)) {
throw new IllegalStateException("Unknown item definition type: " + result.getClass());
}
JpaEntityDefinition baseEntityDefinition = result.getEntityDefinition();
JpaPropertyDefinition orderByDefinition = (JpaPropertyDefinition) targetDefinition;
String hqlPropertyPath = context.getItemPathResolver()
.resolveItemPath(orderByPath, null, context.getPrimaryEntityAlias(), baseEntityDefinition, true)
.getHqlPath();
if (RPolyString.class.equals(orderByDefinition.getJpaClass())) {
hqlPropertyPath += ".orig";
}
RootHibernateQuery hibernateQuery = context.getHibernateQuery();
if (ordering.getDirection() != null) {
switch (ordering.getDirection()) {
case ASCENDING:
hibernateQuery.addOrdering(hqlPropertyPath, OrderDirection.ASCENDING);
break;
case DESCENDING:
hibernateQuery.addOrdering(hqlPropertyPath, OrderDirection.DESCENDING);
break;
}
} else {
hibernateQuery.addOrdering(hqlPropertyPath, OrderDirection.ASCENDING);
}
}
public <T extends Object> Matcher<T> findMatcher(T value) {
return findMatcher(value != null ? (Class<T>) value.getClass() : null);
}
public <T extends Object> Matcher<T> findMatcher(Class<T> type) {
Matcher<T> matcher = AVAILABLE_MATCHERS.get(type);
if (matcher == null) {
//we return default matcher
matcher = AVAILABLE_MATCHERS.get(null);
}
return matcher;
}
}
| |
/*
* Copyright (C) 2014-2015 Actor LLC. <https://actor.im>
*/
package im.AfriChat.core;
import com.google.j2objc.annotations.ObjectiveCName;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import im.AfriChat.core.api.ApiSex;
import im.AfriChat.core.api.ApiAuthSession;
import im.AfriChat.core.entity.FileReference;
import im.AfriChat.core.entity.Group;
import im.AfriChat.core.entity.MentionFilterResult;
import im.AfriChat.core.entity.Peer;
import im.AfriChat.core.entity.PublicGroup;
import im.AfriChat.core.entity.Sex;
import im.AfriChat.core.entity.User;
import im.AfriChat.core.entity.content.FastThumb;
import im.AfriChat.core.i18n.I18nEngine;
import im.AfriChat.core.modules.Modules;
import im.AfriChat.core.network.NetworkState;
import im.AfriChat.core.network.parser.Request;
import im.AfriChat.core.network.parser.Response;
import im.AfriChat.core.util.ActorTrace;
import im.AfriChat.core.util.Timing;
import im.AfriChat.core.viewmodel.AppStateVM;
import im.AfriChat.core.viewmodel.Command;
import im.AfriChat.core.viewmodel.FileCallback;
import im.AfriChat.core.viewmodel.FileVM;
import im.AfriChat.core.viewmodel.FileVMCallback;
import im.AfriChat.core.viewmodel.GroupAvatarVM;
import im.AfriChat.core.viewmodel.GroupVM;
import im.AfriChat.core.viewmodel.OwnAvatarVM;
import im.AfriChat.core.viewmodel.UploadFileCallback;
import im.AfriChat.core.viewmodel.UploadFileVM;
import im.AfriChat.core.viewmodel.UploadFileVMCallback;
import im.AfriChat.core.viewmodel.UserVM;
import im.AfriChat.runtime.actors.ActorSystem;
import im.AfriChat.runtime.mvvm.MVVMCollection;
import im.AfriChat.runtime.mvvm.ValueModel;
import im.AfriChat.runtime.storage.PreferencesStorage;
/**
* Entry point to Actor Messaging
* Before using Messenger you need to create Configuration object by using ConfigurationBuilder.
*/
public class Messenger {
protected Modules modules;
/**
* Construct messenger
*
* @param configuration configuration of messenger
*/
@ObjectiveCName("initWithConfiguration:")
public Messenger(@NotNull Configuration configuration) {
// We assume that configuration is valid and all configuration verification
// Must be implemented in Configuration object
// Start Messenger initialization
Timing timing = new Timing("MESSENGER_INIT");
// Actor system
timing.section("Actors");
ActorSystem.system().setTraceInterface(new ActorTrace());
ActorSystem.system().addDispatcher("network");
ActorSystem.system().addDispatcher("heavy");
ActorSystem.system().addDispatcher("updates", 1);
timing.section("Modules:Create");
this.modules = new Modules(this, configuration);
timing.end();
}
//////////////////////////////////////
// Authentication
//////////////////////////////////////
/**
* Get current Authentication state
*
* @return current Authentication state
*/
@NotNull
public AuthState getAuthState() {
return modules.getAuthModule().getAuthState();
}
/**
* Convenience method for checking if user logged in
*
* @return true if user is logged in
*/
public boolean isLoggedIn() {
return getAuthState() == AuthState.LOGGED_IN;
}
/**
* Request email auth
*
* @param email email to authenticate
* @return Command for execution
*/
@NotNull
@ObjectiveCName("requestStartEmailAuthCommandWithEmail:")
public Command<AuthState> requestStartEmailAuth(final String email) {
return modules.getAuthModule().requestStartEmailAuth(email);
}
/**
* Request phone auth
*
* @param phone phone to authenticate
* @return Command for execution
*/
@NotNull
@ObjectiveCName("requestStartPhoneAuthCommandWithEmail:")
public Command<AuthState> requestStartPhoneAuth(final long phone) {
return modules.getAuthModule().requestStartPhoneAuth(phone);
}
/**
* Request OAuth params
*
* @return Command for execution
*/
@NotNull
@ObjectiveCName("requestGetOAuthParamsCommand")
public Command<AuthState> requestGetOAuthParams() {
return modules.getAuthModule().requestGetOAuth2Params();
}
/**
* Request complete OAuth
*
* @param code code from oauth
* @return Command for execution
*/
@NotNull
@ObjectiveCName("requestCompleteOAuthCommandWithCode:")
public Command<AuthState> requestCompleteOAuth(String code) {
return modules.getAuthModule().requestCompleteOauth(code);
}
/**
* Sending activation code
*
* @param code activation code
* @return Command for execution
*/
@NotNull
@ObjectiveCName("validateCodeCommandWithCode:")
public Command<AuthState> validateCode(final String code) {
return modules.getAuthModule().requestValidateCode(code);
}
/**
* Perform signup
*
* @param name Name of User
* @param sex user sex
* @param avatarPath File descriptor of avatar (may be null if not set)
* @return Comand for execution
*/
@NotNull
@ObjectiveCName("signUpCommandWithName:WithSex:withAvatar:")
public Command<AuthState> signUp(String name, Sex sex, String avatarPath) {
return modules.getAuthModule().signUp(name, ApiSex.UNKNOWN, avatarPath);
}
/**
* Get current Authentication phone.
* Value is valid only for SIGN_UP or CODE_VALIDATION_PHONE states.
*
* @return phone number in international format
*/
@ObjectiveCName("getAuthPhone")
public long getAuthPhone() {
return modules.getAuthModule().getPhone();
}
/**
* Get current Authentication email.
* Value is valid only for SIGN_UP or CODE_VALIDATION_EMAIL states.
*
* @return email
*/
@ObjectiveCName("getAuthEmail")
public String getAuthEmail() {
return modules.getAuthModule().getEmail();
}
/**
* Resetting authentication process
*/
@ObjectiveCName("resetAuth")
public void resetAuth() {
modules.getAuthModule().resetAuth();
}
public void onLoggedIn() {
}
//////////////////////////////////////
// Authenticated state
//////////////////////////////////////
/**
* Get ViewModel of application state
*
* @return view model of application state
*/
@NotNull
@ObjectiveCName("getAppState")
public AppStateVM getAppState() {
return modules.getAppStateModule().getAppStateVM();
}
/**
* Get authenticated User Id
*
* @return current User Id
*/
@ObjectiveCName("myUid")
public int myUid() {
return modules.getAuthModule().myUid();
}
//////////////////////////////////////
// View Models
//////////////////////////////////////
/**
* Get User View Model Collection
*
* @return User ViewModel Collection
*/
@Nullable
@ObjectiveCName("getUsers")
public MVVMCollection<User, UserVM> getUsers() {
if (modules.getUsersModule() == null) {
return null;
}
return modules.getUsersModule().getUsers();
}
/**
* Get User Value Model by UID
*
* @param uid uid
* @return User Value Model
*/
@NotNull
@ObjectiveCName("getUserWithUid:")
public UserVM getUser(int uid) {
//noinspection ConstantConditions
return getUsers().get(uid);
}
/**
* Get Group View Model Collection
*
* @return Group ViewModel Collection
*/
@Nullable
@ObjectiveCName("getGroups")
public MVVMCollection<Group, GroupVM> getGroups() {
if (modules.getGroupsModule() == null) {
return null;
}
return modules.getGroupsModule().getGroupsCollection();
}
/**
* Get Group Value Model by GID
*
* @param gid gid
* @return Group Value Model
*/
@NotNull
@ObjectiveCName("getGroupWithGid:")
public GroupVM getGroup(int gid) {
//noinspection ConstantConditions
return getGroups().get(gid);
}
/**
* Get private chat ViewModel
*
* @param uid chat's User Id
* @return ValueModel of Boolean for typing state
*/
@Nullable
@ObjectiveCName("getTypingWithUid:")
public ValueModel<Boolean> getTyping(int uid) {
if (modules.getTypingModule() == null) {
return null;
}
return modules.getTypingModule().getTyping(uid).getTyping();
}
/**
* Get group chat ViewModel
*
* @param gid chat's Group Id
* @return ValueModel of int[] for typing state
*/
@Nullable
@ObjectiveCName("getGroupTypingWithGid:")
public ValueModel<int[]> getGroupTyping(int gid) {
if (modules.getTypingModule() == null) {
return null;
}
return modules.getTypingModule().getGroupTyping(gid).getActive();
}
/**
* Get Own avatar ViewModel
* Used for displaying avatar change progress
*
* @return the OwnAvatarVM
*/
@Nullable
@ObjectiveCName("getOwnAvatarVM")
public OwnAvatarVM getOwnAvatarVM() {
return modules.getProfileModule().getOwnAvatarVM();
}
/**
* Get Group avatar ViewModel
* Used for displaying group avatar change progress
*
* @param gid group's ID
* @return the GroupAvatarVM
*/
@Nullable
@ObjectiveCName("getGroupAvatarVMWithGid:")
public GroupAvatarVM getGroupAvatarVM(int gid) {
return modules.getGroupsModule().getAvatarVM(gid);
}
//////////////////////////////////////
// Application events
//////////////////////////////////////
/**
* MUST be called on app became visible
*/
@ObjectiveCName("onAppVisible")
public void onAppVisible() {
modules.onAppVisible();
}
/**
* MUST be called on app became hidden
*/
@ObjectiveCName("onAppHidden")
public void onAppHidden() {
modules.onAppHidden();
}
/**
* MUST be called on dialogs open
*/
@ObjectiveCName("onDialogsOpen")
public void onDialogsOpen() {
if (modules.getNotificationsModule() != null) {
modules.getNotificationsModule().onDialogsOpen();
}
}
/**
* MUST be called on dialogs closed
*/
@ObjectiveCName("onDialogsClosed")
public void onDialogsClosed() {
if (modules.getNotificationsModule() != null) {
modules.getNotificationsModule().onDialogsClosed();
}
}
/**
* MUST be called on conversation open
*
* @param peer conversation's peer
*/
@ObjectiveCName("onConversationOpenWithPeer:")
public void onConversationOpen(@NotNull Peer peer) {
modules.getAnalyticsModule().trackChatOpen(peer);
if (modules.getPresenceModule() != null) {
modules.getPresenceModule().subscribe(peer);
modules.getNotificationsModule().onConversationOpen(peer);
modules.getMessagesModule().onConversationOpen(peer);
}
}
/**
* MUST be called on conversation closed
*
* @param peer conversation's peer
*/
@ObjectiveCName("onConversationClosedWithPeer:")
public void onConversationClosed(@NotNull Peer peer) {
modules.getAnalyticsModule().trackChatClosed(peer);
if (modules.getPresenceModule() != null) {
modules.getNotificationsModule().onConversationClose(peer);
}
}
/**
* MUST be called on profile open
*
* @param uid user's Id
*/
@ObjectiveCName("onProfileOpenWithUid:")
public void onProfileOpen(int uid) {
modules.getAnalyticsModule().trackProfileOpen(uid);
if (modules.getPresenceModule() != null) {
modules.getPresenceModule().subscribe(Peer.user(uid));
}
}
/**
* MUST be called on profile closed
*
* @param uid user's Id
*/
@ObjectiveCName("onProfileClosedWithUid:")
public void onProfileClosed(int uid) {
modules.getAnalyticsModule().trackProfileClosed(uid);
}
/**
* MUST be called on typing in chat.
* Can be called with any frequency
*
* @param peer conversation's peer
*/
@ObjectiveCName("onTypingWithPeer:")
public void onTyping(@NotNull Peer peer) {
modules.getTypingModule().onTyping(peer);
}
//////////////////////////////////////
// Technical events
//////////////////////////////////////
/**
* MUST be called when phone book change detected
*/
@ObjectiveCName("onPhoneBookChanged")
public void onPhoneBookChanged() {
if (modules.getContactsModule() != null) {
modules.getContactsModule().onPhoneBookChanged();
}
}
/**
* MUST be called when network status change detected
*
* @param state New network state
*/
@ObjectiveCName("onNetworkChanged")
public void onNetworkChanged(@NotNull NetworkState state) {
modules.getActorApi().onNetworkChanged(state);
}
/**
* MUST be called when external push received
*
* @param seq sequence number of update
*/
@ObjectiveCName("onPushReceivedWithSeq:")
public void onPushReceived(int seq) {
if (modules.getUpdatesModule() != null) {
modules.getUpdatesModule().onPushReceived(seq);
}
}
//////////////////////////////////////
// Messaging operations
//////////////////////////////////////
/**
* Send Markdown Message with mentions
*
* @param peer destination peer
* @param text message text
* @param markDownText message markdown text
* @param mentions user's mentions
*/
@ObjectiveCName("sendMessageWithPeer:withText:withMarkdownText:withMentions:autoDetect:")
public void sendMessage(@NotNull Peer peer, @NotNull String text, @Nullable String markDownText,
@Nullable ArrayList<Integer> mentions, boolean autoDetect) {
modules.getMessagesModule().sendMessage(peer, text, markDownText, mentions, autoDetect);
}
/**
* Send Markdown Message with mentions
*
* @param peer destination peer
* @param text message text
* @param markDownText message markdown text
* @param mentions user's mentions
*/
@ObjectiveCName("sendMessageWithPeer:withText:withMarkdownText:withMentions:")
public void sendMessage(@NotNull Peer peer, @NotNull String text, @Nullable String markDownText,
@Nullable ArrayList<Integer> mentions) {
modules.getMessagesModule().sendMessage(peer, text, markDownText, mentions, false);
}
/**
* Send Markdown Message
*
* @param peer destination peer
* @param text message text
* @param markDownText message markdown text
*/
@ObjectiveCName("sendMessageWithPeer:withText:withMarkdownText:")
public void sendMessage(@NotNull Peer peer, @NotNull String text, @Nullable String markDownText) {
sendMessage(peer, text, markDownText, null, false);
}
/**
* Send Text Message with mentions
*
* @param peer destination peer
* @param text message text
* @param mentions user's mentions
*/
@ObjectiveCName("sendMessageWithPeer:withText:withMentions:")
public void sendMessage(@NotNull Peer peer, @NotNull String text, @Nullable ArrayList<Integer> mentions) {
sendMessage(peer, text, null, mentions, false);
}
/**
* Send Text Message
*
* @param peer destination peer
* @param text message text
*/
@ObjectiveCName("sendMessageWithPeer:withText:")
public void sendMessage(@NotNull Peer peer, @NotNull String text) {
sendMessage(peer, text, null, null, false);
}
/**
* Send Text Message
*
* @param peer destination peer
* @param text message text
*/
@ObjectiveCName("sendMessageWithMentionsDetect:withText:")
public void sendMessageWithMentionsDetect(@NotNull Peer peer, @NotNull String text) {
sendMessage(peer, text, null, null, true);
}
/**
* Send Text Message
*
* @param peer destination peer
* @param text message text
*/
@ObjectiveCName("sendMessageWithMentionsDetect:withText:withMarkdownText:")
public void sendMessageWithMentionsDetect(@NotNull Peer peer, @NotNull String text, @NotNull String markdownText) {
sendMessage(peer, text, markdownText, null, true);
}
/**
* Send Photo message
*
* @param peer destination peer
* @param fileName File name (without path)
* @param w photo width
* @param h photo height
* @param fastThumb Fast thumb of photo
* @param descriptor File Descriptor
*/
@ObjectiveCName("sendPhotoWithPeer:withName:withW:withH:withThumb:withDescriptor:")
public void sendPhoto(@NotNull Peer peer, @NotNull String fileName,
int w, int h, @Nullable FastThumb fastThumb,
@NotNull String descriptor) {
modules.getMessagesModule().sendPhoto(peer, fileName, w, h, fastThumb, descriptor);
}
/**
* Send Video message
*
* @param peer destination peer
* @param fileName File name (without path)
* @param w video width
* @param h video height
* @param duration video duration
* @param fastThumb Fast thumb of video
* @param descriptor File Descriptor
*/
@ObjectiveCName("sendVideoWithPeer:withName:withW:withH:withDuration:withThumb:withDescriptor:")
public void sendVideo(Peer peer, String fileName, int w, int h, int duration,
FastThumb fastThumb, String descriptor) {
modules.getMessagesModule().sendVideo(peer, fileName, w, h, duration, fastThumb, descriptor);
}
/**
* Send document without preview
*
* @param peer destination peer
* @param fileName File name (without path)
* @param mimeType mimetype of document
* @param descriptor File Descriptor
*/
@ObjectiveCName("sendDocumentWithPeer:withName:withMime:withDescriptor:")
public void sendDocument(Peer peer, String fileName, String mimeType, String descriptor) {
sendDocument(peer, fileName, mimeType, null, descriptor);
}
/**
* Send document with preview
*
* @param peer destination peer
* @param fileName File name (without path)
* @param mimeType mimetype of document
* @param descriptor File Descriptor
* @param fastThumb FastThumb of preview
*/
@ObjectiveCName("sendDocumentWithPeer:withName:withMime:withThumb:withDescriptor:")
public void sendDocument(Peer peer, String fileName, String mimeType, FastThumb fastThumb,
String descriptor) {
modules.getMessagesModule().sendDocument(peer, fileName, mimeType, fastThumb, descriptor);
}
/**
* Delete messages
*
* @param peer destination peer
* @param rids rids of messages
*/
@ObjectiveCName("deleteMessagesWithPeer:withRids:")
public void deleteMessages(Peer peer, long[] rids) {
modules.getMessagesModule().deleteMessages(peer, rids);
}
/**
* Delete chat
*
* @param peer destination peer
* @return Command for execution
*/
@ObjectiveCName("deleteChatCommandWithPeer:")
public Command<Boolean> deleteChat(Peer peer) {
return modules.getMessagesModule().deleteChat(peer);
}
/**
* Clear chat
*
* @param peer destination peer
* @return Command for execution
*/
@ObjectiveCName("clearChatCommandWithPeer:")
public Command<Boolean> clearChat(Peer peer) {
return modules.getMessagesModule().clearChat(peer);
}
/**
* Save message draft
*
* @param peer destination peer
* @param draft message draft
*/
@ObjectiveCName("saveDraftWithPeer:withDraft:")
public void saveDraft(Peer peer, String draft) {
modules.getMessagesModule().saveDraft(peer, draft);
}
/**
* Load message draft
*
* @param peer destination peer
* @return null if no draft available
*/
@Nullable
@ObjectiveCName("loadDraftWithPeer:")
public String loadDraft(Peer peer) {
return modules.getMessagesModule().loadDraft(peer);
}
/**
* Loading last read messages
*
* @param peer destination peer
* @return rid of last read message
*/
@ObjectiveCName("loadFirstUnread:")
public long loadFirstUnread(Peer peer) {
return modules.getMessagesModule().loadReadState(peer);
}
/**
* Finding suitable mentions
*
* @param gid gid of group
* @param query query for search
* @return matches
*/
@ObjectiveCName("findMentionsWithGid:withQuery:")
public List<MentionFilterResult> findMentions(int gid, String query) {
return modules.getMentions().findMentions(gid, query);
}
//////////////////////////////////////
// Peer operations
//////////////////////////////////////
/**
* Edit current user's name
*
* @param newName new user's name
* @return Command for execution
*/
@Nullable
@ObjectiveCName("editMyNameCommandWithName:")
public Command<Boolean> editMyName(final String newName) {
return modules.getUsersModule().editMyName(newName);
}
/**
* Edit current user's nick
*
* @param newNick new user's nick
* @return Command for execution
*/
@Nullable
@ObjectiveCName("editMyNickCommandWithNick:")
public Command<Boolean> editMyNick(final String newNick) {
return modules.getUsersModule().editNick(newNick);
}
/**
* Edit current user's about
*
* @param newAbout new user's about
* @return Command for execution
*/
@Nullable
@ObjectiveCName("editMyAboutCommandWithNick:")
public Command<Boolean> editMyAbout(final String newAbout) {
return modules.getUsersModule().editAbout(newAbout);
}
/**
* Change current user's avatar
*
* @param descriptor descriptor of avatar file
*/
@ObjectiveCName("changeMyAvatarWithDescriptor:")
public void changeMyAvatar(String descriptor) {
modules.getProfileModule().changeAvatar(descriptor);
}
/**
* Remove current user's avatar
*/
@ObjectiveCName("removeMyAvatar")
public void removeMyAvatar() {
modules.getProfileModule().removeAvatar();
}
/**
* Edit user's local name
*
* @param uid user's id
* @param name new user's local name
* @return Command for execution
*/
@Nullable
@ObjectiveCName("editNameCommandWithUid:withName:")
public Command<Boolean> editName(final int uid, final String name) {
return modules.getUsersModule().editName(uid, name);
}
/**
* Edit group's title
*
* @param gid group's id
* @param title new group title
* @return Command for execution
*/
@Nullable
@ObjectiveCName("editGroupTitleCommandWithGid:withTitle:")
public Command<Boolean> editGroupTitle(final int gid, final String title) {
return modules.getGroupsModule().editTitle(gid, title);
}
/**
* Edit group's theme
*
* @param gid group's id
* @param theme new group theme
* @return Command for execution
*/
@Nullable
@ObjectiveCName("editGroupThemeCommandWithGid:withTheme:")
public Command<Boolean> editGroupTheme(final int gid, final String theme) {
return modules.getGroupsModule().editTheme(gid, theme);
}
/**
* Edit group's about
*
* @param gid group's id
* @param about new group about
* @return Command for execution
*/
@Nullable
@ObjectiveCName("editGroupAboutCommandWithGid:withAbout:")
public Command<Boolean> editGroupAbout(final int gid, final String about) {
return modules.getGroupsModule().editAbout(gid, about);
}
/**
* Change group avatar
*
* @param gid group's id
* @param descriptor descriptor of avatar file
*/
@ObjectiveCName("changeGroupAvatarWithGid:withDescriptor:")
public void changeGroupAvatar(int gid, String descriptor) {
modules.getGroupsModule().changeAvatar(gid, descriptor);
}
/**
* Removing group avatar
*
* @param gid group's id
*/
@ObjectiveCName("removeGroupAvatarWithGid:")
public void removeGroupAvatar(int gid) {
modules.getGroupsModule().removeAvatar(gid);
}
//////////////////////////////////////
// Group operations
//////////////////////////////////////
/**
* Create group
*
* @param title group title
* @param avatarDescriptor descriptor of group avatar (can be null if not set)
* @param uids member's ids
* @return Command for execution
*/
@Nullable
@ObjectiveCName("createGroupCommandWithTitle:withAvatar:withUids:")
public Command<Integer> createGroup(String title, String avatarDescriptor, int[] uids) {
return modules.getGroupsModule().createGroup(title, avatarDescriptor, uids);
}
/**
* Leave group
*
* @param gid group's id
* @return Command for execution
*/
@Nullable
@ObjectiveCName("leaveGroupCommandWithGid:")
public Command<Boolean> leaveGroup(final int gid) {
return modules.getGroupsModule().leaveGroup(gid);
}
/**
* Adding member to group
*
* @param gid group's id
* @param uid user's id
* @return Command for execution
*/
@Nullable
@ObjectiveCName("inviteMemberCommandWithGid:withUid:")
public Command<Boolean> inviteMember(int gid, int uid) {
return modules.getGroupsModule().addMemberToGroup(gid, uid);
}
/**
* Kick member from group
*
* @param gid group's id
* @param uid user's id
* @return Command for execution
*/
@Nullable
@ObjectiveCName("kickMemberCommandWithGid:withUid:")
public Command<Boolean> kickMember(int gid, int uid) {
return modules.getGroupsModule().kickMember(gid, uid);
}
/**
* Request invite link for group
*
* @param gid group's id
* @return Command for execution
*/
@Nullable
@ObjectiveCName("requestInviteLinkCommandWithGid:")
public Command<String> requestInviteLink(int gid) {
return modules.getGroupsModule().requestInviteLink(gid);
}
/**
* Revoke invite link for group
*
* @param gid group's id
* @return Command for execution
*/
@Nullable
@ObjectiveCName("requestRevokeLinkCommandWithGid:")
public Command<String> revokeInviteLink(int gid) {
return modules.getGroupsModule().requestRevokeLink(gid);
}
/**
* Join group using invite link
*
* @param url invite link
* @return Command for execution
*/
@Nullable
@ObjectiveCName("joinGroupViaLinkCommandWithUrl:")
public Command<Integer> joinGroupViaLink(String url) {
return modules.getGroupsModule().joinGroupViaLink(url);
}
/**
* Join public group
*
* @param gid group's id
* @param accessHash group's accessHash
* @return Command for execution
*/
@Nullable
@ObjectiveCName("joinPublicGroupCommandWithGig:withAccessHash:")
public Command<Integer> joinPublicGroup(int gid, long accessHash) {
return modules.getGroupsModule().joinPublicGroup(gid, accessHash);
}
/**
* Listing public groups
*
* @return Command for execution
*/
@Nullable
@ObjectiveCName("listPublicGroups")
public Command<List<PublicGroup>> listPublicGroups() {
return modules.getGroupsModule().listPublicGroups();
}
/**
* Request integration token for group
*
* @param gid group's id
* @return Command for execution
*/
@Nullable
@ObjectiveCName("requestIntegrationTokenCommandWithGid:")
public Command<String> requestIntegrationToken(int gid) {
return modules.getGroupsModule().requestIntegrationToken(gid);
}
/**
* Revoke get integration token for group
*
* @param gid group's id
* @return Command for execution
*/
@Nullable
@ObjectiveCName("revokeIntegrationTokenCommandWithGid:")
public Command<String> revokeIntegrationToken(int gid) {
return modules.getGroupsModule().revokeIntegrationToken(gid);
}
//////////////////////////////////////
// Contact operations
//////////////////////////////////////
/**
* Remove user from contact's list
*
* @param uid user's id
* @return Command for execution
*/
@Nullable
@ObjectiveCName("removeContactCommandWithUid:")
public Command<Boolean> removeContact(int uid) {
return modules.getContactsModule().removeContact(uid);
}
/**
* Add contact to contact's list
*
* @param uid user's id
* @return Command for execution
*/
@Nullable
@ObjectiveCName("addContactCommandWithUid:")
public Command<Boolean> addContact(int uid) {
return modules.getContactsModule().addContact(uid);
}
/**
* Find Users
*
* @param query query for search
* @return Command for execution
*/
@NotNull
@ObjectiveCName("findUsersCommandWithQuery:")
public Command<UserVM[]> findUsers(String query) {
return modules.getContactsModule().findUsers(query);
}
/**
* Bind File View Model
*
* @param fileReference reference to file
* @param isAutoStart automatically start download
* @param callback View Model file state callback
* @return File View Model
*/
@NotNull
@ObjectiveCName("bindFileWithReference:autoStart:withCallback:")
public FileVM bindFile(FileReference fileReference, boolean isAutoStart, FileVMCallback callback) {
return new FileVM(fileReference, isAutoStart, modules, callback);
}
/**
* Bind Uploading File View Model
*
* @param rid randomId of uploading file
* @param callback View Model file state callback
* @return Upload File View Model
*/
@NotNull
@ObjectiveCName("bindUploadWithRid:withCallback:")
public UploadFileVM bindUpload(long rid, UploadFileVMCallback callback) {
return new UploadFileVM(rid, callback, modules);
}
/**
* Raw Bind File
*
* @param fileReference reference to file
* @param isAutoStart automatically start download
* @param callback file state callback
*/
@ObjectiveCName("bindRawFileWithReference:autoStart:withCallback:")
public void bindRawFile(FileReference fileReference, boolean isAutoStart, FileCallback callback) {
modules.getFilesModule().bindFile(fileReference, isAutoStart, callback);
}
/**
* Unbind Raw File
*
* @param fileId file id
* @param isAutoCancel automatically cancel download
* @param callback file state callback
*/
@ObjectiveCName("unbindRawFileWithFileId:autoCancel:withCallback:")
public void unbindRawFile(long fileId, boolean isAutoCancel, FileCallback callback) {
modules.getFilesModule().unbindFile(fileId, callback, isAutoCancel);
}
/**
* Raw Bind Upload File
*
* @param rid randomId of uploading file
* @param callback file state callback
*/
@ObjectiveCName("bindRawUploadFileWithRid:withCallback:")
public void bindRawUploadFile(long rid, UploadFileCallback callback) {
modules.getFilesModule().bindUploadFile(rid, callback);
}
/**
* Unbind Raw Upload File
*
* @param rid randomId of uploading file
* @param callback file state callback
*/
@ObjectiveCName("unbindRawUploadFileWithRid:withCallback:")
public void unbindRawUploadFile(long rid, UploadFileCallback callback) {
modules.getFilesModule().unbindUploadFile(rid, callback);
}
/**
* Request file state
*
* @param fileId file id
* @param callback file state callback
*/
@ObjectiveCName("requestStateWithFileId:withCallback:")
public void requestState(long fileId, final FileCallback callback) {
modules.getFilesModule().requestState(fileId, callback);
}
/**
* Request upload file state
*
* @param rid file's random id
* @param callback file state callback
*/
@ObjectiveCName("requestUploadStateWithRid:withCallback:")
public void requestUploadState(long rid, UploadFileCallback callback) {
modules.getFilesModule().requestUploadState(rid, callback);
}
/**
* Cancel file download
*
* @param fileId file's id
*/
@ObjectiveCName("cancelDownloadingWithFileId:")
public void cancelDownloading(long fileId) {
modules.getFilesModule().cancelDownloading(fileId);
}
/**
* Start file download
*
* @param reference file's reference
*/
@ObjectiveCName("startDownloadingWithReference:")
public void startDownloading(FileReference reference) {
modules.getFilesModule().startDownloading(reference);
}
/**
* Resume upload
*
* @param rid file's random id
*/
@ObjectiveCName("resumeUploadWithRid:")
public void resumeUpload(long rid) {
modules.getFilesModule().resumeUpload(rid);
}
/**
* Pause upload
*
* @param rid file's random id
*/
@ObjectiveCName("pauseUploadWithRid:")
public void pauseUpload(long rid) {
modules.getFilesModule().pauseUpload(rid);
}
/**
* Get downloaded file descriptor
*
* @param fileId file' id
* @return descriptor if file is downloaded
*/
@Deprecated
@Nullable
@ObjectiveCName("getDownloadedDescriptorWithFileId:")
public String getDownloadedDescriptor(long fileId) {
return modules.getFilesModule().getDownloadedDescriptor(fileId);
}
//////////////////////////////////////
// Settings
//////////////////////////////////////
/**
* Is in app conversation tones enabled
*
* @return is conversation tones enabled flag
*/
@ObjectiveCName("isConversationTonesEnabled")
public boolean isConversationTonesEnabled() {
return modules.getSettingsModule().isConversationTonesEnabled();
}
/**
* Change conversation tones enabled value
*
* @param val is conversation tones enabled
*/
@ObjectiveCName("changeConversationTonesEnabledWithValue:")
public void changeConversationTonesEnabled(boolean val) {
modules.getSettingsModule().changeConversationTonesEnabled(val);
}
/**
* Is notifications enabled setting
*
* @return is notifications enabled
*/
@ObjectiveCName("isNotificationsEnabled")
public boolean isNotificationsEnabled() {
return modules.getSettingsModule().isNotificationsEnabled();
}
/**
* Change notifications enabled value
*
* @param val is notifications enabled
*/
@ObjectiveCName("changeNotificationsEnabledWithValue:")
public void changeNotificationsEnabled(boolean val) {
modules.getSettingsModule().changeNotificationsEnabled(val);
}
/**
* Is notifications sounds enabled
*
* @return is notification sounds enabled
*/
@ObjectiveCName("isNotificationSoundEnabled")
public boolean isNotificationSoundEnabled() {
return modules.getSettingsModule().isNotificationSoundEnabled();
}
/**
* Change notification sounds enabled
*
* @param val is notification sounds enabled
*/
@ObjectiveCName("changeNotificationSoundEnabledWithValue:")
public void changeNotificationSoundEnabled(boolean val) {
modules.getSettingsModule().changeNotificationSoundEnabled(val);
}
/**
* Sound that used for notifications
*
* @return notification sound name
*/
@Nullable
@ObjectiveCName("getNotificationSound")
public String getNotificationSound() {
return modules.getSettingsModule().getNotificationSound();
}
/**
* Change sound that used for notifications
*
* @param sound notification sound name
*/
@ObjectiveCName("changeNotificationSoundWithSound:")
public void changeNotificationSound(String sound) {
modules.getSettingsModule().changeNotificationSound(sound);
}
/**
* Is notification vibration enabled
*
* @return is notification vibration enabled
*/
@ObjectiveCName("isNotificationVibrationEnabled")
public boolean isNotificationVibrationEnabled() {
return modules.getSettingsModule().isVibrationEnabled();
}
/**
* Change notification vibration enabled
*
* @param val is notification vibration enabled
*/
@ObjectiveCName("changeNotificationVibrationEnabledWithValue")
public void changeNotificationVibrationEnabled(boolean val) {
modules.getSettingsModule().changeNotificationVibrationEnabled(val);
}
/**
* Is displaying text in notifications enabled
*
* @return is displaying text in notifications enabled
*/
@ObjectiveCName("isShowNotificationsText")
public boolean isShowNotificationsText() {
return modules.getSettingsModule().isShowNotificationsText();
}
/**
* Change displaying text in notifications enabled
*
* @param val is displaying text in notifications enabled
*/
@ObjectiveCName("changeShowNotificationTextEnabledWithValue:")
public void changeShowNotificationTextEnabled(boolean val) {
modules.getSettingsModule().changeShowNotificationTextEnabled(val);
}
/**
* Is send by enter enabled. Useful for android and web.
*
* @return is send by enter enabled
*/
@ObjectiveCName("isSendByEnterEnabled")
public boolean isSendByEnterEnabled() {
return modules.getSettingsModule().isSendByEnterEnabled();
}
/**
* Change if send by enter enabled
*
* @param val is send by enter enabled
*/
@ObjectiveCName("changeSendByEnterWithValue:")
public void changeSendByEnter(boolean val) {
modules.getSettingsModule().changeSendByEnter(val);
}
/**
* Is markdown enabled.
*
* @return is markdown enabled
*/
@ObjectiveCName("isMarkdownEnabled")
public boolean isMarkdownEnabled() {
return modules.getSettingsModule().isMarkdownEnabled();
}
/**
* Change if markdown enabled
*
* @param val is markdown enabled
*/
@ObjectiveCName("changeMarkdownWithValue:")
public void changeMarkdown(boolean val) {
modules.getSettingsModule().changeMarkdown(val);
}
/**
* Is notifications enabled for peer
*
* @param peer destination peer
* @return is notifications enabled
*/
@ObjectiveCName("isNotificationsEnabledWithPeer:")
public boolean isNotificationsEnabled(Peer peer) {
return modules.getSettingsModule().isNotificationsEnabled(peer);
}
/**
* Change if notifications enabled for peer
*
* @param peer destination peer
* @param val is notifications enabled
*/
@ObjectiveCName("changeNotificationsEnabledWithPeer:withValue:")
public void changeNotificationsEnabled(Peer peer, boolean val) {
modules.getSettingsModule().changeNotificationsEnabled(peer, val);
}
/**
* Is in-app notifications enabled
*
* @return is notifications enabled
*/
@ObjectiveCName("isInAppNotificationsEnabled")
public boolean isInAppNotificationsEnabled() {
return modules.getSettingsModule().isInAppEnabled();
}
/**
* Change in-app notifications enable value
*
* @param val is notifications enabled
*/
@ObjectiveCName("changeInAppNotificationsEnabledWithValue:")
public void changeInAppNotificationsEnabled(boolean val) {
modules.getSettingsModule().changeInAppEnabled(val);
}
/**
* Is in-app notifications sound enabled
*
* @return is notifications sound enabled
*/
@ObjectiveCName("isInAppNotificationSoundEnabled")
public boolean isInAppNotificationSoundEnabled() {
return modules.getSettingsModule().isInAppSoundEnabled();
}
/**
* Change in-app notifications sound enabled value
*
* @param val is notifications sound enabled
*/
@ObjectiveCName("changeInAppNotificationSoundEnabledWithValue:")
public void changeInAppNotificationSoundEnabled(boolean val) {
modules.getSettingsModule().changeInAppSoundEnabled(val);
}
/**
* Is in-app notification vibration enabled
*
* @return is notifications vibration enabled
*/
@ObjectiveCName("isInAppNotificationVibrationEnabled")
public boolean isInAppNotificationVibrationEnabled() {
return modules.getSettingsModule().isInAppVibrationEnabled();
}
/**
* Change in-app notifications vibration enabled value
*
* @param val is notifications vibration enabled
*/
@ObjectiveCName("changeInAppNotificationVibrationEnabledWithValue:")
public void changeInAppNotificationVibrationEnabled(boolean val) {
modules.getSettingsModule().changeInAppVibrationEnabled(val);
}
/**
* Is Group Notifications Enabled
*
* @return is group notifications enabled
*/
@ObjectiveCName("isGroupNotificationsEnabled")
public boolean isGroupNotificationsEnabled() {
return modules.getSettingsModule().isGroupNotificationsEnabled();
}
/**
* Change group notifications enabled
*
* @param val is group notifications enabled
*/
@ObjectiveCName("changeGroupNotificationsEnabled:")
public void changeGroupNotificationsEnabled(boolean val) {
modules.getSettingsModule().changeGroupNotificationsEnabled(val);
}
/**
* Is Group Notifications only for mentions enabled
*
* @return val is group notifications only for mentions
*/
@ObjectiveCName("isGroupNotificationsOnlyMentionsEnabled")
public boolean isGroupNotificationsOnlyMentionsEnabled() {
return modules.getSettingsModule().isGroupNotificationsOnlyMentionsEnabled();
}
/**
* Change group notifications only for mentions enabled
*
* @param val is group notifications only for mentions
*/
@ObjectiveCName("changeGroupNotificationsOnlyMentionsEnabled:")
public void changeGroupNotificationsOnlyMentionsEnabled(boolean val) {
modules.getSettingsModule().changeGroupNotificationsOnlyMentionsEnabled(val);
}
/**
* Is Hint about contact rename shown to user and automatically mark as shown if not.
*
* @return is hint already shown
*/
@ObjectiveCName("isRenameHintShown")
public boolean isRenameHintShown() {
return modules.getSettingsModule().isRenameHintShown();
}
//////////////////////////////////////
// Security
//////////////////////////////////////
/**
* Loading active sessions
*
* @return Command for execution
*/
@Nullable
@ObjectiveCName("loadSessionsCommand")
public Command<List<ApiAuthSession>> loadSessions() {
return modules.getSecurityModule().loadSessions();
}
/**
* Terminate all other sessions
*
* @return Command for execution
*/
@Nullable
@ObjectiveCName("terminateAllSessionsCommand")
public Command<Boolean> terminateAllSessions() {
return modules.getSecurityModule().terminateAllSessions();
}
/**
* Terminate active session
*
* @param id session id
* @return Command for execution
*/
@Nullable
@ObjectiveCName("terminateSessionCommandWithId:")
public Command<Boolean> terminateSession(int id) {
return modules.getSecurityModule().terminateSession(id);
}
//////////////////////////////////////
// User Tracking
//////////////////////////////////////
/**
* Track phone number authentication screen
*/
@ObjectiveCName("trackAuthPhoneOpen")
public void trackAuthPhoneOpen() {
modules.getAnalyticsModule().trackAuthPhoneOpen();
}
/**
* Track pick country open
*/
@ObjectiveCName("trackAuthCountryOpen")
public void trackAuthCountryOpen() {
modules.getAnalyticsModule().trackAuthCountryOpen();
}
/**
* Track pick country closed
*/
@ObjectiveCName("trackAuthCountryClosed")
public void trackAuthCountryClosed() {
modules.getAnalyticsModule().trackAuthCountryClosed();
}
/**
* Track country picked
*/
@ObjectiveCName("trackAuthCountryPickedWithCountry:")
public void trackAuthCountryPicked(String country) {
modules.getAnalyticsModule().trackAuthCountryPicked(country);
}
/**
* Track auth phone typing
*/
@ObjectiveCName("trackAuthPhoneTypeWithValue:")
public void trackAuthPhoneType(String newValue) {
modules.getAnalyticsModule().trackAuthPhoneType(newValue);
}
/**
* Tack opening why screen
*/
@ObjectiveCName("trackAuthPhoneInfoOpen")
public void trackAuthPhoneInfoOpen() {
modules.getAnalyticsModule().trackAuthPhoneInfoOpen();
}
/**
* Track request code tap
*/
@ObjectiveCName("trackCodeRequest")
public void trackCodeRequest() {
modules.getAnalyticsModule().trackCodeRequest();
}
@ObjectiveCName("trackAuthCodeTypeWithValue:")
public void trackAuthCodeType(String newValue) {
modules.getAnalyticsModule().trackAuthCodeType(newValue);
}
@ObjectiveCName("trackBackPressed")
public void trackBackPressed() {
modules.getAnalyticsModule().trackBackPressed();
}
@ObjectiveCName("trackUpPressed")
public void trackUpPressed() {
modules.getAnalyticsModule().trackUpPressed();
}
@ObjectiveCName("trackAuthCodeWrongNumber")
public void trackAuthCodeWrongNumber() {
modules.getAnalyticsModule().trackAuthCodeWrongNumber();
}
@ObjectiveCName("trackAuthCodeWrongNumberCancel")
public void trackAuthCodeWrongNumberCancel() {
modules.getAnalyticsModule().trackAuthCodeWrongNumberCancel();
}
@ObjectiveCName("trackAuthCodeWrongNumberChange")
public void trackAuthCodeWrongNumberChange() {
modules.getAnalyticsModule().trackAuthCodeWrongNumberChange();
}
@ObjectiveCName("trackAuthCodeOpen")
public void trackAuthCodeOpen() {
modules.getAnalyticsModule().trackAuthCodeOpen();
}
@ObjectiveCName("trackAuthCodeClosed")
public void trackAuthCodeClosed() {
modules.getAnalyticsModule().trackAuthCodeClosed();
}
// Auth signup
@ObjectiveCName("trackAuthSignupOpen")
public void trackAuthSignupOpen() {
modules.getAnalyticsModule().trackAuthSignupOpen();
}
@ObjectiveCName("trackAuthSignupClosed")
public void trackAuthSignupClosed() {
modules.getAnalyticsModule().trackAuthSignupClosed();
}
@ObjectiveCName("trackAuthSignupNameTypeWithValue:")
public void trackAuthSignupNameType(String newValue) {
modules.getAnalyticsModule().trackAuthSignupClosedNameType(newValue);
}
@ObjectiveCName("trackAuthSignupPressedAvatar")
public void trackAuthSignupPressedAvatar() {
modules.getAnalyticsModule().trackAuthSignupPressedAvatar();
}
@ObjectiveCName("trackAuthSignupAvatarPicked")
public void trackAuthSignupAvatarPicked() {
modules.getAnalyticsModule().trackAuthSignupAvatarPicked();
}
@ObjectiveCName("trackAuthSignupAvatarDeleted")
public void trackAuthSignupAvatarDeleted() {
modules.getAnalyticsModule().trackAuthSignupAvatarDeleted();
}
@ObjectiveCName("trackAuthSignupAvatarCanelled")
public void trackAuthSignupAvatarCanelled() {
modules.getAnalyticsModule().trackAuthSignupAvatarCanelled();
}
// Auth success
@ObjectiveCName("trackAuthSuccess")
public void trackAuthSuccess() {
modules.getAnalyticsModule().trackAuthSuccess();
}
// Main screens
@ObjectiveCName("trackDialogsOpen")
public void trackDialogsOpen() {
modules.getAnalyticsModule().trackDialogsOpen();
}
@ObjectiveCName("trackDialogsClosed")
public void trackDialogsClosed() {
modules.getAnalyticsModule().trackDialogsClosed();
}
@ObjectiveCName("trackContactsOpen")
public void trackContactsOpen() {
modules.getAnalyticsModule().trackContactsOpen();
}
@ObjectiveCName("trackContactsClosed")
public void trackContactsClosed() {
modules.getAnalyticsModule().trackContactsClosed();
}
@ObjectiveCName("trackMainScreensOpen")
public void trackMainScreensOpen() {
modules.getAnalyticsModule().trackMainScreensOpen();
}
@ObjectiveCName("trackMainScreensClosed")
public void trackMainScreensClosed() {
modules.getAnalyticsModule().trackMainScreensClosed();
}
@ObjectiveCName("trackOwnProfileOpen")
public void trackOwnProfileOpen() {
modules.getAnalyticsModule().trackOwnProfileOpen();
}
@ObjectiveCName("trackOwnProfileClosed")
public void trackOwnProfileClosed() {
modules.getAnalyticsModule().trackOwnProfileClosed();
}
// Track message send
@ObjectiveCName("trackTextSendWithPeer:")
public void trackTextSend(Peer peer) {
modules.getAnalyticsModule().trackTextSend(peer);
}
@ObjectiveCName("trackPhotoSendWithPeer:")
public void trackPhotoSend(Peer peer) {
modules.getAnalyticsModule().trackPhotoSend(peer);
}
@ObjectiveCName("trackVideoSendWithPeer:")
public void trackVideoSend(Peer peer) {
modules.getAnalyticsModule().trackVideoSend(peer);
}
@ObjectiveCName("trackDocumentSendWithPeer:")
public void trackDocumentSend(Peer peer) {
modules.getAnalyticsModule().trackDocumentSend(peer);
}
/**
* Track sync action error
*
* @param action action key
* @param tag error tag
* @param message error message that shown to user
*/
@ObjectiveCName("trackActionError:withTag:withMessage:")
public void trackActionError(String action, String tag, String message) {
modules.getAnalyticsModule().trackActionError(action, tag, message);
}
/**
* Track sync action success
*
* @param action action key
*/
@ObjectiveCName("trackActionSuccess:")
public void trackActionSuccess(String action) {
modules.getAnalyticsModule().trackActionSuccess(action);
}
/**
* Track sync action try again
*
* @param action action key
*/
@ObjectiveCName("trackActionTryAgain:")
public void trackActionTryAgain(String action) {
modules.getAnalyticsModule().trackActionTryAgain(action);
}
/**
* Track sync action cancel
*
* @param action action key
*/
@ObjectiveCName("trackActionCancel:")
public void trackActionCancel(String action) {
modules.getAnalyticsModule().trackActionCancel(action);
}
//////////////////////////////////////
// Tools and Tech
//////////////////////////////////////
/**
* Formatting texts for UI
*
* @return formatter engine
*/
@NotNull
@ObjectiveCName("getFormatter")
public I18nEngine getFormatter() {
return modules.getI18nModule();
}
/**
* Register google push
*
* @param projectId GCM project id
* @param token GCM token
*/
@ObjectiveCName("registerGooglePushWithProjectId:withToken:")
public void registerGooglePush(long projectId, String token) {
modules.getPushesModule().registerGooglePush(projectId, token);
}
/**
* Register apple push
*
* @param apnsId internal APNS cert key
* @param token APNS token
*/
@ObjectiveCName("registerApplePushWithApnsId:withToken:")
public void registerApplePush(int apnsId, String token) {
modules.getPushesModule().registerApplePush(apnsId, token);
}
/**
* Get preferences storage
*
* @return the Preferences
*/
@NotNull
@ObjectiveCName("getPreferences")
public PreferencesStorage getPreferences() {
return modules.getPreferences();
}
/**
* Executing external command
*
* @param request command request
* @param <T> return type
* @return Command
*/
@NotNull
@ObjectiveCName("executeExternalCommand:")
public <T extends Response> Command<T> executeExternalCommand(@NotNull Request<T> request) {
return modules.getExternalModule().externalMethod(request);
}
/**
* Force checking of connection
*/
@ObjectiveCName("forceNetworkCheck")
public void forceNetworkCheck() {
modules.getActorApi().forceNetworkCheck();
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.trino.client;
import java.util.Optional;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
public final class ProtocolHeaders
{
public static final ProtocolHeaders TRINO_HEADERS = new ProtocolHeaders("Trino");
private final String name;
private final String prefix;
public static ProtocolHeaders createProtocolHeaders(String name)
{
// canonicalize trino name
if (TRINO_HEADERS.getProtocolName().equalsIgnoreCase(name)) {
return TRINO_HEADERS;
}
return new ProtocolHeaders(name);
}
private ProtocolHeaders(String name)
{
requireNonNull(name, "name is null");
checkArgument(!name.isEmpty(), "name is empty");
this.name = name;
this.prefix = "X-" + name + "-";
}
public String getProtocolName()
{
return name;
}
public String requestUser()
{
return prefix + "User";
}
public String requestSource()
{
return prefix + "Source";
}
public String requestCatalog()
{
return prefix + "Catalog";
}
public String requestSchema()
{
return prefix + "Schema";
}
public String requestPath()
{
return prefix + "Path";
}
public String requestTimeZone()
{
return prefix + "Time-Zone";
}
public String requestLanguage()
{
return prefix + "Language";
}
public String requestTraceToken()
{
return prefix + "Trace-Token";
}
public String requestSession()
{
return prefix + "Session";
}
public String requestRole()
{
return prefix + "Role";
}
public String requestPreparedStatement()
{
return prefix + "Prepared-Statement";
}
public String requestTransactionId()
{
return prefix + "Transaction-Id";
}
public String requestClientInfo()
{
return prefix + "Client-Info";
}
public String requestClientTags()
{
return prefix + "Client-Tags";
}
public String requestClientCapabilities()
{
return prefix + "Client-Capabilities";
}
public String requestResourceEstimate()
{
return prefix + "Resource-Estimate";
}
public String requestExtraCredential()
{
return prefix + "Extra-Credential";
}
public String responseSetCatalog()
{
return prefix + "Set-Catalog";
}
public String responseSetSchema()
{
return prefix + "Set-Schema";
}
public String responseSetPath()
{
return prefix + "Set-Path";
}
public String responseSetSession()
{
return prefix + "Set-Session";
}
public String responseClearSession()
{
return prefix + "Clear-Session";
}
public String responseSetRole()
{
return prefix + "Set-Role";
}
public String responseAddedPrepare()
{
return prefix + "Added-Prepare";
}
public String responseDeallocatedPrepare()
{
return prefix + "Deallocated-Prepare";
}
public String responseStartedTransactionId()
{
return prefix + "Started-Transaction-Id";
}
public String responseClearTransactionId()
{
return prefix + "Clear-Transaction-Id";
}
public static ProtocolHeaders detectProtocol(Optional<String> alternateHeaderName, Set<String> headerNames)
throws ProtocolDetectionException
{
requireNonNull(alternateHeaderName, "alternateHeaderName is null");
requireNonNull(headerNames, "headerNames is null");
if (alternateHeaderName.isPresent() && !alternateHeaderName.get().equalsIgnoreCase("Trino")) {
if (headerNames.contains("X-" + alternateHeaderName.get() + "-User")) {
if (headerNames.contains("X-Trino-User")) {
throw new ProtocolDetectionException("Both Trino and " + alternateHeaderName.get() + " headers detected");
}
return createProtocolHeaders(alternateHeaderName.get());
}
}
return TRINO_HEADERS;
}
}
| |
/**
* Please modify this class to meet your needs
* This class is not complete
*/
package org.cagrid.gridgrouper.wsrf.stubs;
import java.util.logging.Logger;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;
/**
* This class was generated by Apache CXF 2.6.3
* 2013-05-13T14:22:39.135-04:00
* Generated source version: 2.6.3
*
*/
@WebService(
serviceName = "GridGrouperService",
portName = "GridGrouperPortTypePort",
targetNamespace = "http://cagrid.nci.nih.gov/GridGrouper/service",
wsdlLocation = "/schema/org/cagrid/gridgrouper/GridGrouper_service.wsdl",
endpointInterface = "org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType")
public class GridGrouperPortTypeImpl implements GridGrouperPortType {
private static final Logger LOG = Logger.getLogger(GridGrouperPortTypeImpl.class.getName());
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getMemberships(org.cagrid.gridgrouper.wsrf.stubs.GetMembershipsRequest parameters )*
*/
public GetMembershipsResponse getMemberships(GetMembershipsRequest parameters) throws GroupNotFoundFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage {
LOG.info("Executing operation getMemberships");
System.out.println(parameters);
try {
GetMembershipsResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GroupNotFoundFaultFaultMessage("GroupNotFoundFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getSubjectsWithStemPrivilege(org.cagrid.gridgrouper.wsrf.stubs.GetSubjectsWithStemPrivilegeRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.GetSubjectsWithStemPrivilegeResponse getSubjectsWithStemPrivilege(GetSubjectsWithStemPrivilegeRequest parameters) throws GridGrouperRuntimeFaultFaultMessage , StemNotFoundFaultFaultMessage {
LOG.info("Executing operation getSubjectsWithStemPrivilege");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.GetSubjectsWithStemPrivilegeResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new StemNotFoundFaultFaultMessage("StemNotFoundFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#addMember(org.cagrid.gridgrouper.wsrf.stubs.AddMemberRequest parameters )*
*/
public AddMemberResponse addMember(AddMemberRequest parameters) throws InsufficientPrivilegeFaultFaultMessage , GroupNotFoundFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage , MemberAddFaultFaultMessage {
LOG.info("Executing operation addMember");
System.out.println(parameters);
try {
AddMemberResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new InsufficientPrivilegeFaultFaultMessage("InsufficientPrivilegeFaultFaultMessage...");
//throw new GroupNotFoundFaultFaultMessage("GroupNotFoundFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new MemberAddFaultFaultMessage("MemberAddFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getServiceSecurityMetadata(org.cagrid.gaards.security.servicesecurity.GetServiceSecurityMetadataRequest parameters )*
*/
public org.cagrid.gaards.security.servicesecurity.GetServiceSecurityMetadataResponse getServiceSecurityMetadata(org.cagrid.gaards.security.servicesecurity.GetServiceSecurityMetadataRequest parameters) {
LOG.info("Executing operation getServiceSecurityMetadata");
System.out.println(parameters);
try {
org.cagrid.gaards.security.servicesecurity.GetServiceSecurityMetadataResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#isMemberOf(org.cagrid.gridgrouper.wsrf.stubs.IsMemberOfRequest parameters )*
*/
public IsMemberOfResponse isMemberOf(IsMemberOfRequest parameters) throws GroupNotFoundFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage {
LOG.info("Executing operation isMemberOf");
System.out.println(parameters);
try {
IsMemberOfResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GroupNotFoundFaultFaultMessage("GroupNotFoundFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#revokeGroupPrivilege(org.cagrid.gridgrouper.wsrf.stubs.RevokeGroupPrivilegeRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.RevokeGroupPrivilegeResponse revokeGroupPrivilege(RevokeGroupPrivilegeRequest parameters) throws InsufficientPrivilegeFaultFaultMessage , GroupNotFoundFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage , RevokePrivilegeFaultFaultMessage , SchemaFaultFaultMessage {
LOG.info("Executing operation revokeGroupPrivilege");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.RevokeGroupPrivilegeResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new InsufficientPrivilegeFaultFaultMessage("InsufficientPrivilegeFaultFaultMessage...");
//throw new GroupNotFoundFaultFaultMessage("GroupNotFoundFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new RevokePrivilegeFaultFaultMessage("RevokePrivilegeFaultFaultMessage...");
//throw new SchemaFaultFaultMessage("SchemaFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#updateStem(org.cagrid.gridgrouper.wsrf.stubs.UpdateStemRequest parameters )*
*/
public UpdateStemResponse updateStem(UpdateStemRequest parameters) throws InsufficientPrivilegeFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage , StemModifyFaultFaultMessage {
LOG.info("Executing operation updateStem");
System.out.println(parameters);
try {
UpdateStemResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new InsufficientPrivilegeFaultFaultMessage("InsufficientPrivilegeFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new StemModifyFaultFaultMessage("StemModifyFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#grantGroupPrivilege(org.cagrid.gridgrouper.wsrf.stubs.GrantGroupPrivilegeRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.GrantGroupPrivilegeResponse grantGroupPrivilege(GrantGroupPrivilegeRequest parameters) throws GrantPrivilegeFaultFaultMessage , InsufficientPrivilegeFaultFaultMessage , GroupNotFoundFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage {
LOG.info("Executing operation grantGroupPrivilege");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.GrantGroupPrivilegeResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GrantPrivilegeFaultFaultMessage("GrantPrivilegeFaultFaultMessage...");
//throw new InsufficientPrivilegeFaultFaultMessage("InsufficientPrivilegeFaultFaultMessage...");
//throw new GroupNotFoundFaultFaultMessage("GroupNotFoundFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getMember(org.cagrid.gridgrouper.wsrf.stubs.GetMemberRequest parameters )*
*/
public GetMemberResponse getMember(GetMemberRequest parameters) throws InsufficientPrivilegeFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage {
LOG.info("Executing operation getMember");
System.out.println(parameters);
try {
GetMemberResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new InsufficientPrivilegeFaultFaultMessage("InsufficientPrivilegeFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#hasStemPrivilege(org.cagrid.gridgrouper.wsrf.stubs.HasStemPrivilegeRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.HasStemPrivilegeResponse hasStemPrivilege(HasStemPrivilegeRequest parameters) throws GridGrouperRuntimeFaultFaultMessage , StemNotFoundFaultFaultMessage {
LOG.info("Executing operation hasStemPrivilege");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.HasStemPrivilegeResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new StemNotFoundFaultFaultMessage("StemNotFoundFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getMembershipRequests(org.cagrid.gridgrouper.wsrf.stubs.GetMembershipRequestsRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.GetMembershipRequestsResponse getMembershipRequests(GetMembershipRequestsRequest parameters) {
LOG.info("Executing operation getMembershipRequests");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.GetMembershipRequestsResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#isMember(org.cagrid.gridgrouper.wsrf.stubs.IsMemberRequest parameters )*
*/
public IsMemberResponse isMember(IsMemberRequest parameters) throws GridGrouperRuntimeFaultFaultMessage {
LOG.info("Executing operation isMember");
System.out.println(parameters);
try {
IsMemberResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getChildStems(org.cagrid.gridgrouper.wsrf.stubs.GetChildStemsRequest parameters )*
*/
public GetChildStemsResponse getChildStems(GetChildStemsRequest parameters) throws GridGrouperRuntimeFaultFaultMessage , StemNotFoundFaultFaultMessage {
LOG.info("Executing operation getChildStems");
System.out.println(parameters);
try {
GetChildStemsResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new StemNotFoundFaultFaultMessage("StemNotFoundFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#addChildGroup(org.cagrid.gridgrouper.wsrf.stubs.AddChildGroupRequest parameters )*
*/
public AddChildGroupResponse addChildGroup(AddChildGroupRequest parameters) throws GroupAddFaultFaultMessage , InsufficientPrivilegeFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage {
LOG.info("Executing operation addChildGroup");
System.out.println(parameters);
try {
AddChildGroupResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GroupAddFaultFaultMessage("GroupAddFaultFaultMessage...");
//throw new InsufficientPrivilegeFaultFaultMessage("InsufficientPrivilegeFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getMembers(org.cagrid.gridgrouper.wsrf.stubs.GetMembersRequest parameters )*
*/
public GetMembersResponse getMembers(GetMembersRequest parameters) throws GroupNotFoundFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage {
LOG.info("Executing operation getMembers");
System.out.println(parameters);
try {
GetMembersResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GroupNotFoundFaultFaultMessage("GroupNotFoundFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getStem(org.cagrid.gridgrouper.wsrf.stubs.GetStemRequest parameters )*
*/
public GetStemResponse getStem(GetStemRequest parameters) throws GridGrouperRuntimeFaultFaultMessage , StemNotFoundFaultFaultMessage {
LOG.info("Executing operation getStem");
System.out.println(parameters);
try {
GetStemResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new StemNotFoundFaultFaultMessage("StemNotFoundFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#updateGroup(org.cagrid.gridgrouper.wsrf.stubs.UpdateGroupRequest parameters )*
*/
public UpdateGroupResponse updateGroup(UpdateGroupRequest parameters) throws GroupModifyFaultFaultMessage , InsufficientPrivilegeFaultFaultMessage , GroupNotFoundFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage {
LOG.info("Executing operation updateGroup");
System.out.println(parameters);
try {
UpdateGroupResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GroupModifyFaultFaultMessage("GroupModifyFaultFaultMessage...");
//throw new InsufficientPrivilegeFaultFaultMessage("InsufficientPrivilegeFaultFaultMessage...");
//throw new GroupNotFoundFaultFaultMessage("GroupNotFoundFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#deleteCompositeMember(org.cagrid.gridgrouper.wsrf.stubs.DeleteCompositeMemberRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.DeleteCompositeMemberResponse deleteCompositeMember(DeleteCompositeMemberRequest parameters) throws InsufficientPrivilegeFaultFaultMessage , GroupNotFoundFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage , MemberDeleteFaultFaultMessage {
LOG.info("Executing operation deleteCompositeMember");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.DeleteCompositeMemberResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new InsufficientPrivilegeFaultFaultMessage("InsufficientPrivilegeFaultFaultMessage...");
//throw new GroupNotFoundFaultFaultMessage("GroupNotFoundFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new MemberDeleteFaultFaultMessage("MemberDeleteFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#deleteStem(org.cagrid.gridgrouper.wsrf.stubs.DeleteStemRequest parameters )*
*/
public DeleteStemResponse deleteStem(DeleteStemRequest parameters) throws InsufficientPrivilegeFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage , StemNotFoundFaultFaultMessage , StemDeleteFaultFaultMessage {
LOG.info("Executing operation deleteStem");
System.out.println(parameters);
try {
DeleteStemResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new InsufficientPrivilegeFaultFaultMessage("InsufficientPrivilegeFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new StemNotFoundFaultFaultMessage("StemNotFoundFaultFaultMessage...");
//throw new StemDeleteFaultFaultMessage("StemDeleteFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getParentStem(org.cagrid.gridgrouper.wsrf.stubs.GetParentStemRequest parameters )*
*/
public GetParentStemResponse getParentStem(GetParentStemRequest parameters) throws GridGrouperRuntimeFaultFaultMessage , StemNotFoundFaultFaultMessage {
LOG.info("Executing operation getParentStem");
System.out.println(parameters);
try {
GetParentStemResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new StemNotFoundFaultFaultMessage("StemNotFoundFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getResourceProperty(javax.xml.namespace.QName getResourcePropertyRequest )*
*/
public org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01.GetResourcePropertyResponse getResourceProperty(javax.xml.namespace.QName getResourcePropertyRequest) throws org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.ResourceUnknownFault , org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.InvalidResourcePropertyQNameFault {
LOG.info("Executing operation getResourceProperty");
System.out.println(getResourcePropertyRequest);
try {
org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01.GetResourcePropertyResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.ResourceUnknownFault("ResourceUnknownFault...");
//throw new org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.InvalidResourcePropertyQNameFault("InvalidResourcePropertyQNameFault...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getStemPrivileges(org.cagrid.gridgrouper.wsrf.stubs.GetStemPrivilegesRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.GetStemPrivilegesResponse getStemPrivileges(GetStemPrivilegesRequest parameters) throws GridGrouperRuntimeFaultFaultMessage , StemNotFoundFaultFaultMessage {
LOG.info("Executing operation getStemPrivileges");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.GetStemPrivilegesResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new StemNotFoundFaultFaultMessage("StemNotFoundFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getMembersGroups(org.cagrid.gridgrouper.wsrf.stubs.GetMembersGroupsRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.GetMembersGroupsResponse getMembersGroups(GetMembersGroupsRequest parameters) throws InsufficientPrivilegeFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage {
LOG.info("Executing operation getMembersGroups");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.GetMembersGroupsResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new InsufficientPrivilegeFaultFaultMessage("InsufficientPrivilegeFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#addMembershipRequest(org.cagrid.gridgrouper.wsrf.stubs.AddMembershipRequestRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.AddMembershipRequestResponse addMembershipRequest(AddMembershipRequestRequest parameters) {
LOG.info("Executing operation addMembershipRequest");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.AddMembershipRequestResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getSubjectsWithGroupPrivilege(org.cagrid.gridgrouper.wsrf.stubs.GetSubjectsWithGroupPrivilegeRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.GetSubjectsWithGroupPrivilegeResponse getSubjectsWithGroupPrivilege(GetSubjectsWithGroupPrivilegeRequest parameters) throws GroupNotFoundFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage {
LOG.info("Executing operation getSubjectsWithGroupPrivilege");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.GetSubjectsWithGroupPrivilegeResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GroupNotFoundFaultFaultMessage("GroupNotFoundFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getGroupPrivileges(org.cagrid.gridgrouper.wsrf.stubs.GetGroupPrivilegesRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.GetGroupPrivilegesResponse getGroupPrivileges(GetGroupPrivilegesRequest parameters) throws GroupNotFoundFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage {
LOG.info("Executing operation getGroupPrivileges");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.GetGroupPrivilegesResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GroupNotFoundFaultFaultMessage("GroupNotFoundFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#queryResourceProperties(org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01.QueryResourceProperties queryResourcePropertiesRequest )*
*/
public org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01.QueryResourcePropertiesResponse queryResourceProperties(org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01.QueryResourceProperties queryResourcePropertiesRequest) throws org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.ResourceUnknownFault , org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.InvalidQueryExpressionFault , org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.QueryEvaluationErrorFault , org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.InvalidResourcePropertyQNameFault , org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.UnknownQueryExpressionDialectFault {
LOG.info("Executing operation queryResourceProperties");
System.out.println(queryResourcePropertiesRequest);
try {
org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01.QueryResourcePropertiesResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.ResourceUnknownFault("ResourceUnknownFault...");
//throw new org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.InvalidQueryExpressionFault("InvalidQueryExpressionFault...");
//throw new org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.QueryEvaluationErrorFault("QueryEvaluationErrorFault...");
//throw new org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.InvalidResourcePropertyQNameFault("InvalidResourcePropertyQNameFault...");
//throw new org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.UnknownQueryExpressionDialectFault("UnknownQueryExpressionDialectFault...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#deleteMember(org.cagrid.gridgrouper.wsrf.stubs.DeleteMemberRequest parameters )*
*/
public DeleteMemberResponse deleteMember(DeleteMemberRequest parameters) throws InsufficientPrivilegeFaultFaultMessage , GroupNotFoundFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage , MemberDeleteFaultFaultMessage {
LOG.info("Executing operation deleteMember");
System.out.println(parameters);
try {
DeleteMemberResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new InsufficientPrivilegeFaultFaultMessage("InsufficientPrivilegeFaultFaultMessage...");
//throw new GroupNotFoundFaultFaultMessage("GroupNotFoundFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new MemberDeleteFaultFaultMessage("MemberDeleteFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#grantStemPrivilege(org.cagrid.gridgrouper.wsrf.stubs.GrantStemPrivilegeRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.GrantStemPrivilegeResponse grantStemPrivilege(GrantStemPrivilegeRequest parameters) throws GrantPrivilegeFaultFaultMessage , InsufficientPrivilegeFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage , StemNotFoundFaultFaultMessage , SchemaFaultFaultMessage {
LOG.info("Executing operation grantStemPrivilege");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.GrantStemPrivilegeResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GrantPrivilegeFaultFaultMessage("GrantPrivilegeFaultFaultMessage...");
//throw new InsufficientPrivilegeFaultFaultMessage("InsufficientPrivilegeFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new StemNotFoundFaultFaultMessage("StemNotFoundFaultFaultMessage...");
//throw new SchemaFaultFaultMessage("SchemaFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#disableMembershipRequests(org.cagrid.gridgrouper.wsrf.stubs.DisableMembershipRequestsRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.DisableMembershipRequestsResponse disableMembershipRequests(DisableMembershipRequestsRequest parameters) {
LOG.info("Executing operation disableMembershipRequests");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.DisableMembershipRequestsResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#enableMembershipRequests(org.cagrid.gridgrouper.wsrf.stubs.EnableMembershipRequestsRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.EnableMembershipRequestsResponse enableMembershipRequests(EnableMembershipRequestsRequest parameters) {
LOG.info("Executing operation enableMembershipRequests");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.EnableMembershipRequestsResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#deleteGroup(org.cagrid.gridgrouper.wsrf.stubs.DeleteGroupRequest parameters )*
*/
public DeleteGroupResponse deleteGroup(DeleteGroupRequest parameters) throws InsufficientPrivilegeFaultFaultMessage , GroupNotFoundFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage , GroupDeleteFaultFaultMessage {
LOG.info("Executing operation deleteGroup");
System.out.println(parameters);
try {
DeleteGroupResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new InsufficientPrivilegeFaultFaultMessage("InsufficientPrivilegeFaultFaultMessage...");
//throw new GroupNotFoundFaultFaultMessage("GroupNotFoundFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new GroupDeleteFaultFaultMessage("GroupDeleteFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#isMembershipRequestEnabled(org.cagrid.gridgrouper.wsrf.stubs.IsMembershipRequestEnabledRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.IsMembershipRequestEnabledResponse isMembershipRequestEnabled(IsMembershipRequestEnabledRequest parameters) {
LOG.info("Executing operation isMembershipRequestEnabled");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.IsMembershipRequestEnabledResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#revokeStemPrivilege(org.cagrid.gridgrouper.wsrf.stubs.RevokeStemPrivilegeRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.RevokeStemPrivilegeResponse revokeStemPrivilege(RevokeStemPrivilegeRequest parameters) throws InsufficientPrivilegeFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage , RevokePrivilegeFaultFaultMessage , StemNotFoundFaultFaultMessage , SchemaFaultFaultMessage {
LOG.info("Executing operation revokeStemPrivilege");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.RevokeStemPrivilegeResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new InsufficientPrivilegeFaultFaultMessage("InsufficientPrivilegeFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new RevokePrivilegeFaultFaultMessage("RevokePrivilegeFaultFaultMessage...");
//throw new StemNotFoundFaultFaultMessage("StemNotFoundFaultFaultMessage...");
//throw new SchemaFaultFaultMessage("SchemaFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getMultipleResourceProperties(org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01.GetMultipleResourceProperties getMultipleResourcePropertiesRequest )*
*/
public org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01.GetMultipleResourcePropertiesResponse getMultipleResourceProperties(org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01.GetMultipleResourceProperties getMultipleResourcePropertiesRequest) throws org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.ResourceUnknownFault , org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.InvalidResourcePropertyQNameFault {
LOG.info("Executing operation getMultipleResourceProperties");
System.out.println(getMultipleResourcePropertiesRequest);
try {
org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01.GetMultipleResourcePropertiesResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.ResourceUnknownFault("ResourceUnknownFault...");
//throw new org.oasis_open.docs.wsrf._2004._06.wsrf_ws_resourceproperties_1_2_draft_01_wsdl.InvalidResourcePropertyQNameFault("InvalidResourcePropertyQNameFault...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getChildGroups(org.cagrid.gridgrouper.wsrf.stubs.GetChildGroupsRequest parameters )*
*/
public GetChildGroupsResponse getChildGroups(GetChildGroupsRequest parameters) throws GridGrouperRuntimeFaultFaultMessage , StemNotFoundFaultFaultMessage {
LOG.info("Executing operation getChildGroups");
System.out.println(parameters);
try {
GetChildGroupsResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new StemNotFoundFaultFaultMessage("StemNotFoundFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#updateMembershipRequest(org.cagrid.gridgrouper.wsrf.stubs.UpdateMembershipRequestRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.UpdateMembershipRequestResponse updateMembershipRequest(UpdateMembershipRequestRequest parameters) {
LOG.info("Executing operation updateMembershipRequest");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.UpdateMembershipRequestResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#addChildStem(org.cagrid.gridgrouper.wsrf.stubs.AddChildStemRequest parameters )*
*/
public AddChildStemResponse addChildStem(AddChildStemRequest parameters) throws StemAddFaultFaultMessage , InsufficientPrivilegeFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage , StemNotFoundFaultFaultMessage {
LOG.info("Executing operation addChildStem");
System.out.println(parameters);
try {
AddChildStemResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new StemAddFaultFaultMessage("StemAddFaultFaultMessage...");
//throw new InsufficientPrivilegeFaultFaultMessage("InsufficientPrivilegeFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new StemNotFoundFaultFaultMessage("StemNotFoundFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#getGroup(org.cagrid.gridgrouper.wsrf.stubs.GetGroupRequest parameters )*
*/
public GetGroupResponse getGroup(GetGroupRequest parameters) throws GroupNotFoundFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage {
LOG.info("Executing operation getGroup");
System.out.println(parameters);
try {
GetGroupResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GroupNotFoundFaultFaultMessage("GroupNotFoundFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#addCompositeMember(org.cagrid.gridgrouper.wsrf.stubs.AddCompositeMemberRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.AddCompositeMemberResponse addCompositeMember(AddCompositeMemberRequest parameters) throws InsufficientPrivilegeFaultFaultMessage , GroupNotFoundFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage , MemberAddFaultFaultMessage {
LOG.info("Executing operation addCompositeMember");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.AddCompositeMemberResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new InsufficientPrivilegeFaultFaultMessage("InsufficientPrivilegeFaultFaultMessage...");
//throw new GroupNotFoundFaultFaultMessage("GroupNotFoundFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
//throw new MemberAddFaultFaultMessage("MemberAddFaultFaultMessage...");
}
/* (non-Javadoc)
* @see org.cagrid.gridgrouper.wsrf.stubs.GridGrouperPortType#hasGroupPrivilege(org.cagrid.gridgrouper.wsrf.stubs.HasGroupPrivilegeRequest parameters )*
*/
public org.cagrid.gridgrouper.wsrf.stubs.HasGroupPrivilegeResponse hasGroupPrivilege(HasGroupPrivilegeRequest parameters) throws GroupNotFoundFaultFaultMessage , GridGrouperRuntimeFaultFaultMessage {
LOG.info("Executing operation hasGroupPrivilege");
System.out.println(parameters);
try {
org.cagrid.gridgrouper.wsrf.stubs.HasGroupPrivilegeResponse _return = null;
return _return;
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
//throw new GroupNotFoundFaultFaultMessage("GroupNotFoundFaultFaultMessage...");
//throw new GridGrouperRuntimeFaultFaultMessage("GridGrouperRuntimeFaultFaultMessage...");
}
}
| |
package test;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.Iterator;
import prefuse.action.layout.Layout;
import prefuse.data.Graph;
import prefuse.data.Schema;
import prefuse.data.tuple.TupleSet;
import prefuse.util.PrefuseLib;
import prefuse.util.force.DragForce;
import prefuse.util.force.ForceItem;
import prefuse.util.force.ForceSimulator;
import prefuse.util.force.NBodyForce;
import prefuse.util.force.SpringForce;
import prefuse.visual.EdgeItem;
import prefuse.visual.NodeItem;
import prefuse.visual.VisualItem;
/**
* <p>Layout that positions graph elements based on a physics simulation of
* interacting forces; by default, nodes repel each other, edges act as
* springs, and drag forces (similar to air resistance) are applied. This
* algorithm can be run for multiple iterations for a run-once layout
* computation or repeatedly run in an animated fashion for a dynamic and
* interactive layout.</p>
*
* <p>The running time of this layout algorithm is the greater of O(N log N)
* and O(E), where N is the number of nodes and E the number of edges.
* The addition of custom force calculation modules may, however, increase
* this value.</p>
*
* <p>The {@link prefuse.util.force.ForceSimulator} used to drive this layout
* can be set explicitly, allowing any number of custom force directed layouts
* to be created through the user's selection of included
* {@link prefuse.util.force.Force} components. Each node in the layout is
* mapped to a {@link prefuse.util.force.ForceItem} instance and each edge
* to a {@link prefuse.util.force.Spring} instance for storing the state
* of the simulation. See the {@link prefuse.util.force} package for more.</p>
*
* @author <a href="http://jheer.org">jeffrey heer</a>
*/
public class CodysFDR extends Layout {
private ForceSimulator m_fsim;
private long m_lasttime = -1L;
private long m_maxstep = 50L;
private boolean m_runonce;
private int m_iterations = 100;
private boolean m_enforceBounds;
protected transient VisualItem referrer;
protected String m_nodeGroup;
protected String m_edgeGroup;
/**
* Create a new ForceDirectedLayout. By default, this layout will not
* restrict the layout to the layout bounds and will assume it is being
* run in animated (rather than run-once) fashion.
* @param graph the data group to layout. Must resolve to a Graph instance.
*/
public CodysFDR(String graph)
{
this(graph, false, false);
}
/**
* Create a new ForceDirectedLayout. The layout will assume it is being
* run in animated (rather than run-once) fashion.
* @param group the data group to layout. Must resolve to a Graph instance.
* @param enforceBounds indicates whether or not the layout should require
* that all node placements stay within the layout bounds.
*/
public CodysFDR(String group, boolean enforceBounds)
{
this(group, enforceBounds, false);
}
/**
* Create a new ForceDirectedLayout.
* @param group the data group to layout. Must resolve to a Graph instance.
* @param enforceBounds indicates whether or not the layout should require
* that all node placements stay within the layout bounds.
* @param runonce indicates if the layout will be run in a run-once or
* animated fashion. In run-once mode, the layout will run for a set number
* of iterations when invoked. In animation mode, only one iteration of the
* layout is computed.
*/
public CodysFDR(String group,
boolean enforceBounds, boolean runonce)
{
super(group);
m_nodeGroup = PrefuseLib.getGroupName(group, Graph.NODES);
m_edgeGroup = PrefuseLib.getGroupName(group, Graph.EDGES);
m_enforceBounds = enforceBounds;
m_runonce = runonce;
m_fsim = new ForceSimulator();
m_fsim.addForce(new NBodyForce());
m_fsim.addForce(new SpringForce());
m_fsim.addForce(new DragForce());
}
/**
* Create a new ForceDirectedLayout. The layout will assume it is being
* run in animated (rather than run-once) fashion.
* @param group the data group to layout. Must resolve to a Graph instance.
* @param fsim the force simulator used to drive the layout computation
* @param enforceBounds indicates whether or not the layout should require
* that all node placements stay within the layout bounds.
*/
public CodysFDR(String group,
ForceSimulator fsim, boolean enforceBounds) {
this(group, fsim, enforceBounds, false);
}
/**
* Create a new ForceDirectedLayout.
* @param group the data group to layout. Must resolve to a Graph instance.
* @param fsim the force simulator used to drive the layout computation
* @param enforceBounds indicates whether or not the layout should require
* that all node placements stay within the layout bounds.
* @param runonce indicates if the layout will be run in a run-once or
* animated fashion. In run-once mode, the layout will run for a set number
* of iterations when invoked. In animation mode, only one iteration of the
* layout is computed.
*/
public CodysFDR(String group, ForceSimulator fsim,
boolean enforceBounds, boolean runonce)
{
super(group);
m_nodeGroup = PrefuseLib.getGroupName(group, Graph.NODES);
m_edgeGroup = PrefuseLib.getGroupName(group, Graph.EDGES);
m_enforceBounds = enforceBounds;
m_runonce = runonce;
m_fsim = fsim;
}
// ------------------------------------------------------------------------
/**
* Get the maximum timestep allowed for integrating node settings between
* runs of this layout. When computation times are longer than desired,
* and node positions are changing dramatically between animated frames,
* the max step time can be lowered to suppress node movement.
* @return the maximum timestep allowed for integrating between two
* layout steps.
*/
public long getMaxTimeStep() {
return m_maxstep;
}
/**
* Set the maximum timestep allowed for integrating node settings between
* runs of this layout. When computation times are longer than desired,
* and node positions are changing dramatically between animated frames,
* the max step time can be lowered to suppress node movement.
* @param maxstep the maximum timestep allowed for integrating between two
* layout steps
*/
public void setMaxTimeStep(long maxstep) {
this.m_maxstep = maxstep;
}
/**
* Get the force simulator driving this layout.
* @return the force simulator
*/
public ForceSimulator getForceSimulator() {
return m_fsim;
}
/**
* Set the force simulator driving this layout.
* @param fsim the force simulator
*/
public void setForceSimulator(ForceSimulator fsim) {
m_fsim = fsim;
}
/**
* Get the number of iterations to use when computing a layout in
* run-once mode.
* @return the number of layout iterations to run
*/
public int getIterations() {
return m_iterations;
}
/**
* Set the number of iterations to use when computing a layout in
* run-once mode.
* @param iter the number of layout iterations to run
*/
public void setIterations(int iter) {
if ( iter < 1 )
throw new IllegalArgumentException(
"Iterations must be a positive number!");
m_iterations = iter;
}
/**
* Explicitly sets the node and edge groups to use for this layout,
* overriding the group setting passed to the constructor.
* @param nodeGroup the node data group
* @param edgeGroup the edge data group
*/
public void setDataGroups(String nodeGroup, String edgeGroup) {
m_nodeGroup = nodeGroup;
m_edgeGroup = edgeGroup;
}
// ------------------------------------------------------------------------
/**
* @see prefuse.action.Action#run(double)
*/
public void run(double frac) {
// perform different actions if this is a run-once or
// run-continuously layout
if ( m_runonce ) {
Point2D anchor = getLayoutAnchor();
Iterator iter = m_vis.visibleItems(m_nodeGroup);
while ( iter.hasNext() ) {
VisualItem item = (NodeItem)iter.next();
item.setX(anchor.getX());
item.setY(anchor.getY());
}
m_fsim.clear();
long timestep = 1000L;
initSimulator(m_fsim);
for ( int i = 0; i < m_iterations; i++ ) {
// use an annealing schedule to set time step
timestep *= (1.0 - i/(double)m_iterations);
long step = timestep+50;
// run simulator
m_fsim.runSimulator(step);
// debugging output
// if (i % 10 == 0 ) {
// System.out.println("iter: "+i);
// }
}
updateNodePositions();
} else {
// get timestep
if ( m_lasttime == -1 )
m_lasttime = System.currentTimeMillis()-20;
long time = System.currentTimeMillis();
long timestep = Math.min(m_maxstep, time - m_lasttime);
m_lasttime = time;
// run force simulator
m_fsim.clear();
initSimulator(m_fsim);
m_fsim.runSimulator(timestep);
updateNodePositions();
}
if ( frac == 1.0 ) {
reset();
}
}
private void updateNodePositions() {
Rectangle2D bounds = getLayoutBounds();
double x1=0, x2=0, y1=0, y2=0;
if ( bounds != null ) {
x1 = bounds.getMinX(); y1 = bounds.getMinY();
x2 = bounds.getMaxX(); y2 = bounds.getMaxY();
}
// update positions
Iterator iter = m_vis.visibleItems(m_nodeGroup);
while ( iter.hasNext() ) {
VisualItem item = (VisualItem)iter.next();
ForceItem fitem = (ForceItem)item.get(FORCEITEM);
if ( item.isFixed() ) {
// clear any force computations
fitem.force[0] = 0.0f;
fitem.force[1] = 0.0f;
fitem.velocity[0] = 0.0f;
fitem.velocity[1] = 0.0f;
if ( Double.isNaN(item.getX()) ) {
setX(item, referrer, 0.0);
setY(item, referrer, 0.0);
}
continue;
}
double x = fitem.location[0];
double y = fitem.location[1];
if ( m_enforceBounds && bounds != null) {
Rectangle2D b = item.getBounds();
double hw = b.getWidth()/2;
double hh = b.getHeight()/2;
if ( x+hw > x2 ) x = x2-hw;
if ( x-hw < x1 ) x = x1+hw;
if ( y+hh > y2 ) y = y2-hh;
if ( y-hh < y1 ) y = y1+hh;
}
// set the actual position
setX(item, referrer, x);
setY(item, referrer, y);
}
}
/**
* Reset the force simulation state for all nodes processed
* by this layout.
*/
public void reset() {
Iterator iter = m_vis.visibleItems(m_nodeGroup);
while ( iter.hasNext() ) {
VisualItem item = (VisualItem)iter.next();
ForceItem fitem = (ForceItem)item.get(FORCEITEM);
if ( fitem != null ) {
fitem.location[0] = (float)item.getEndX();
fitem.location[1] = (float)item.getEndY();
fitem.force[0] = fitem.force[1] = 0;
fitem.velocity[0] = fitem.velocity[1] = 0;
}
}
m_lasttime = -1L;
}
/**
* Loads the simulator with all relevant force items and springs.
* @param fsim the force simulator driving this layout
*/
protected void initSimulator(ForceSimulator fsim) {
// make sure we have force items to work with
TupleSet ts = m_vis.getGroup(m_nodeGroup);
if ( ts == null ) return;
try {
ts.addColumns(FORCEITEM_SCHEMA);
} catch ( IllegalArgumentException iae ) { /* ignored */ }
float startX = (referrer == null ? 0f : (float)referrer.getX());
float startY = (referrer == null ? 0f : (float)referrer.getY());
startX = Float.isNaN(startX) ? 0f : startX;
startY = Float.isNaN(startY) ? 0f : startY;
Iterator iter = m_vis.visibleItems(m_nodeGroup);
while ( iter.hasNext() ) {
VisualItem item = (VisualItem)iter.next();
ForceItem fitem = (ForceItem)item.get(FORCEITEM);
fitem.mass = getMassValue(item);
double x = item.getEndX();
double y = item.getEndY();
fitem.location[0] = (Double.isNaN(x) ? startX : (float)x);
fitem.location[1] = (Double.isNaN(y) ? startY : (float)y);
fsim.addItem(fitem);
}
if ( m_edgeGroup != null ) {
iter = m_vis.visibleItems(m_edgeGroup);
while ( iter.hasNext() ) {
EdgeItem e = (EdgeItem)iter.next();
NodeItem n1 = e.getSourceItem();
ForceItem f1 = (ForceItem)n1.get(FORCEITEM);
NodeItem n2 = e.getTargetItem();
ForceItem f2 = (ForceItem)n2.get(FORCEITEM);
float coeff = getSpringCoefficient(e);
float slen = getSpringLength(e);
fsim.addSpring(f1, f2, (coeff>=0?coeff:-1.f), (slen>=0?slen:-1.f));
}
}
}
/**
* Get the mass value associated with the given node. Subclasses should
* override this method to perform custom mass assignment.
* @param n the node for which to compute the mass value
* @return the mass value for the node. By default, all items are given
* a mass value of 1.0.
*/
protected float getMassValue(VisualItem n) {
return 1.0f;
}
/**
* Get the spring length for the given edge. Subclasses should
* override this method to perform custom spring length assignment.
* @param e the edge for which to compute the spring length
* @return the spring length for the edge. A return value of
* -1 means to ignore this method and use the global default.
*/
protected float getSpringLength(EdgeItem e) {
return -1.f;
}
/**
* Get the spring coefficient for the given edge, which controls the
* tension or strength of the spring. Subclasses should
* override this method to perform custom spring tension assignment.
* @param e the edge for which to compute the spring coefficient.
* @return the spring coefficient for the edge. A return value of
* -1 means to ignore this method and use the global default.
*/
protected float getSpringCoefficient(EdgeItem e) {
return -1.f;
}
/**
* Get the referrer item to use to set x or y coordinates that are
* initialized to NaN.
* @return the referrer item.
* @see prefuse.util.PrefuseLib#setX(VisualItem, VisualItem, double)
* @see prefuse.util.PrefuseLib#setY(VisualItem, VisualItem, double)
*/
public VisualItem getReferrer() {
return referrer;
}
/**
* Set the referrer item to use to set x or y coordinates that are
* initialized to NaN.
* @param referrer the referrer item to use.
* @see prefuse.util.PrefuseLib#setX(VisualItem, VisualItem, double)
* @see prefuse.util.PrefuseLib#setY(VisualItem, VisualItem, double)
*/
public void setReferrer(VisualItem referrer) {
this.referrer = referrer;
}
// ------------------------------------------------------------------------
// ForceItem Schema Addition
/**
* The data field in which the parameters used by this layout are stored.
*/
public static final String FORCEITEM = "_forceItem";
/**
* The schema for the parameters used by this layout.
*/
public static final Schema FORCEITEM_SCHEMA = new Schema();
static {
FORCEITEM_SCHEMA.addColumn(FORCEITEM,
ForceItem.class,
new ForceItem());
}
} // end of class ForceDirectedLayout
| |
/*
* Artifactory is a binaries repository manager.
* Copyright (C) 2012 JFrog Ltd.
*
* Artifactory is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Artifactory 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Artifactory. If not, see <http://www.gnu.org/licenses/>.
*/
package org.artifactory.storage.db.security.service;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.artifactory.factory.InfoFactoryHolder;
import org.artifactory.security.AceInfo;
import org.artifactory.security.AclInfo;
import org.artifactory.security.GroupInfo;
import org.artifactory.security.MutableAceInfo;
import org.artifactory.security.MutableAclInfo;
import org.artifactory.security.MutablePermissionTargetInfo;
import org.artifactory.security.PermissionTargetInfo;
import org.artifactory.security.UserInfo;
import org.artifactory.storage.StorageException;
import org.artifactory.storage.db.DbService;
import org.artifactory.storage.db.security.dao.AclsDao;
import org.artifactory.storage.db.security.dao.PermissionTargetsDao;
import org.artifactory.storage.db.security.dao.UserGroupsDao;
import org.artifactory.storage.db.security.entity.Ace;
import org.artifactory.storage.db.security.entity.Acl;
import org.artifactory.storage.db.security.entity.Group;
import org.artifactory.storage.db.security.entity.PermissionTarget;
import org.artifactory.storage.db.security.entity.User;
import org.artifactory.storage.security.service.AclStoreService;
import org.artifactory.util.AlreadyExistsException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import static org.artifactory.security.ArtifactoryPermission.DEPLOY;
import static org.artifactory.security.ArtifactoryPermission.READ;
import static org.artifactory.security.PermissionTargetInfo.*;
/**
* Date: 9/3/12
* Time: 4:12 PM
*
* @author freds
*/
@Service
public class AclServiceImpl implements AclStoreService {
private static final Logger log = LoggerFactory.getLogger(AclServiceImpl.class);
@Autowired
private DbService dbService;
@Autowired
private AclsDao aclsDao;
@Autowired
private PermissionTargetsDao permTargetsDao;
@Autowired
private UserGroupsDao userGroupsDao;
private AclsCache aclsCache = new AclsCache(new AclCacheLoader());
@Override
public Collection<AclInfo> getAllAcls() {
return getAclsMap().values();
}
@Override
public void createAcl(AclInfo entity) {
try {
PermissionTargetInfo permTargetInfo = entity.getPermissionTarget();
PermissionTarget dbPermTarget = permTargetsDao.findPermissionTarget(permTargetInfo.getName());
if (dbPermTarget != null) {
throw new AlreadyExistsException("Could not create ACL. Permission target already exist: " +
permTargetInfo.getName());
}
dbPermTarget = new PermissionTarget(dbService.nextId(), permTargetInfo.getName(),
permTargetInfo.getIncludes(), permTargetInfo.getExcludes());
dbPermTarget.setRepoKeys(Sets.newHashSet(permTargetInfo.getRepoKeys()));
permTargetsDao.createPermissionTarget(dbPermTarget);
Acl acl = aclFromInfo(dbService.nextId(), entity, dbPermTarget.getPermTargetId());
aclsDao.createAcl(acl);
} catch (SQLException e) {
throw new StorageException("Could not create ACL " + entity, e);
} finally {
aclsCache.promoteAclsDbVersion();
}
}
@Override
public void updateAcl(MutableAclInfo aclInfo) {
PermissionTargetInfo permTargetInfo = aclInfo.getPermissionTarget();
try {
PermissionTarget dbPermTarget = permTargetsDao.findPermissionTarget(permTargetInfo.getName());
if (dbPermTarget == null) {
throw new StorageException(
"Could not update ACL with non existent Permission Target " + aclInfo.getPermissionTarget());
}
long permTargetId = dbPermTarget.getPermTargetId();
PermissionTarget newPermTarget = new PermissionTarget(permTargetId,
permTargetInfo.getName(), permTargetInfo.getIncludes(), permTargetInfo.getExcludes());
newPermTarget.setRepoKeys(Sets.newHashSet(permTargetInfo.getRepoKeys()));
permTargetsDao.updatePermissionTarget(newPermTarget);
Acl dbAcl = aclsDao.findAclByPermissionTargetId(permTargetId);
if (dbAcl == null) {
throw new StorageException("Could not update non existent ACL " + aclInfo);
}
Acl acl = aclFromInfo(dbAcl.getAclId(), aclInfo, permTargetId);
aclsDao.updateAcl(acl);
} catch (SQLException e) {
throw new StorageException("Could not update ACL " + aclInfo, e);
} finally {
aclsCache.promoteAclsDbVersion();
}
}
@Override
public void deleteAcl(String permTargetName) {
try {
PermissionTarget permissionTarget = permTargetsDao.findPermissionTarget(permTargetName);
if (permissionTarget == null) {
// Already deleted
return;
}
Acl acl = aclsDao.findAclByPermissionTargetId(permissionTarget.getPermTargetId());
if (acl != null) {
aclsDao.deleteAcl(acl.getAclId());
} else {
log.warn("ACL already deleted, but permission target was not!");
}
permTargetsDao.deletePermissionTarget(permissionTarget.getPermTargetId());
} catch (SQLException e) {
throw new StorageException("Could not delete ACL " + permTargetName, e);
} finally {
aclsCache.promoteAclsDbVersion();
}
}
@Override
public AclInfo getAcl(String permTargetName) {
return getAclsMap().get(permTargetName);
}
@Override
public boolean permissionTargetExists(String permTargetName) {
return getAclsMap().containsKey(permTargetName);
}
@Override
public boolean userHasPermissions(String username) {
try {
long userId = userGroupsDao.findUserIdByUsername(username);
if (userId <= 0L) {
// User not in DB yet
return false;
}
return aclsDao.userHasAce(userId);
} catch (SQLException e) {
throw new StorageException("Cannot check if user " + username + " has permissions!", e);
}
}
@Override
public void removeAllUserAces(String username) {
try {
long userId = userGroupsDao.findUserIdByUsername(username);
if (userId <= 0L) {
// User does not exists
return;
}
aclsDao.deleteAceForUser(userId);
} catch (SQLException e) {
throw new StorageException("Could not delete ACE for user " + username, e);
} finally {
aclsCache.promoteAclsDbVersion();
}
}
@Override
public void removeAllGroupAces(String groupName) {
try {
Group group = userGroupsDao.findGroupByName(groupName);
if (group == null) {
// Group does not exists
return;
}
aclsDao.deleteAceForGroup(group.getGroupId());
} catch (SQLException e) {
throw new StorageException("Could not delete ACE for group " + groupName, e);
} finally {
aclsCache.promoteAclsDbVersion();
}
}
@Override
public void createDefaultSecurityEntities(UserInfo anonUser, GroupInfo readersGroup, String currentUsername) {
if (!UserInfo.ANONYMOUS.equals(anonUser.getUsername())) {
throw new IllegalArgumentException(
"Default anything permissions should be created for the anonymous user only");
}
// create or update read permissions on "anything"
AclInfo anyAnyAcl = getAcl(ANY_PERMISSION_TARGET_NAME);
Set<AceInfo> anyAnyAces = new HashSet<>(2);
anyAnyAces.add(InfoFactoryHolder.get().createAce(
anonUser.getUsername(), false, READ.getMask()));
anyAnyAces.add(InfoFactoryHolder.get().createAce(
readersGroup.getGroupName(), true, READ.getMask()));
if (anyAnyAcl == null) {
MutablePermissionTargetInfo anyAnyTarget = InfoFactoryHolder.get().createPermissionTarget(
ANY_PERMISSION_TARGET_NAME, Lists.newArrayList((ANY_REPO)));
anyAnyTarget.setIncludesPattern(ANY_PATH);
anyAnyAcl = InfoFactoryHolder.get().createAcl(anyAnyTarget, anyAnyAces, currentUsername);
createAcl(anyAnyAcl);
} else {
MutableAclInfo acl = InfoFactoryHolder.get().createAcl(anyAnyAcl.getPermissionTarget());
acl.setAces(anyAnyAces);
acl.setUpdatedBy(currentUsername);
updateAcl(acl);
}
// create or update read and deploy permissions on all remote repos
AclInfo anyRemoteAcl = getAcl(ANY_REMOTE_PERMISSION_TARGET_NAME);
HashSet<AceInfo> anyRemoteAces = new HashSet<>(2);
anyRemoteAces.add(InfoFactoryHolder.get().createAce(
anonUser.getUsername(), false,
READ.getMask() | DEPLOY.getMask()));
if (anyRemoteAcl == null) {
MutablePermissionTargetInfo anyRemoteTarget = InfoFactoryHolder.get().createPermissionTarget(
ANY_REMOTE_PERMISSION_TARGET_NAME, new ArrayList<String>() {{
add(ANY_REMOTE_REPO);
}});
anyRemoteTarget.setIncludesPattern(ANY_PATH);
anyRemoteAcl = InfoFactoryHolder.get().createAcl(anyRemoteTarget, anyRemoteAces, currentUsername);
createAcl(anyRemoteAcl);
} else {
MutableAclInfo acl = InfoFactoryHolder.get().createAcl(anyRemoteAcl.getPermissionTarget());
acl.setAces(anyRemoteAces);
acl.setUpdatedBy(currentUsername);
updateAcl(acl);
}
}
@Override
public void deleteAllAcls() {
try {
aclsDao.deleteAllAcls();
permTargetsDao.deleteAllPermissionTargets();
} catch (SQLException e) {
throw new StorageException("Could not delete all ACLs", e);
} finally {
aclsCache.promoteAclsDbVersion();
}
}
@Override
public int promoteAclsDbVersion() {
return aclsCache.promoteAclsDbVersion();
}
private Acl aclFromInfo(long aclId, AclInfo aclInfo, long permTargetId) throws SQLException {
Acl acl = new Acl(aclId, permTargetId, System.currentTimeMillis(),
aclInfo.getUpdatedBy());
Set<AceInfo> aces = aclInfo.getAces();
HashSet<Ace> dbAces = new HashSet<>(aces.size());
for (AceInfo ace : aces) {
Ace dbAce = null;
if (ace.isGroup()) {
Group group = userGroupsDao.findGroupByName(ace.getPrincipal());
if (group != null) {
dbAce = new Ace(dbService.nextId(), acl.getAclId(), ace.getMask(), 0, group.getGroupId());
} else {
log.error("Got ACE entry for ACL " + aclInfo.getPermissionTarget().getName() +
" with a group " + ace.getPrincipal() + " that does not exist!");
}
} else {
long userId = userGroupsDao.findUserIdByUsername(ace.getPrincipal());
if (userId > 0L) {
dbAce = new Ace(dbService.nextId(), acl.getAclId(), ace.getMask(), userId, 0);
} else {
log.error("Got ACE entry for ACL " + aclInfo.getPermissionTarget().getName() +
" with a user " + ace.getPrincipal() + " that does not exist!");
}
}
if (dbAce != null) {
dbAces.add(dbAce);
}
}
acl.setAces(dbAces);
return acl;
}
private Map<String, AclInfo> getAclsMap() {
return aclsCache.get();
}
private static class AclsCache {
private final AclCacheLoader cacheLoader;
private AtomicInteger aclsDbVersion = new AtomicInteger(
1); // promoted on each DB change (permission change/add/delete)
private volatile int aclsMapVersion = 0; // promoted each time we load the map from DB
private volatile Map<String, AclInfo> aclsMap;
public AclsCache(AclCacheLoader cacheLoader) {
this.cacheLoader = cacheLoader;
}
/**
* Call this method each permission update/change/delete in DB.
*/
public int promoteAclsDbVersion() {
return aclsDbVersion.incrementAndGet();
}
/**
* Returns permissions map.
*/
public Map<String, AclInfo> get() {
Map<String, AclInfo> tempMap = aclsMap;
if (aclsDbVersion.get() > aclsMapVersion) {
// Need to update aclsMap (new version in aclsDbVersion).
synchronized (cacheLoader) {
tempMap = aclsMap;
// Double check after cacheLoader synchronization.
if (aclsDbVersion.get() > aclsMapVersion) {
// The map will be valid for version the current aclsDbVersion.
int startingVersion = aclsDbVersion.get();
tempMap = cacheLoader.call();
aclsMap = tempMap;
aclsMapVersion = startingVersion;
}
}
}
return tempMap;
}
}
private class AclCacheLoader implements Callable<Map<String, AclInfo>> {
@Override
public Map<String, AclInfo> call() {
try {
Collection<Acl> allAcls = aclsDao.getAllAcls();
Map<String, AclInfo> result = Maps.newHashMapWithExpectedSize(allAcls.size());
for (Acl acl : allAcls) {
PermissionTarget permTarget = permTargetsDao.findPermissionTarget(acl.getPermTargetId());
MutablePermissionTargetInfo permissionTarget = InfoFactoryHolder.get().createPermissionTarget(
permTarget.getName(), new ArrayList<>(permTarget.getRepoKeys()));
permissionTarget.setIncludes(permTarget.getIncludes());
permissionTarget.setExcludes(permTarget.getExcludes());
ImmutableSet<Ace> dbAces = acl.getAces();
HashSet<AceInfo> aces = new HashSet<>(dbAces.size());
for (Ace dbAce : dbAces) {
MutableAceInfo ace;
if (dbAce.isOnGroup()) {
Group group = userGroupsDao.findGroupById(dbAce.getGroupId());
ace = InfoFactoryHolder.get().createAce(group.getGroupName(), true, dbAce.getMask());
} else {
User user = userGroupsDao.findUserById(dbAce.getUserId());
ace = InfoFactoryHolder.get().createAce(user.getUsername(), false, dbAce.getMask());
}
aces.add(ace);
}
result.put(permTarget.getName(),
InfoFactoryHolder.get().createAcl(permissionTarget, aces, acl.getLastModifiedBy()));
}
return result;
} catch (SQLException e) {
throw new StorageException("Could not load all Access Control List from DB due to:" + e.getMessage(),
e);
}
}
}
}
| |
package org.apache.maven.project;
/*
* 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.util.Collections;
import java.util.List;
import org.apache.maven.artifact.InvalidRepositoryException;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Parent;
import org.apache.maven.model.resolution.ModelResolver;
import org.apache.maven.model.resolution.UnresolvableModelException;
import org.apache.maven.repository.internal.MavenRepositorySystemUtils;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.impl.RemoteRepositoryManager;
import org.eclipse.aether.repository.RemoteRepository;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertTrue;
import static junit.framework.TestCase.fail;
import static org.codehaus.plexus.PlexusTestCase.getBasedir;
/**
* Test cases for the project {@code ModelResolver} implementation.
*
* @author Christian Schulte
* @since 3.5.0
*/
public class ProjectModelResolverTest extends AbstractMavenProjectTestCase
{
/**
* Creates a new {@code ProjectModelResolverTest} instance.
*/
public ProjectModelResolverTest()
{
super();
}
public void testResolveParentThrowsUnresolvableModelExceptionWhenNotFound() throws Exception
{
final Parent parent = new Parent();
parent.setGroupId( "org.apache" );
parent.setArtifactId( "apache" );
parent.setVersion( "0" );
try
{
this.newModelResolver().resolveModel( parent );
fail( "Expected 'UnresolvableModelException' not thrown." );
}
catch ( final UnresolvableModelException e )
{
assertNotNull( e.getMessage() );
assertTrue( e.getMessage().startsWith( "Could not find artifact org.apache:apache:pom:0 in central" ) );
}
}
public void testResolveParentThrowsUnresolvableModelExceptionWhenNoMatchingVersionFound() throws Exception
{
final Parent parent = new Parent();
parent.setGroupId( "org.apache" );
parent.setArtifactId( "apache" );
parent.setVersion( "[2.0,2.1)" );
try
{
this.newModelResolver().resolveModel( parent );
fail( "Expected 'UnresolvableModelException' not thrown." );
}
catch ( final UnresolvableModelException e )
{
assertEquals( "No versions matched the requested parent version range '[2.0,2.1)'",
e.getMessage() );
}
}
public void testResolveParentThrowsUnresolvableModelExceptionWhenUsingRangesWithoutUpperBound() throws Exception
{
final Parent parent = new Parent();
parent.setGroupId( "org.apache" );
parent.setArtifactId( "apache" );
parent.setVersion( "[1,)" );
try
{
this.newModelResolver().resolveModel( parent );
fail( "Expected 'UnresolvableModelException' not thrown." );
}
catch ( final UnresolvableModelException e )
{
assertEquals( "The requested parent version range '[1,)' does not specify an upper bound",
e.getMessage() );
}
}
public void testResolveParentSuccessfullyResolvesExistingParentWithoutRange() throws Exception
{
final Parent parent = new Parent();
parent.setGroupId( "org.apache" );
parent.setArtifactId( "apache" );
parent.setVersion( "1" );
assertNotNull( this.newModelResolver().resolveModel( parent ) );
assertEquals( "1", parent.getVersion() );
}
public void testResolveParentSuccessfullyResolvesExistingParentUsingHighestVersion() throws Exception
{
final Parent parent = new Parent();
parent.setGroupId( "org.apache" );
parent.setArtifactId( "apache" );
parent.setVersion( "(,2.0)" );
assertNotNull( this.newModelResolver().resolveModel( parent ) );
assertEquals( "1", parent.getVersion() );
}
public void testResolveDependencyThrowsUnresolvableModelExceptionWhenNotFound() throws Exception
{
final Dependency dependency = new Dependency();
dependency.setGroupId( "org.apache" );
dependency.setArtifactId( "apache" );
dependency.setVersion( "0" );
try
{
this.newModelResolver().resolveModel( dependency );
fail( "Expected 'UnresolvableModelException' not thrown." );
}
catch ( final UnresolvableModelException e )
{
assertNotNull( e.getMessage() );
assertTrue( e.getMessage().startsWith( "Could not find artifact org.apache:apache:pom:0 in central" ) );
}
}
public void testResolveDependencyThrowsUnresolvableModelExceptionWhenNoMatchingVersionFound() throws Exception
{
final Dependency dependency = new Dependency();
dependency.setGroupId( "org.apache" );
dependency.setArtifactId( "apache" );
dependency.setVersion( "[2.0,2.1)" );
try
{
this.newModelResolver().resolveModel( dependency );
fail( "Expected 'UnresolvableModelException' not thrown." );
}
catch ( final UnresolvableModelException e )
{
assertEquals( "No versions matched the requested dependency version range '[2.0,2.1)'",
e.getMessage() );
}
}
public void testResolveDependencyThrowsUnresolvableModelExceptionWhenUsingRangesWithoutUpperBound() throws Exception
{
final Dependency dependency = new Dependency();
dependency.setGroupId( "org.apache" );
dependency.setArtifactId( "apache" );
dependency.setVersion( "[1,)" );
try
{
this.newModelResolver().resolveModel( dependency );
fail( "Expected 'UnresolvableModelException' not thrown." );
}
catch ( final UnresolvableModelException e )
{
assertEquals( "The requested dependency version range '[1,)' does not specify an upper bound",
e.getMessage() );
}
}
public void testResolveDependencySuccessfullyResolvesExistingDependencyWithoutRange() throws Exception
{
final Dependency dependency = new Dependency();
dependency.setGroupId( "org.apache" );
dependency.setArtifactId( "apache" );
dependency.setVersion( "1" );
assertNotNull( this.newModelResolver().resolveModel( dependency ) );
assertEquals( "1", dependency.getVersion() );
}
public void testResolveDependencySuccessfullyResolvesExistingDependencyUsingHighestVersion() throws Exception
{
final Dependency dependency = new Dependency();
dependency.setGroupId( "org.apache" );
dependency.setArtifactId( "apache" );
dependency.setVersion( "(,2.0)" );
assertNotNull( this.newModelResolver().resolveModel( dependency ) );
assertEquals( "1", dependency.getVersion() );
}
private ModelResolver newModelResolver() throws Exception
{
final File localRepo = new File( this.getLocalRepository().getBasedir() );
final DefaultRepositorySystemSession repoSession = MavenRepositorySystemUtils.newSession();
repoSession.setLocalRepositoryManager( new LegacyLocalRepositoryManager( localRepo ) );
return new ProjectModelResolver( repoSession, null, lookup( RepositorySystem.class ),
lookup( RemoteRepositoryManager.class ),
this.getRemoteRepositories(),
ProjectBuildingRequest.RepositoryMerging.REQUEST_DOMINANT, null );
}
private List<RemoteRepository> getRemoteRepositories()
throws InvalidRepositoryException
{
final File repoDir = new File( getBasedir(), "src/test/remote-repo" ).getAbsoluteFile();
final RemoteRepository remoteRepository =
new RemoteRepository.Builder( org.apache.maven.repository.RepositorySystem.DEFAULT_REMOTE_REPO_ID,
"default", repoDir.toURI().toASCIIString() ).build();
return Collections.singletonList( remoteRepository );
}
}
| |
/**
* Copyright (c) 2014, FinancialForce.com, inc
* 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 FinancialForce.com, inc 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.
**/
//package
package com.financialforce.objectmodelutil.model.config;
//imports
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;
import com.financialforce.objectmodelutil.App;
import com.financialforce.objectmodelutil.model.exception.SpecificException;
import com.financialforce.objectmodelutil.model.exception.misc.MiscConfigException;
import com.financialforce.objectmodelutil.model.exception.misc.MiscConfigInvalidException;
import com.financialforce.objectmodelutil.model.exception.misc.MiscFactoryException;
import com.financialforce.objectmodelutil.model.exception.parse.ParseCommandException;
import com.financialforce.objectmodelutil.model.exception.parse.ParseCommandRequiredException;
import com.financialforce.objectmodelutil.model.exception.parse.ParseConfigException;
import com.financialforce.objectmodelutil.model.processor.Processor;
import com.financialforce.objectmodelutil.model.processor.input.InputProcessor;
import com.financialforce.objectmodelutil.model.processor.output.OutputProcessor;
import com.financialforce.objectmodelutil.model.processor.retrieve.RetrieveProcessor;
/**
* Class to parse input params to key value pairs in a hashmap.
* Also loads config file to generate the classes needed to run the utility.
*
* @author Brad Slater (DevOps) financialforce.com
* @version 1.0.0
*/
public class ConfigProcessor {
/**
* empty constructors
*/
public ConfigProcessor() {}
/**
* Parses arguments into a hashmap
* Parses config file first, gets the required
* params for the processors set and
* sees if the params match the requirements.
*
* @param args
* @return map of arguments / map of processors
* @throws MiscConfigException
* @throws ParseConfigException
* @throws ParseCommandRequiredException
* @throws MiscConfigInvalidException
* @throws CommandParseException
*/
public AbstractMap.SimpleEntry<HashMap<String, String>,HashMap<String, Processor>> parseArguments(String args[])
throws ParseCommandException, ParseConfigException, MiscConfigException, ParseCommandRequiredException, MiscConfigInvalidException{
//make a map to hold params.
HashMap<String, String> params = new HashMap<String,String>();
try {
//for each argument, split argument into params
for (String arg : args){
String[] subArgs = arg.split("=");
params.put(subArgs[0], subArgs[1]);
}
} catch (Exception e){
throw new ParseCommandException(e);
}
String configFile = params.get("config.properties");
if (configFile == null){
throw new ParseCommandRequiredException(new SpecificException("Config Processor requires parameter: config.properties (path to properties file)"));
}
//now we have the params, get the processors...
HashMap<String, Processor> processors = this.parseConfigFile(configFile);
InputProcessor input = (InputProcessor) processors.get("input");
RetrieveProcessor retrieve = (RetrieveProcessor) processors.get("retrieve");
OutputProcessor output = (OutputProcessor) processors.get("output");
//now we have processors and params
//create errors list
ArrayList<String> errors = new ArrayList<String>();
//get input processor if it isnt null
if(processors.get("input") != null){
Set<String> requiredParamsIn = input.getRequiredParameters();
for (String req : requiredParamsIn){
//if the params list doesnt contain the param:
String currentParamToCheck = params.get(req);
if (currentParamToCheck == null){
errors.add("Input Processor: " + input.getClass().getSimpleName() + ", requires parameter: " + req);
}
}
}
Set<String> requiredParamsRet = retrieve.getRequiredParameters();
for (String req : requiredParamsRet){
//if the params list doesnt contain the param:
String currentParamToCheck = params.get(req);
if (currentParamToCheck == null){
errors.add("Retrieve Processor: " + retrieve.getClass().getSimpleName() + ", requires parameter: " + req);
}
}
Set<String> requiredParamsOut = output.getRequiredParameters();
for (String req : requiredParamsOut){
//if the params list doesnt contain the param:
String currentParamToCheck = params.get(req);
if (currentParamToCheck == null){
errors.add("Output Processor: " + output.getClass().getSimpleName() + ", requires parameter: " + req);
}
}
if (errors.size() > 0){
String errorList = "";
for (String error: errors){
errorList += error + "\n\t";
}
throw new ParseCommandRequiredException(new SpecificException(errorList));
}
//return the params map and the processor map
return new AbstractMap.SimpleEntry<HashMap<String, String>,HashMap<String, Processor>>(params,processors);
}
/**
* Parses config.properties file into the required classes
*
* @return Map<String, Object> classes needed.
* @throws ParseConfigException
* @throws MiscConfigException
* @throws IOException
*/
private HashMap<String, Processor> parseConfigFile(String configFilePath) throws ParseConfigException, MiscConfigException {
Properties prop = new Properties();
try {
prop.load(new FileInputStream(new File(configFilePath)));
} catch (IOException e){
throw new ParseConfigException(e);
}
InputProcessor input = null;
RetrieveProcessor retrieve = null;
OutputProcessor output = null;
//get the class names
String inputName = prop.getProperty("input");
String retrieveName = prop.getProperty("retrieve");
String outputName = prop.getProperty("output");
//error check (retriever or output processor cant be null
if(retrieveName == null || outputName == null){
throw new MiscConfigException(new SpecificException("'retrieve=' and 'output=' must be set in the config.properties file."));
}
try {
//set input if there is one
if (inputName != null){
input = InputProcessor.getNewInputProcessor(inputName);
}
//set retriever and output
retrieve = RetrieveProcessor.getNewRetrieveService(retrieveName);
output = OutputProcessor.getNewOutputProcessor(outputName);
} catch (MiscFactoryException e){
throw new MiscConfigException(e);
}
//at this point you deffinately have at lease a retrieve and output processor and possibly an input processor.
HashMap<String,Processor> processorSet = new HashMap<String,Processor>();
processorSet.put("output",output);
processorSet.put("retrieve",retrieve);
if (input != null){
processorSet.put("input",input);
}
return processorSet;
}
}
| |
package com.elmakers.mine.bukkit.heroes;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import com.elmakers.mine.bukkit.api.attributes.AttributeProvider;
import com.elmakers.mine.bukkit.api.entity.TeamProvider;
import com.elmakers.mine.bukkit.api.spell.MageSpell;
import com.elmakers.mine.bukkit.api.spell.SpellTemplate;
import com.elmakers.mine.bukkit.magic.MagicController;
import com.elmakers.mine.bukkit.magic.ManaController;
import com.elmakers.mine.bukkit.utility.ConfigurationUtils;
import com.google.common.collect.Multimap;
import com.google.common.collect.Ordering;
import com.google.common.collect.TreeMultimap;
import com.herocraftonline.heroes.Heroes;
import com.herocraftonline.heroes.characters.CharacterManager;
import com.herocraftonline.heroes.characters.Hero;
import com.herocraftonline.heroes.characters.classes.HeroClass;
import com.herocraftonline.heroes.characters.party.HeroParty;
import com.herocraftonline.heroes.characters.skill.ActiveSkill;
import com.herocraftonline.heroes.characters.skill.Skill;
import com.herocraftonline.heroes.characters.skill.SkillConfigManager;
import com.herocraftonline.heroes.characters.skill.SkillManager;
import com.herocraftonline.heroes.characters.skill.SkillSetting;
public class HeroesManager implements ManaController, AttributeProvider, TeamProvider {
private Heroes heroes;
private CharacterManager characters;
private SkillManager skills;
private static final Set<String> emptySkills = new HashSet<>();
private static final List<String> emptySkillList = new ArrayList<>();
private final Logger log;
private Method getHeroAttributeMethod;
private static final Map<String, Enum<?>> attributes = new HashMap<>();
private final Set<String> usesMana = new HashSet<>();
private boolean usesParties = true;
public HeroesManager(Plugin plugin, Plugin heroesPlugin) {
log = plugin.getLogger();
if (!(heroesPlugin instanceof Heroes))
{
log.warning("Heroes found, but is not instance of Heroes plugin!");
return;
}
heroes = (Heroes)heroesPlugin;
try {
@SuppressWarnings("unchecked")
Class<Enum<?>> classAttributeType = (Class<Enum<?>>)Class.forName("com.herocraftonline.heroes.attributes.AttributeType");
Enum<?>[] values = classAttributeType.getEnumConstants();
for (Enum<?> value : values) {
attributes.put(value.name().toLowerCase(), value);
}
getHeroAttributeMethod = Hero.class.getMethod("getAttributeValue", classAttributeType);
log.info("Registered Heroes attributes for use in spell parameters: " + getAllAttributes());
} catch (Exception ex) {
attributes.clear();
getHeroAttributeMethod = null;
log.info("Could not register Heroes attributes, you may need to update Heroes");
}
// Delay integration because Heroes doesn't create its subsystems right away
plugin.getServer().getScheduler().runTaskLater(plugin, new Runnable() {
@Override
public void run() {
finishIntegration();
}
}, 2);
}
public void load(ConfigurationSection configuration) {
boolean useMana = configuration.getBoolean("use_heroes_mana", true);
usesMana.clear();
if (useMana) {
usesMana.addAll(ConfigurationUtils.getStringList(configuration, "heroes_mana_classes"));
}
usesParties = configuration.getBoolean("use_heroes_parties", true);
if (usesParties) {
log.info("Heroes parties will be respected in friendly fire checks");
}
if (!usesMana.isEmpty()) {
log.info("Heroes mana will be used for classes: " + StringUtils.join(usesMana, ",") + ")");
}
}
public boolean useParties() {
return usesParties;
}
public boolean usesMana(String mageClass) {
return usesMana.contains(mageClass);
}
public void finishIntegration() {
characters = heroes.getCharacterManager();
skills = heroes.getSkillManager();
if (characters != null && skills != null)
{
log.info("Heroes found, skills available for wand and hotbar use.");
log.info("Give Magic.commands.mskills permission for /mskills command");
log.info("Use \"/wand heroes\" for a wand that uses Heroes skills");
}
else
{
log.warning("Heroes found, but failed to integrate!");
if (characters == null) {
log.warning(" CharacterManager is null");
}
if (skills == null) {
log.warning(" SkillManager is null");
}
}
}
public boolean canUseSkill(Player player, String skillName) {
Hero hero = getHero(player);
if (hero == null) return false;
return hero.canUseSkill(skillName);
}
public List<String> getSkillList(Player player, boolean showUnuseable, boolean showPassive)
{
if (skills == null) return emptySkillList;
Hero hero = getHero(player);
if (hero == null) return emptySkillList;
HeroClass heroClass = hero.getHeroClass();
HeroClass secondClass = hero.getSecondClass();
Set<String> primarySkills = new HashSet<>();
Set<String> secondarySkills = new HashSet<>();
addSkills(hero, heroClass, primarySkills, showUnuseable, showPassive);
addSkills(hero, secondClass, secondarySkills, showUnuseable, showPassive);
secondarySkills.removeAll(primarySkills);
Multimap<Integer, Skill> primaryMap = mapSkillsByLevel(hero, primarySkills);
Multimap<Integer, Skill> secondaryMap = mapSkillsByLevel(hero, secondarySkills);
List<String> skillNames = new ArrayList<>();
for (Skill skill : primaryMap.values())
{
skillNames.add(skill.getName());
}
for (Skill skill : secondaryMap.values())
{
skillNames.add(skill.getName());
}
return skillNames;
}
private Multimap<Integer, Skill> mapSkillsByLevel(Hero hero, Collection<String> skillNames) {
Multimap<Integer, Skill> skillMap = TreeMultimap.create(Ordering.natural(), new Comparator<Skill>() {
@Override
public int compare(Skill skill1, Skill skill2) {
return skill1.getName().compareTo(skill2.getName());
}
});
for (String skillName : skillNames)
{
Skill skill = skills.getSkill(skillName);
if (skill == null) continue;
int level = SkillConfigManager.getUseSetting(hero, skill, SkillSetting.LEVEL, 1, true);
skillMap.put(level, skill);
}
return skillMap;
}
public int getSkillLevel(Player player, String skillName) {
Skill skill = skills.getSkill(skillName);
if (skill == null) return 0;
Hero hero = getHero(player);
if (hero == null) return 0;
return SkillConfigManager.getUseSetting(hero, skill, SkillSetting.LEVEL, 1, true);
}
private void addSkills(Hero hero, HeroClass heroClass, Collection<String> skillSet, boolean showUnuseable, boolean showPassive)
{
if (heroClass != null)
{
Set<String> classSkills = heroClass.getSkillNames();
for (String classSkill : classSkills)
{
Skill skill = skills.getSkill(classSkill);
if (!showUnuseable && !hero.canUseSkill(skill)) continue;
if (!showPassive && !(skill instanceof ActiveSkill)) continue;
// getRaw's boolean default value is ignored! :(
if (SkillConfigManager.getRaw(skill, "wand", "true").equalsIgnoreCase("true"))
{
skillSet.add(classSkill);
}
}
}
}
public Set<String> getSkills(Player player) {
return getSkills(player, false, false);
}
public Set<String> getSkills(Player player, boolean showUnuseable, boolean showPassive) {
if (skills == null) return emptySkills;
Hero hero = getHero(player);
if (hero == null) return emptySkills;
Set<String> skillSet = new HashSet<>();
HeroClass heroClass = hero.getHeroClass();
HeroClass secondClass = hero.getSecondClass();
addSkills(hero, heroClass, skillSet, showUnuseable, showPassive);
addSkills(hero, secondClass, skillSet, showUnuseable, showPassive);
return skillSet;
}
public void clearCooldown(Player player) {
Hero hero = getHero(player);
if (hero == null) return;
hero.clearCooldowns();
}
public void setCooldown(Player player, long ms) {
Hero hero = getHero(player);
if (hero == null) return;
long cooldown = System.currentTimeMillis() + ms;
Set<String> skills = getSkills(player, false, false);
for (String skill : skills) {
Long currentCooldown = hero.getCooldown(skill);
if (currentCooldown == null || currentCooldown < cooldown) {
hero.setCooldown(skill, cooldown);
}
}
}
public void reduceCooldown(Player player, long ms) {
Hero hero = getHero(player);
if (hero == null) return;
Set<String> skills = getSkills(player, false, false);
for (String skill : skills) {
Long currentCooldown = hero.getCooldown(skill);
if (currentCooldown != null) {
hero.setCooldown(skill, Math.max(0, currentCooldown - ms));
}
}
}
@Nullable
public SpellTemplate createSkillSpell(MagicController controller, String skillName) {
if (skills == null) return null;
Skill skill = skills.getSkill(skillName);
if (skill == null) return null;
MageSpell newSpell = new HeroesSkillSpell();
newSpell.initialize(controller);
ConfigurationSection config = ConfigurationUtils.newConfigurationSection();
String iconURL = SkillConfigManager.getRaw(skill, "icon-url", SkillConfigManager.getRaw(skill, "icon_url", null));
if (iconURL == null || iconURL.isEmpty()) {
String icon = SkillConfigManager.getRaw(skill, "icon", null);
if (icon == null || icon.isEmpty()) {
config.set("icon", controller.getDefaultSkillIcon());
} else if (icon.startsWith("http://")) {
config.set("icon_url", icon);
} else {
config.set("icon", icon);
}
} else {
config.set("icon_url", iconURL);
}
String iconDisabledURL = SkillConfigManager.getRaw(skill, "icon-disabled-url", SkillConfigManager.getRaw(skill, "icon_disabled_url", null));
if (iconDisabledURL == null || iconDisabledURL.isEmpty()) {
String icon = SkillConfigManager.getRaw(skill, "icon-disabled", SkillConfigManager.getRaw(skill, "icon_disabled", null));
if (icon != null && !icon.isEmpty()) {
if (icon.startsWith("http://")) {
config.set("icon_disabled_url", icon);
} else {
config.set("icon_disabled", icon);
}
}
} else {
config.set("icon_disabled_url", iconDisabledURL);
}
String nameTemplate = controller.getMessages().get("skills.item_name", "$skill");
String skillDisplayName = SkillConfigManager.getRaw(skill, "name", skill.getName());
config.set("name", nameTemplate.replace("$skill", skillDisplayName));
config.set("category", "skills");
String descriptionTemplate = controller.getMessages().get("skills.item_description", "$description");
descriptionTemplate = descriptionTemplate.replace("$description", SkillConfigManager.getRaw(skill, "description", ""));
config.set("description", descriptionTemplate);
newSpell.loadTemplate("heroes*" + skillName, config);
return newSpell;
}
public String getClassName(Player player) {
Hero hero = getHero(player);
if (hero == null) return "";
HeroClass heroClass = hero.getHeroClass();
if (heroClass == null) return "";
return heroClass.getName();
}
public String getSecondaryClassName(Player player) {
Hero hero = getHero(player);
if (hero == null) return "";
HeroClass heroClass = hero.getSecondClass();
if (heroClass == null) return "";
return heroClass.getName();
}
@Nullable
protected Skill getSkill(String key) {
if (skills == null) return null;
return skills.getSkill(key);
}
@Nullable
protected Hero getHero(Player player) {
if (characters == null) return null;
return characters.getHero(player);
}
@Override
public double getMaxMana(Player player) {
Hero hero = getHero(player);
if (hero == null) return 0;
return hero.getMaxMana();
}
@Override
public double getManaRegen(Player player) {
Hero hero = getHero(player);
if (hero == null) return 0;
return hero.getManaRegen();
}
@Override
public double getMana(Player player) {
Hero hero = getHero(player);
if (hero == null) return 0;
return hero.getMana();
}
@Override
public void removeMana(Player player, double amount) {
Hero hero = getHero(player);
if (hero == null) return;
hero.setMana(Math.max(0, hero.getMana() - (int)amount));
}
@Override
public void setMana(Player player, double amount) {
Hero hero = getHero(player);
if (hero == null) return;
hero.setMana((int)amount);
}
public boolean isInParty(Player source, Player check, boolean pvpCheck) {
Hero sourceHero = getHero(source);
Hero checkHero = getHero(check);
if (sourceHero == null || checkHero == null) return false;
HeroParty party = sourceHero.getParty();
if (party == null || (pvpCheck && !party.isNoPvp())) return false;
return party.getMembers().contains(checkHero);
}
@Override
public boolean isFriendly(Entity attacker, Entity entity) {
if (attacker instanceof Player && entity instanceof Player) {
return isInParty((Player)attacker, (Player)entity, false);
}
return false;
}
@Override
public Set<String> getAllAttributes() {
return attributes.keySet();
}
@Nullable
@Override
public Double getAttributeValue(String attribute, Player player) {
Double result = null;
Hero hero = getHero(player);
if (hero == null) {
return null;
}
try {
if (getHeroAttributeMethod != null) {
Enum<?> attributeType = attributes.get(attribute);
if (attributeType != null) {
result = (double)(int)getHeroAttributeMethod.invoke(hero, attributeType);
}
}
} catch (Exception ex) {
log.log(Level.WARNING, "Failed read Hero attribute", ex);
}
return result;
}
}
| |
/*
* 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/dialogflow/v2/agent.proto
package com.google.cloud.dialogflow.v2;
/**
*
*
* <pre>
* The request message for [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2.SearchAgentsRequest}
*/
public final class SearchAgentsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2.SearchAgentsRequest)
SearchAgentsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use SearchAgentsRequest.newBuilder() to construct.
private SearchAgentsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SearchAgentsRequest() {
parent_ = "";
pageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new SearchAgentsRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private SearchAgentsRequest(
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 10:
{
java.lang.String s = input.readStringRequireUtf8();
parent_ = s;
break;
}
case 16:
{
pageSize_ = input.readInt32();
break;
}
case 26:
{
java.lang.String s = input.readStringRequireUtf8();
pageToken_ = s;
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.dialogflow.v2.AgentProto
.internal_static_google_cloud_dialogflow_v2_SearchAgentsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2.AgentProto
.internal_static_google_cloud_dialogflow_v2_SearchAgentsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2.SearchAgentsRequest.class,
com.google.cloud.dialogflow.v2.SearchAgentsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
private volatile java.lang.Object parent_;
/**
*
*
* <pre>
* Required. The project to list agents from.
* Format: `projects/<Project ID or '-'>`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The project to list agents from.
* Format: `projects/<Project ID or '-'>`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_;
/**
*
*
* <pre>
* Optional. The maximum number of items to return in a single page. By
* default 100 and at most 1000.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
private volatile java.lang.Object pageToken_;
/**
*
*
* <pre>
* The next_page_token value returned from a previous list request.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* The next_page_token value returned from a previous list request.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
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 (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
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.dialogflow.v2.SearchAgentsRequest)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.v2.SearchAgentsRequest other =
(com.google.cloud.dialogflow.v2.SearchAgentsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) 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) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dialogflow.v2.SearchAgentsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.SearchAgentsRequest 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.dialogflow.v2.SearchAgentsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.SearchAgentsRequest 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.dialogflow.v2.SearchAgentsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2.SearchAgentsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2.SearchAgentsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.SearchAgentsRequest 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.dialogflow.v2.SearchAgentsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.SearchAgentsRequest 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.dialogflow.v2.SearchAgentsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2.SearchAgentsRequest 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.dialogflow.v2.SearchAgentsRequest 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>
* The request message for [Agents.SearchAgents][google.cloud.dialogflow.v2.Agents.SearchAgents].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2.SearchAgentsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2.SearchAgentsRequest)
com.google.cloud.dialogflow.v2.SearchAgentsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2.AgentProto
.internal_static_google_cloud_dialogflow_v2_SearchAgentsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2.AgentProto
.internal_static_google_cloud_dialogflow_v2_SearchAgentsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2.SearchAgentsRequest.class,
com.google.cloud.dialogflow.v2.SearchAgentsRequest.Builder.class);
}
// Construct using com.google.cloud.dialogflow.v2.SearchAgentsRequest.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();
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dialogflow.v2.AgentProto
.internal_static_google_cloud_dialogflow_v2_SearchAgentsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.SearchAgentsRequest getDefaultInstanceForType() {
return com.google.cloud.dialogflow.v2.SearchAgentsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.SearchAgentsRequest build() {
com.google.cloud.dialogflow.v2.SearchAgentsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.SearchAgentsRequest buildPartial() {
com.google.cloud.dialogflow.v2.SearchAgentsRequest result =
new com.google.cloud.dialogflow.v2.SearchAgentsRequest(this);
result.parent_ = parent_;
result.pageSize_ = pageSize_;
result.pageToken_ = pageToken_;
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.dialogflow.v2.SearchAgentsRequest) {
return mergeFrom((com.google.cloud.dialogflow.v2.SearchAgentsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dialogflow.v2.SearchAgentsRequest other) {
if (other == com.google.cloud.dialogflow.v2.SearchAgentsRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
onChanged();
}
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.dialogflow.v2.SearchAgentsRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.dialogflow.v2.SearchAgentsRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The project to list agents from.
* Format: `projects/<Project ID or '-'>`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The project to list agents from.
* Format: `projects/<Project ID or '-'>`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The project to list agents from.
* Format: `projects/<Project ID or '-'>`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The project to list agents from.
* Format: `projects/<Project ID or '-'>`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The project to list agents from.
* Format: `projects/<Project ID or '-'>`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Optional. The maximum number of items to return in a single page. By
* default 100 and at most 1000.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Optional. The maximum number of items to return in a single page. By
* default 100 and at most 1000.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The maximum number of items to return in a single page. By
* default 100 and at most 1000.
* </pre>
*
* <code>int32 page_size = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* The next_page_token value returned from a previous list request.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The next_page_token value returned from a previous list request.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The next_page_token value returned from a previous list request.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The next_page_token value returned from a previous list request.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
onChanged();
return this;
}
/**
*
*
* <pre>
* The next_page_token value returned from a previous list request.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
onChanged();
return this;
}
@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.dialogflow.v2.SearchAgentsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2.SearchAgentsRequest)
private static final com.google.cloud.dialogflow.v2.SearchAgentsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2.SearchAgentsRequest();
}
public static com.google.cloud.dialogflow.v2.SearchAgentsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SearchAgentsRequest> PARSER =
new com.google.protobuf.AbstractParser<SearchAgentsRequest>() {
@java.lang.Override
public SearchAgentsRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new SearchAgentsRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<SearchAgentsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SearchAgentsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2.SearchAgentsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
/*
* #%L
* ELK Reasoner
*
* $Id$
* $HeadURL$
* %%
* Copyright (C) 2011 Department of Computer Science, University of Oxford
* %%
* 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.
* #L%
*/
package org.semanticweb.elk.reasoner.indexing.classes;
import java.util.ArrayList;
import java.util.List;
import org.semanticweb.elk.owl.interfaces.ElkAxiom;
import org.semanticweb.elk.owl.interfaces.ElkObject;
import org.semanticweb.elk.owl.predefined.PredefinedElkEntityFactory;
import org.semanticweb.elk.reasoner.indexing.model.CachedIndexedOwlNothing;
import org.semanticweb.elk.reasoner.indexing.model.CachedIndexedOwlThing;
import org.semanticweb.elk.reasoner.indexing.model.IndexedObjectProperty;
import org.semanticweb.elk.reasoner.indexing.model.ModifiableIndexedClass;
import org.semanticweb.elk.reasoner.indexing.model.ModifiableIndexedClassExpression;
import org.semanticweb.elk.reasoner.indexing.model.ModifiableIndexedObject;
import org.semanticweb.elk.reasoner.indexing.model.ModifiableOntologyIndex;
import org.semanticweb.elk.reasoner.indexing.model.OccurrenceIncrement;
import org.semanticweb.elk.reasoner.indexing.model.OntologyIndex;
import org.semanticweb.elk.reasoner.saturation.rules.contextinit.ChainableContextInitRule;
import org.semanticweb.elk.reasoner.saturation.rules.contextinit.LinkedContextInitRule;
import org.semanticweb.elk.reasoner.saturation.rules.contextinit.RootContextInitializationRule;
import org.semanticweb.elk.reasoner.saturation.rules.subsumers.ChainableSubsumerRule;
import org.semanticweb.elk.util.collections.HashListMultimap;
import org.semanticweb.elk.util.collections.Multimap;
import org.semanticweb.elk.util.collections.chains.AbstractChain;
import org.semanticweb.elk.util.collections.chains.Chain;
/**
* An implementation of {@link ModifiableOntologyIndex}
*
* @author "Yevgeny Kazakov"
*
*/
public class DirectIndex extends ModifiableIndexedObjectCacheImpl
implements ModifiableOntologyIndex {
private ChainableContextInitRule contextInitRules_;
private final Multimap<IndexedObjectProperty, ElkAxiom> reflexiveObjectProperties_;
private final List<OntologyIndex.ChangeListener> listeners_;
private final List<ModifiableOntologyIndex.IndexingUnsupportedListener> indexingUnsupportedListeners_;
public DirectIndex(final PredefinedElkEntityFactory elkFactory) {
super(elkFactory);
this.reflexiveObjectProperties_ = new HashListMultimap<IndexedObjectProperty, ElkAxiom>(
64);
this.listeners_ = new ArrayList<OntologyIndex.ChangeListener>();
this.indexingUnsupportedListeners_ = new ArrayList<ModifiableOntologyIndex.IndexingUnsupportedListener>();
// the context root initialization rule is always registered
RootContextInitializationRule.addRuleFor(this);
// owl:Thing and owl:Nothing always occur
OccurrenceIncrement addition = OccurrenceIncrement
.getNeutralIncrement(1);
getOwlThing().updateOccurrenceNumbers(this, addition);
getOwlNothing().updateOccurrenceNumbers(this, addition);
getOwlTopObjectProperty().updateOccurrenceNumbers(this, addition);
getOwlBottomObjectProperty().updateOccurrenceNumbers(this, addition);
// register listeners for occurrences
getOwlThing().addListener(new CachedIndexedOwlThing.ChangeListener() {
@Override
public void negativeOccurrenceAppeared() {
for (int i = 0; i < listeners_.size(); i++) {
listeners_.get(i).negativeOwlThingAppeared();
}
}
@Override
public void negativeOccurrenceDisappeared() {
for (int i = 0; i < listeners_.size(); i++) {
listeners_.get(i).negativeOwlThingDisappeared();
}
}
});
getOwlNothing().addListener(new CachedIndexedOwlNothing.ChangeListener() {
@Override
public void positiveOccurrenceAppeared() {
for (int i = 0; i < listeners_.size(); i++) {
listeners_.get(i).positiveOwlNothingAppeared();
}
}
@Override
public void positiveOccurrenceDisappeared() {
for (int i = 0; i < listeners_.size(); i++) {
listeners_.get(i).positiveOwlNothingDisappeared();
}
}
});
}
/* read-only methods required by the interface */
@Override
public final LinkedContextInitRule getContextInitRuleHead() {
return contextInitRules_;
}
@Override
public final Multimap<IndexedObjectProperty, ElkAxiom> getReflexiveObjectProperties() {
// TODO: make unmodifiable
return reflexiveObjectProperties_;
}
/* read-write methods required by the interface */
@Override
public boolean addContextInitRule(ChainableContextInitRule newRule) {
return newRule.addTo(getContextInitRuleChain());
}
@Override
public boolean removeContextInitRule(ChainableContextInitRule oldRule) {
return oldRule.removeFrom(getContextInitRuleChain());
}
@Override
public boolean add(ModifiableIndexedClassExpression target,
ChainableSubsumerRule rule) {
return rule.addTo(target.getCompositionRuleChain());
}
@Override
public boolean remove(ModifiableIndexedClassExpression target,
ChainableSubsumerRule rule) {
return rule.removeFrom(target.getCompositionRuleChain());
}
@Override
public boolean addReflexiveProperty(IndexedObjectProperty property,
ElkAxiom reason) {
boolean success = reflexiveObjectProperties_.add(property, reason);
if (success) {
for (int i = 0; i < listeners_.size(); i++) {
listeners_.get(i).reflexiveObjectPropertyAddition(property,
reason);
}
}
return success;
}
@Override
public boolean removeReflexiveProperty(IndexedObjectProperty property,
ElkAxiom reason) {
boolean success = reflexiveObjectProperties_.remove(property, reason);
if (success) {
for (int i = 0; i < listeners_.size(); i++) {
listeners_.get(i).reflexiveObjectPropertyRemoval(property,
reason);
}
}
return success;
}
@Override
public final boolean hasNegativeOwlThing() {
return getOwlThing().occursNegatively();
}
@Override
public final boolean hasPositiveOwlNothing() {
return getOwlNothing().occursPositively();
}
@Override
public boolean tryAddDefinition(ModifiableIndexedClass target,
ModifiableIndexedClassExpression definition, ElkAxiom reason) {
return target.setDefinition(definition, reason);
}
@Override
public boolean tryRemoveDefinition(ModifiableIndexedClass target,
ModifiableIndexedClassExpression definition, ElkAxiom reason) {
if (target.getDefinition() != definition
|| !target.getDefinitionReason().equals(reason))
// it was not defined by this definition
return false;
// else
target.removeDefinition();
return true;
}
/* class-specific methods */
/**
* @return a {@link Chain} view of context initialization rules assigned to
* this {@link OntologyIndex}; it can be used for inserting new
* rules or deleting existing ones
*/
public Chain<ChainableContextInitRule> getContextInitRuleChain() {
return new AbstractChain<ChainableContextInitRule>() {
@Override
public ChainableContextInitRule next() {
return contextInitRules_;
}
@Override
public void setNext(ChainableContextInitRule tail) {
contextInitRules_ = tail;
for (int i = 0; i < listeners_.size(); i++) {
listeners_.get(i).contextInitRuleHeadSet(tail);
}
}
};
}
@Override
public boolean addListener(OntologyIndex.ChangeListener listener) {
if (!super.addListener(listener)) {
return false;
}
// else
if (!listeners_.add(listener)) {
// revert
super.removeListener(listener);
return false;
}
// else
return true;
}
@Override
public boolean removeListener(OntologyIndex.ChangeListener listener) {
if (!super.removeListener(listener)) {
return false;
}
// else
if (!listeners_.remove(listener)) {
// revert
super.addListener(listener);
return false;
}
// else
return true;
}
@Override
public boolean addIndexingUnsupportedListener(
final ModifiableOntologyIndex.IndexingUnsupportedListener listener) {
return indexingUnsupportedListeners_.add(listener);
}
@Override
public boolean removeIndexingUnsupportedListener(
final ModifiableOntologyIndex.IndexingUnsupportedListener listener) {
return indexingUnsupportedListeners_.remove(listener);
}
@Override
public void fireIndexingUnsupported(
final ModifiableIndexedObject indexedObject,
final OccurrenceIncrement increment) {
for (final IndexingUnsupportedListener listener : indexingUnsupportedListeners_) {
listener.indexingUnsupported(indexedObject, increment);
}
}
@Override
public void fireIndexingUnsupported(final ElkObject elkObject) {
for (final IndexingUnsupportedListener listener : indexingUnsupportedListeners_) {
listener.indexingUnsupported(elkObject);
}
}
}
| |
/*
* Copyright 2012-2017 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.elasticache.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
* <p>
* Describes all of the attributes of a reserved cache node offering.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/elasticache-2015-02-02/ReservedCacheNodesOffering"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ReservedCacheNodesOffering implements Serializable, Cloneable {
/**
* <p>
* A unique identifier for the reserved cache node offering.
* </p>
*/
private String reservedCacheNodesOfferingId;
/**
* <p>
* The cache node type for the reserved cache node.
* </p>
* <p>
* Valid node types are as follows:
* </p>
* <ul>
* <li>
* <p>
* General purpose:
* </p>
* <ul>
* <li>
* <p>
* Current generation: <code>cache.t2.micro</code>, <code>cache.t2.small</code>, <code>cache.t2.medium</code>,
* <code>cache.m3.medium</code>, <code>cache.m3.large</code>, <code>cache.m3.xlarge</code>,
* <code>cache.m3.2xlarge</code>, <code>cache.m4.large</code>, <code>cache.m4.xlarge</code>,
* <code>cache.m4.2xlarge</code>, <code>cache.m4.4xlarge</code>, <code>cache.m4.10xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Previous generation: <code>cache.t1.micro</code>, <code>cache.m1.small</code>, <code>cache.m1.medium</code>,
* <code>cache.m1.large</code>, <code>cache.m1.xlarge</code>
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Compute optimized: <code>cache.c1.xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Memory optimized:
* </p>
* <ul>
* <li>
* <p>
* Current generation: <code>cache.r3.large</code>, <code>cache.r3.xlarge</code>, <code>cache.r3.2xlarge</code>,
* <code>cache.r3.4xlarge</code>, <code>cache.r3.8xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Previous generation: <code>cache.m2.xlarge</code>, <code>cache.m2.2xlarge</code>, <code>cache.m2.4xlarge</code>
* </p>
* </li>
* </ul>
* </li>
* </ul>
* <p>
* <b>Notes:</b>
* </p>
* <ul>
* <li>
* <p>
* All T2 instances are created in an Amazon Virtual Private Cloud (Amazon VPC).
* </p>
* </li>
* <li>
* <p>
* Redis backup/restore is not supported for Redis (cluster mode disabled) T1 and T2 instances. Backup/restore is
* supported on Redis (cluster mode enabled) T2 instances.
* </p>
* </li>
* <li>
* <p>
* Redis Append-only files (AOF) functionality is not supported for T1 or T2 instances.
* </p>
* </li>
* </ul>
* <p>
* For a complete listing of node types and specifications, see <a
* href="http://aws.amazon.com/elasticache/details">Amazon ElastiCache Product Features and Details</a> and either
* <a href=
* "http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Memcached.html#ParameterGroups.Memcached.NodeSpecific"
* >Cache Node Type-Specific Parameters for Memcached</a> or <a href=
* "http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Redis.html#ParameterGroups.Redis.NodeSpecific"
* >Cache Node Type-Specific Parameters for Redis</a>.
* </p>
*/
private String cacheNodeType;
/**
* <p>
* The duration of the offering. in seconds.
* </p>
*/
private Integer duration;
/**
* <p>
* The fixed price charged for this offering.
* </p>
*/
private Double fixedPrice;
/**
* <p>
* The hourly price charged for this offering.
* </p>
*/
private Double usagePrice;
/**
* <p>
* The cache engine used by the offering.
* </p>
*/
private String productDescription;
/**
* <p>
* The offering type.
* </p>
*/
private String offeringType;
/**
* <p>
* The recurring price charged to run this reserved cache node.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<RecurringCharge> recurringCharges;
/**
* <p>
* A unique identifier for the reserved cache node offering.
* </p>
*
* @param reservedCacheNodesOfferingId
* A unique identifier for the reserved cache node offering.
*/
public void setReservedCacheNodesOfferingId(String reservedCacheNodesOfferingId) {
this.reservedCacheNodesOfferingId = reservedCacheNodesOfferingId;
}
/**
* <p>
* A unique identifier for the reserved cache node offering.
* </p>
*
* @return A unique identifier for the reserved cache node offering.
*/
public String getReservedCacheNodesOfferingId() {
return this.reservedCacheNodesOfferingId;
}
/**
* <p>
* A unique identifier for the reserved cache node offering.
* </p>
*
* @param reservedCacheNodesOfferingId
* A unique identifier for the reserved cache node offering.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ReservedCacheNodesOffering withReservedCacheNodesOfferingId(String reservedCacheNodesOfferingId) {
setReservedCacheNodesOfferingId(reservedCacheNodesOfferingId);
return this;
}
/**
* <p>
* The cache node type for the reserved cache node.
* </p>
* <p>
* Valid node types are as follows:
* </p>
* <ul>
* <li>
* <p>
* General purpose:
* </p>
* <ul>
* <li>
* <p>
* Current generation: <code>cache.t2.micro</code>, <code>cache.t2.small</code>, <code>cache.t2.medium</code>,
* <code>cache.m3.medium</code>, <code>cache.m3.large</code>, <code>cache.m3.xlarge</code>,
* <code>cache.m3.2xlarge</code>, <code>cache.m4.large</code>, <code>cache.m4.xlarge</code>,
* <code>cache.m4.2xlarge</code>, <code>cache.m4.4xlarge</code>, <code>cache.m4.10xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Previous generation: <code>cache.t1.micro</code>, <code>cache.m1.small</code>, <code>cache.m1.medium</code>,
* <code>cache.m1.large</code>, <code>cache.m1.xlarge</code>
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Compute optimized: <code>cache.c1.xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Memory optimized:
* </p>
* <ul>
* <li>
* <p>
* Current generation: <code>cache.r3.large</code>, <code>cache.r3.xlarge</code>, <code>cache.r3.2xlarge</code>,
* <code>cache.r3.4xlarge</code>, <code>cache.r3.8xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Previous generation: <code>cache.m2.xlarge</code>, <code>cache.m2.2xlarge</code>, <code>cache.m2.4xlarge</code>
* </p>
* </li>
* </ul>
* </li>
* </ul>
* <p>
* <b>Notes:</b>
* </p>
* <ul>
* <li>
* <p>
* All T2 instances are created in an Amazon Virtual Private Cloud (Amazon VPC).
* </p>
* </li>
* <li>
* <p>
* Redis backup/restore is not supported for Redis (cluster mode disabled) T1 and T2 instances. Backup/restore is
* supported on Redis (cluster mode enabled) T2 instances.
* </p>
* </li>
* <li>
* <p>
* Redis Append-only files (AOF) functionality is not supported for T1 or T2 instances.
* </p>
* </li>
* </ul>
* <p>
* For a complete listing of node types and specifications, see <a
* href="http://aws.amazon.com/elasticache/details">Amazon ElastiCache Product Features and Details</a> and either
* <a href=
* "http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Memcached.html#ParameterGroups.Memcached.NodeSpecific"
* >Cache Node Type-Specific Parameters for Memcached</a> or <a href=
* "http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Redis.html#ParameterGroups.Redis.NodeSpecific"
* >Cache Node Type-Specific Parameters for Redis</a>.
* </p>
*
* @param cacheNodeType
* The cache node type for the reserved cache node.</p>
* <p>
* Valid node types are as follows:
* </p>
* <ul>
* <li>
* <p>
* General purpose:
* </p>
* <ul>
* <li>
* <p>
* Current generation: <code>cache.t2.micro</code>, <code>cache.t2.small</code>, <code>cache.t2.medium</code>, <code>cache.m3.medium</code>, <code>cache.m3.large</code>, <code>cache.m3.xlarge</code>,
* <code>cache.m3.2xlarge</code>, <code>cache.m4.large</code>, <code>cache.m4.xlarge</code>,
* <code>cache.m4.2xlarge</code>, <code>cache.m4.4xlarge</code>, <code>cache.m4.10xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Previous generation: <code>cache.t1.micro</code>, <code>cache.m1.small</code>,
* <code>cache.m1.medium</code>, <code>cache.m1.large</code>, <code>cache.m1.xlarge</code>
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Compute optimized: <code>cache.c1.xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Memory optimized:
* </p>
* <ul>
* <li>
* <p>
* Current generation: <code>cache.r3.large</code>, <code>cache.r3.xlarge</code>,
* <code>cache.r3.2xlarge</code>, <code>cache.r3.4xlarge</code>, <code>cache.r3.8xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Previous generation: <code>cache.m2.xlarge</code>, <code>cache.m2.2xlarge</code>,
* <code>cache.m2.4xlarge</code>
* </p>
* </li>
* </ul>
* </li>
* </ul>
* <p>
* <b>Notes:</b>
* </p>
* <ul>
* <li>
* <p>
* All T2 instances are created in an Amazon Virtual Private Cloud (Amazon VPC).
* </p>
* </li>
* <li>
* <p>
* Redis backup/restore is not supported for Redis (cluster mode disabled) T1 and T2 instances.
* Backup/restore is supported on Redis (cluster mode enabled) T2 instances.
* </p>
* </li>
* <li>
* <p>
* Redis Append-only files (AOF) functionality is not supported for T1 or T2 instances.
* </p>
* </li>
* </ul>
* <p>
* For a complete listing of node types and specifications, see <a
* href="http://aws.amazon.com/elasticache/details">Amazon ElastiCache Product Features and Details</a> and
* either <a href=
* "http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Memcached.html#ParameterGroups.Memcached.NodeSpecific"
* >Cache Node Type-Specific Parameters for Memcached</a> or <a href=
* "http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Redis.html#ParameterGroups.Redis.NodeSpecific"
* >Cache Node Type-Specific Parameters for Redis</a>.
*/
public void setCacheNodeType(String cacheNodeType) {
this.cacheNodeType = cacheNodeType;
}
/**
* <p>
* The cache node type for the reserved cache node.
* </p>
* <p>
* Valid node types are as follows:
* </p>
* <ul>
* <li>
* <p>
* General purpose:
* </p>
* <ul>
* <li>
* <p>
* Current generation: <code>cache.t2.micro</code>, <code>cache.t2.small</code>, <code>cache.t2.medium</code>,
* <code>cache.m3.medium</code>, <code>cache.m3.large</code>, <code>cache.m3.xlarge</code>,
* <code>cache.m3.2xlarge</code>, <code>cache.m4.large</code>, <code>cache.m4.xlarge</code>,
* <code>cache.m4.2xlarge</code>, <code>cache.m4.4xlarge</code>, <code>cache.m4.10xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Previous generation: <code>cache.t1.micro</code>, <code>cache.m1.small</code>, <code>cache.m1.medium</code>,
* <code>cache.m1.large</code>, <code>cache.m1.xlarge</code>
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Compute optimized: <code>cache.c1.xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Memory optimized:
* </p>
* <ul>
* <li>
* <p>
* Current generation: <code>cache.r3.large</code>, <code>cache.r3.xlarge</code>, <code>cache.r3.2xlarge</code>,
* <code>cache.r3.4xlarge</code>, <code>cache.r3.8xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Previous generation: <code>cache.m2.xlarge</code>, <code>cache.m2.2xlarge</code>, <code>cache.m2.4xlarge</code>
* </p>
* </li>
* </ul>
* </li>
* </ul>
* <p>
* <b>Notes:</b>
* </p>
* <ul>
* <li>
* <p>
* All T2 instances are created in an Amazon Virtual Private Cloud (Amazon VPC).
* </p>
* </li>
* <li>
* <p>
* Redis backup/restore is not supported for Redis (cluster mode disabled) T1 and T2 instances. Backup/restore is
* supported on Redis (cluster mode enabled) T2 instances.
* </p>
* </li>
* <li>
* <p>
* Redis Append-only files (AOF) functionality is not supported for T1 or T2 instances.
* </p>
* </li>
* </ul>
* <p>
* For a complete listing of node types and specifications, see <a
* href="http://aws.amazon.com/elasticache/details">Amazon ElastiCache Product Features and Details</a> and either
* <a href=
* "http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Memcached.html#ParameterGroups.Memcached.NodeSpecific"
* >Cache Node Type-Specific Parameters for Memcached</a> or <a href=
* "http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Redis.html#ParameterGroups.Redis.NodeSpecific"
* >Cache Node Type-Specific Parameters for Redis</a>.
* </p>
*
* @return The cache node type for the reserved cache node.</p>
* <p>
* Valid node types are as follows:
* </p>
* <ul>
* <li>
* <p>
* General purpose:
* </p>
* <ul>
* <li>
* <p>
* Current generation: <code>cache.t2.micro</code>, <code>cache.t2.small</code>,
* <code>cache.t2.medium</code>, <code>cache.m3.medium</code>, <code>cache.m3.large</code>,
* <code>cache.m3.xlarge</code>, <code>cache.m3.2xlarge</code>, <code>cache.m4.large</code>,
* <code>cache.m4.xlarge</code>, <code>cache.m4.2xlarge</code>, <code>cache.m4.4xlarge</code>,
* <code>cache.m4.10xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Previous generation: <code>cache.t1.micro</code>, <code>cache.m1.small</code>,
* <code>cache.m1.medium</code>, <code>cache.m1.large</code>, <code>cache.m1.xlarge</code>
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Compute optimized: <code>cache.c1.xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Memory optimized:
* </p>
* <ul>
* <li>
* <p>
* Current generation: <code>cache.r3.large</code>, <code>cache.r3.xlarge</code>,
* <code>cache.r3.2xlarge</code>, <code>cache.r3.4xlarge</code>, <code>cache.r3.8xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Previous generation: <code>cache.m2.xlarge</code>, <code>cache.m2.2xlarge</code>,
* <code>cache.m2.4xlarge</code>
* </p>
* </li>
* </ul>
* </li>
* </ul>
* <p>
* <b>Notes:</b>
* </p>
* <ul>
* <li>
* <p>
* All T2 instances are created in an Amazon Virtual Private Cloud (Amazon VPC).
* </p>
* </li>
* <li>
* <p>
* Redis backup/restore is not supported for Redis (cluster mode disabled) T1 and T2 instances.
* Backup/restore is supported on Redis (cluster mode enabled) T2 instances.
* </p>
* </li>
* <li>
* <p>
* Redis Append-only files (AOF) functionality is not supported for T1 or T2 instances.
* </p>
* </li>
* </ul>
* <p>
* For a complete listing of node types and specifications, see <a
* href="http://aws.amazon.com/elasticache/details">Amazon ElastiCache Product Features and Details</a> and
* either <a href=
* "http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Memcached.html#ParameterGroups.Memcached.NodeSpecific"
* >Cache Node Type-Specific Parameters for Memcached</a> or <a href=
* "http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Redis.html#ParameterGroups.Redis.NodeSpecific"
* >Cache Node Type-Specific Parameters for Redis</a>.
*/
public String getCacheNodeType() {
return this.cacheNodeType;
}
/**
* <p>
* The cache node type for the reserved cache node.
* </p>
* <p>
* Valid node types are as follows:
* </p>
* <ul>
* <li>
* <p>
* General purpose:
* </p>
* <ul>
* <li>
* <p>
* Current generation: <code>cache.t2.micro</code>, <code>cache.t2.small</code>, <code>cache.t2.medium</code>,
* <code>cache.m3.medium</code>, <code>cache.m3.large</code>, <code>cache.m3.xlarge</code>,
* <code>cache.m3.2xlarge</code>, <code>cache.m4.large</code>, <code>cache.m4.xlarge</code>,
* <code>cache.m4.2xlarge</code>, <code>cache.m4.4xlarge</code>, <code>cache.m4.10xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Previous generation: <code>cache.t1.micro</code>, <code>cache.m1.small</code>, <code>cache.m1.medium</code>,
* <code>cache.m1.large</code>, <code>cache.m1.xlarge</code>
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Compute optimized: <code>cache.c1.xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Memory optimized:
* </p>
* <ul>
* <li>
* <p>
* Current generation: <code>cache.r3.large</code>, <code>cache.r3.xlarge</code>, <code>cache.r3.2xlarge</code>,
* <code>cache.r3.4xlarge</code>, <code>cache.r3.8xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Previous generation: <code>cache.m2.xlarge</code>, <code>cache.m2.2xlarge</code>, <code>cache.m2.4xlarge</code>
* </p>
* </li>
* </ul>
* </li>
* </ul>
* <p>
* <b>Notes:</b>
* </p>
* <ul>
* <li>
* <p>
* All T2 instances are created in an Amazon Virtual Private Cloud (Amazon VPC).
* </p>
* </li>
* <li>
* <p>
* Redis backup/restore is not supported for Redis (cluster mode disabled) T1 and T2 instances. Backup/restore is
* supported on Redis (cluster mode enabled) T2 instances.
* </p>
* </li>
* <li>
* <p>
* Redis Append-only files (AOF) functionality is not supported for T1 or T2 instances.
* </p>
* </li>
* </ul>
* <p>
* For a complete listing of node types and specifications, see <a
* href="http://aws.amazon.com/elasticache/details">Amazon ElastiCache Product Features and Details</a> and either
* <a href=
* "http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Memcached.html#ParameterGroups.Memcached.NodeSpecific"
* >Cache Node Type-Specific Parameters for Memcached</a> or <a href=
* "http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Redis.html#ParameterGroups.Redis.NodeSpecific"
* >Cache Node Type-Specific Parameters for Redis</a>.
* </p>
*
* @param cacheNodeType
* The cache node type for the reserved cache node.</p>
* <p>
* Valid node types are as follows:
* </p>
* <ul>
* <li>
* <p>
* General purpose:
* </p>
* <ul>
* <li>
* <p>
* Current generation: <code>cache.t2.micro</code>, <code>cache.t2.small</code>, <code>cache.t2.medium</code>, <code>cache.m3.medium</code>, <code>cache.m3.large</code>, <code>cache.m3.xlarge</code>,
* <code>cache.m3.2xlarge</code>, <code>cache.m4.large</code>, <code>cache.m4.xlarge</code>,
* <code>cache.m4.2xlarge</code>, <code>cache.m4.4xlarge</code>, <code>cache.m4.10xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Previous generation: <code>cache.t1.micro</code>, <code>cache.m1.small</code>,
* <code>cache.m1.medium</code>, <code>cache.m1.large</code>, <code>cache.m1.xlarge</code>
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Compute optimized: <code>cache.c1.xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Memory optimized:
* </p>
* <ul>
* <li>
* <p>
* Current generation: <code>cache.r3.large</code>, <code>cache.r3.xlarge</code>,
* <code>cache.r3.2xlarge</code>, <code>cache.r3.4xlarge</code>, <code>cache.r3.8xlarge</code>
* </p>
* </li>
* <li>
* <p>
* Previous generation: <code>cache.m2.xlarge</code>, <code>cache.m2.2xlarge</code>,
* <code>cache.m2.4xlarge</code>
* </p>
* </li>
* </ul>
* </li>
* </ul>
* <p>
* <b>Notes:</b>
* </p>
* <ul>
* <li>
* <p>
* All T2 instances are created in an Amazon Virtual Private Cloud (Amazon VPC).
* </p>
* </li>
* <li>
* <p>
* Redis backup/restore is not supported for Redis (cluster mode disabled) T1 and T2 instances.
* Backup/restore is supported on Redis (cluster mode enabled) T2 instances.
* </p>
* </li>
* <li>
* <p>
* Redis Append-only files (AOF) functionality is not supported for T1 or T2 instances.
* </p>
* </li>
* </ul>
* <p>
* For a complete listing of node types and specifications, see <a
* href="http://aws.amazon.com/elasticache/details">Amazon ElastiCache Product Features and Details</a> and
* either <a href=
* "http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Memcached.html#ParameterGroups.Memcached.NodeSpecific"
* >Cache Node Type-Specific Parameters for Memcached</a> or <a href=
* "http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/CacheParameterGroups.Redis.html#ParameterGroups.Redis.NodeSpecific"
* >Cache Node Type-Specific Parameters for Redis</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ReservedCacheNodesOffering withCacheNodeType(String cacheNodeType) {
setCacheNodeType(cacheNodeType);
return this;
}
/**
* <p>
* The duration of the offering. in seconds.
* </p>
*
* @param duration
* The duration of the offering. in seconds.
*/
public void setDuration(Integer duration) {
this.duration = duration;
}
/**
* <p>
* The duration of the offering. in seconds.
* </p>
*
* @return The duration of the offering. in seconds.
*/
public Integer getDuration() {
return this.duration;
}
/**
* <p>
* The duration of the offering. in seconds.
* </p>
*
* @param duration
* The duration of the offering. in seconds.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ReservedCacheNodesOffering withDuration(Integer duration) {
setDuration(duration);
return this;
}
/**
* <p>
* The fixed price charged for this offering.
* </p>
*
* @param fixedPrice
* The fixed price charged for this offering.
*/
public void setFixedPrice(Double fixedPrice) {
this.fixedPrice = fixedPrice;
}
/**
* <p>
* The fixed price charged for this offering.
* </p>
*
* @return The fixed price charged for this offering.
*/
public Double getFixedPrice() {
return this.fixedPrice;
}
/**
* <p>
* The fixed price charged for this offering.
* </p>
*
* @param fixedPrice
* The fixed price charged for this offering.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ReservedCacheNodesOffering withFixedPrice(Double fixedPrice) {
setFixedPrice(fixedPrice);
return this;
}
/**
* <p>
* The hourly price charged for this offering.
* </p>
*
* @param usagePrice
* The hourly price charged for this offering.
*/
public void setUsagePrice(Double usagePrice) {
this.usagePrice = usagePrice;
}
/**
* <p>
* The hourly price charged for this offering.
* </p>
*
* @return The hourly price charged for this offering.
*/
public Double getUsagePrice() {
return this.usagePrice;
}
/**
* <p>
* The hourly price charged for this offering.
* </p>
*
* @param usagePrice
* The hourly price charged for this offering.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ReservedCacheNodesOffering withUsagePrice(Double usagePrice) {
setUsagePrice(usagePrice);
return this;
}
/**
* <p>
* The cache engine used by the offering.
* </p>
*
* @param productDescription
* The cache engine used by the offering.
*/
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
/**
* <p>
* The cache engine used by the offering.
* </p>
*
* @return The cache engine used by the offering.
*/
public String getProductDescription() {
return this.productDescription;
}
/**
* <p>
* The cache engine used by the offering.
* </p>
*
* @param productDescription
* The cache engine used by the offering.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ReservedCacheNodesOffering withProductDescription(String productDescription) {
setProductDescription(productDescription);
return this;
}
/**
* <p>
* The offering type.
* </p>
*
* @param offeringType
* The offering type.
*/
public void setOfferingType(String offeringType) {
this.offeringType = offeringType;
}
/**
* <p>
* The offering type.
* </p>
*
* @return The offering type.
*/
public String getOfferingType() {
return this.offeringType;
}
/**
* <p>
* The offering type.
* </p>
*
* @param offeringType
* The offering type.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ReservedCacheNodesOffering withOfferingType(String offeringType) {
setOfferingType(offeringType);
return this;
}
/**
* <p>
* The recurring price charged to run this reserved cache node.
* </p>
*
* @return The recurring price charged to run this reserved cache node.
*/
public java.util.List<RecurringCharge> getRecurringCharges() {
if (recurringCharges == null) {
recurringCharges = new com.amazonaws.internal.SdkInternalList<RecurringCharge>();
}
return recurringCharges;
}
/**
* <p>
* The recurring price charged to run this reserved cache node.
* </p>
*
* @param recurringCharges
* The recurring price charged to run this reserved cache node.
*/
public void setRecurringCharges(java.util.Collection<RecurringCharge> recurringCharges) {
if (recurringCharges == null) {
this.recurringCharges = null;
return;
}
this.recurringCharges = new com.amazonaws.internal.SdkInternalList<RecurringCharge>(recurringCharges);
}
/**
* <p>
* The recurring price charged to run this reserved cache node.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setRecurringCharges(java.util.Collection)} or {@link #withRecurringCharges(java.util.Collection)} if you
* want to override the existing values.
* </p>
*
* @param recurringCharges
* The recurring price charged to run this reserved cache node.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ReservedCacheNodesOffering withRecurringCharges(RecurringCharge... recurringCharges) {
if (this.recurringCharges == null) {
setRecurringCharges(new com.amazonaws.internal.SdkInternalList<RecurringCharge>(recurringCharges.length));
}
for (RecurringCharge ele : recurringCharges) {
this.recurringCharges.add(ele);
}
return this;
}
/**
* <p>
* The recurring price charged to run this reserved cache node.
* </p>
*
* @param recurringCharges
* The recurring price charged to run this reserved cache node.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ReservedCacheNodesOffering withRecurringCharges(java.util.Collection<RecurringCharge> recurringCharges) {
setRecurringCharges(recurringCharges);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getReservedCacheNodesOfferingId() != null)
sb.append("ReservedCacheNodesOfferingId: ").append(getReservedCacheNodesOfferingId()).append(",");
if (getCacheNodeType() != null)
sb.append("CacheNodeType: ").append(getCacheNodeType()).append(",");
if (getDuration() != null)
sb.append("Duration: ").append(getDuration()).append(",");
if (getFixedPrice() != null)
sb.append("FixedPrice: ").append(getFixedPrice()).append(",");
if (getUsagePrice() != null)
sb.append("UsagePrice: ").append(getUsagePrice()).append(",");
if (getProductDescription() != null)
sb.append("ProductDescription: ").append(getProductDescription()).append(",");
if (getOfferingType() != null)
sb.append("OfferingType: ").append(getOfferingType()).append(",");
if (getRecurringCharges() != null)
sb.append("RecurringCharges: ").append(getRecurringCharges());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ReservedCacheNodesOffering == false)
return false;
ReservedCacheNodesOffering other = (ReservedCacheNodesOffering) obj;
if (other.getReservedCacheNodesOfferingId() == null ^ this.getReservedCacheNodesOfferingId() == null)
return false;
if (other.getReservedCacheNodesOfferingId() != null && other.getReservedCacheNodesOfferingId().equals(this.getReservedCacheNodesOfferingId()) == false)
return false;
if (other.getCacheNodeType() == null ^ this.getCacheNodeType() == null)
return false;
if (other.getCacheNodeType() != null && other.getCacheNodeType().equals(this.getCacheNodeType()) == false)
return false;
if (other.getDuration() == null ^ this.getDuration() == null)
return false;
if (other.getDuration() != null && other.getDuration().equals(this.getDuration()) == false)
return false;
if (other.getFixedPrice() == null ^ this.getFixedPrice() == null)
return false;
if (other.getFixedPrice() != null && other.getFixedPrice().equals(this.getFixedPrice()) == false)
return false;
if (other.getUsagePrice() == null ^ this.getUsagePrice() == null)
return false;
if (other.getUsagePrice() != null && other.getUsagePrice().equals(this.getUsagePrice()) == false)
return false;
if (other.getProductDescription() == null ^ this.getProductDescription() == null)
return false;
if (other.getProductDescription() != null && other.getProductDescription().equals(this.getProductDescription()) == false)
return false;
if (other.getOfferingType() == null ^ this.getOfferingType() == null)
return false;
if (other.getOfferingType() != null && other.getOfferingType().equals(this.getOfferingType()) == false)
return false;
if (other.getRecurringCharges() == null ^ this.getRecurringCharges() == null)
return false;
if (other.getRecurringCharges() != null && other.getRecurringCharges().equals(this.getRecurringCharges()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getReservedCacheNodesOfferingId() == null) ? 0 : getReservedCacheNodesOfferingId().hashCode());
hashCode = prime * hashCode + ((getCacheNodeType() == null) ? 0 : getCacheNodeType().hashCode());
hashCode = prime * hashCode + ((getDuration() == null) ? 0 : getDuration().hashCode());
hashCode = prime * hashCode + ((getFixedPrice() == null) ? 0 : getFixedPrice().hashCode());
hashCode = prime * hashCode + ((getUsagePrice() == null) ? 0 : getUsagePrice().hashCode());
hashCode = prime * hashCode + ((getProductDescription() == null) ? 0 : getProductDescription().hashCode());
hashCode = prime * hashCode + ((getOfferingType() == null) ? 0 : getOfferingType().hashCode());
hashCode = prime * hashCode + ((getRecurringCharges() == null) ? 0 : getRecurringCharges().hashCode());
return hashCode;
}
@Override
public ReservedCacheNodesOffering clone() {
try {
return (ReservedCacheNodesOffering) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| |
/*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.guvnor.ala.ui.client.wizard.source;
import static org.guvnor.ala.ui.client.util.UIUtil.EMPTY_STRING;
import static org.junit.Assert.assertEquals;
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;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gwtmockito.GwtMockitoTestRunner;
import org.guvnor.ala.ui.client.util.ContentChangeHandler;
import org.guvnor.ala.ui.client.widget.FormStatus;
import org.guvnor.ala.ui.client.wizard.NewDeployWizard;
import org.guvnor.ala.ui.service.SourceService;
import org.guvnor.common.services.project.model.Module;
import org.jboss.errai.common.client.api.Caller;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.uberfire.mocks.CallerMock;
import org.uberfire.spaces.Space;
@RunWith(GwtMockitoTestRunner.class)
public class SourceConfigurationParamsPresenterTest {
private static final int ELEMENTS_SIZE = 5;
private static final String SOME_VALUE = "SOME_VALUE";
private static final String RUNTIME_NAME = "RUNTIME_NAME";
private static final String OU = "OU";
private static final String REPOSITORY = "REPOSITORY";
private static final String BRANCH = "BRANCH";
private static final String MODULE = "PROJECT";
private static final Space SPACE = new Space(OU);
@Mock
private SourceConfigurationParamsPresenter.View view;
@Mock
private SourceService sourceService;
private Caller<SourceService> sourceServiceCaller;
@Mock
private ContentChangeHandler changeHandler;
private SourceConfigurationParamsPresenter presenter;
private List<String> ous;
private List<String> repositories;
private List<String> branches;
private List<Module> modules;
@Before
public void setUp() {
ous = createOUs();
repositories = createRepositories();
branches = createBranches();
modules = createModules();
sourceServiceCaller = spy(new CallerMock<>(sourceService));
presenter = new SourceConfigurationParamsPresenter(view,
sourceServiceCaller);
presenter.addContentChangeHandler(changeHandler);
presenter.init();
verify(view,
times(1)).init(presenter);
}
@Test
public void testInitialize() {
when(sourceService.getOrganizationUnits()).thenReturn(ous);
presenter.initialise();
ous.forEach(ou -> verify(view,
times(1)).addOrganizationUnit(ou));
verify(view,
times(1)).clearOrganizationUnits();
verify(view,
times(1)).clearRepositories();
verify(view,
times(1)).clearBranches();
verify(view,
times(1)).clearModules();
}
@Test
public void testIsComplete() {
when(view.getRuntimeName()).thenReturn(EMPTY_STRING);
when(view.getOU()).thenReturn(EMPTY_STRING);
when(view.getRepository()).thenReturn(EMPTY_STRING);
when(view.getBranch()).thenReturn(EMPTY_STRING);
when(view.getModule()).thenReturn(EMPTY_STRING);
presenter.isComplete(Assert::assertFalse);
when(view.getRuntimeName()).thenReturn(SOME_VALUE);
presenter.isComplete(Assert::assertFalse);
when(view.getOU()).thenReturn(OU);
presenter.isComplete(Assert::assertFalse);
when(view.getRepository()).thenReturn(REPOSITORY);
presenter.isComplete(Assert::assertFalse);
//now the branch is completed and emulate the projects are loaded.
when(view.getBranch()).thenReturn(BRANCH);
when(sourceService.getModules(eq(SPACE),
eq(REPOSITORY),
eq(BRANCH))).thenReturn(modules);
presenter.onBranchChange();
//pick an arbitrary project as the selected one
int selectedModule = 1;
String moduleName = modules.get(selectedModule).getModuleName();
when(view.getModule()).thenReturn(moduleName);
//completed when al values are in place.
presenter.isComplete(Assert::assertTrue);
}
@Test
public void testBuildParams() {
//emulate the page is completed and that there is a selected project.
when(view.getRuntimeName()).thenReturn(RUNTIME_NAME);
when(view.getOU()).thenReturn(OU);
when(view.getRepository()).thenReturn(REPOSITORY);
when(view.getBranch()).thenReturn(BRANCH);
when(sourceService.getModules(eq(SPACE),
eq(REPOSITORY),
eq(BRANCH))).thenReturn(modules);
when(view.getModule()).thenReturn(MODULE);
presenter.onBranchChange();
//pick an arbitrary project as the selected one
int selectedModule = 2;
String moduleName = modules.get(selectedModule).getModuleName();
when(view.getModule()).thenReturn(moduleName);
Map<String, String> params = presenter.buildParams();
assertEquals(RUNTIME_NAME,
params.get(NewDeployWizard.RUNTIME_NAME));
assertEquals(REPOSITORY,
params.get(SourceConfigurationParamsPresenter.REPO_NAME));
assertEquals(BRANCH,
params.get(SourceConfigurationParamsPresenter.BRANCH));
assertEquals(moduleName,
params.get(SourceConfigurationParamsPresenter.MODULE_DIR));
}
@Test
public void testClear() {
presenter.clear();
verify(view,
times(1)).clear();
}
@Test
public void testDisable() {
presenter.disable();
verify(view,
times(1)).disable();
}
@Test
public void testOnRuntimeChangeValid() {
when(view.getRuntimeName()).thenReturn(RUNTIME_NAME);
presenter.onRuntimeNameChange();
verify(view,
times(1)).setRuntimeStatus(FormStatus.VALID);
verifyHandlerNotified();
}
@Test
public void testOnRuntimeChangeInvalid() {
when(view.getRuntimeName()).thenReturn(EMPTY_STRING);
presenter.onRuntimeNameChange();
verify(view,
times(1)).setRuntimeStatus(FormStatus.ERROR);
verifyHandlerNotified();
}
@Test
public void testOnOrganizationalUnitChangeValid() {
when(view.getOU()).thenReturn(OU);
when(sourceService.getRepositories(OU)).thenReturn(repositories);
presenter.onOrganizationalUnitChange();
verify(view,
times(1)).setOUStatus(FormStatus.VALID);
verify(view,
times(2)).getOU();
verify(view,
times(2)).clearRepositories();
verify(view,
times(2)).clearBranches();
verify(view,
times(2)).clearModules();
verityRepositoriesWereLoaded();
verifyHandlerNotified();
}
@Test
public void testOnOrganizationalUnitChangeInvalid() {
when(view.getOU()).thenReturn(EMPTY_STRING);
presenter.onOrganizationalUnitChange();
verify(view,
times(1)).setOUStatus(FormStatus.ERROR);
verifyHandlerNotified();
}
@Test
public void testOnRepositoryChangeValid() {
when(view.getRepository()).thenReturn(REPOSITORY);
when(view.getOU()).thenReturn(OU);
when(sourceService.getBranches(eq(SPACE), eq(REPOSITORY))).thenReturn(branches);
presenter.onRepositoryChange();
verify(view,
times(1)).setRepositoryStatus(FormStatus.VALID);
verify(view,
times(2)).clearBranches();
verify(view,
times(2)).clearModules();
verifyBranchesWereLoaded();
verifyHandlerNotified();
}
@Test
public void testOnRepositoryChangeInvalid() {
when(view.getRepository()).thenReturn(EMPTY_STRING);
presenter.onRepositoryChange();
verify(view,
times(1)).setRepositoryStatus(FormStatus.ERROR);
verifyHandlerNotified();
}
@Test
public void testOnBranchChangeValid() {
when(view.getOU()).thenReturn(OU);
when(view.getRepository()).thenReturn(REPOSITORY);
when(view.getBranch()).thenReturn(BRANCH);
when(sourceService.getModules(eq(SPACE),
eq(REPOSITORY),
eq(BRANCH))).thenReturn(modules);
presenter.onBranchChange();
verify(view,
times(1)).setBranchStatus(FormStatus.VALID);
verify(view,
times(2)).clearModules();
verifyProjectsWereLoaded();
verifyHandlerNotified();
}
@Test
public void testOnBranchChangeInvalid() {
when(view.getBranch()).thenReturn(EMPTY_STRING);
presenter.onBranchChange();
verify(view,
times(1)).setBranchStatus(FormStatus.ERROR);
verifyHandlerNotified();
}
@Test
public void testOnProjectChangeValid() {
when(view.getModule()).thenReturn(MODULE);
presenter.onModuleChange();
verify(view,
times(1)).setProjectStatus(FormStatus.VALID);
verifyHandlerNotified();
}
@Test
public void testOnProjectChangeInValid() {
when(view.getModule()).thenReturn(EMPTY_STRING);
presenter.onModuleChange();
verify(view,
times(1)).setProjectStatus(FormStatus.ERROR);
verifyHandlerNotified();
}
private void verityRepositoriesWereLoaded() {
repositories.forEach(repository -> verify(view,
times(1)).addRepository(repository));
}
private void verifyBranchesWereLoaded() {
branches.forEach(branch -> verify(view,
times(1)).addBranch(branch));
}
private void verifyProjectsWereLoaded() {
modules.forEach(module -> verify(view,
times(1)).addModule(module.getModuleName()));
}
private List<String> createOUs() {
return createValues(ELEMENTS_SIZE,
"OU.name.");
}
private List<String> createRepositories() {
return createValues(ELEMENTS_SIZE,
"REPO.name.");
}
private List<String> createBranches() {
return createValues(ELEMENTS_SIZE,
"Branch.name.");
}
private List<Module> createModules() {
List<Module> elements = new ArrayList<>();
for (int i = 0; i < ELEMENTS_SIZE; i++) {
Module module = mock(Module.class);
when(module.getModuleName()).thenReturn("Module.name." + i);
elements.add(module);
}
return elements;
}
private List<String> createValues(int size,
String PREFIX) {
List<String> elements = new ArrayList<>();
for (int i = 0; i < size; i++) {
elements.add(PREFIX + i);
}
return elements;
}
private void verifyHandlerNotified() {
verify(changeHandler,
times(1)).onContentChange();
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.projectflink.spark;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.broadcast.Broadcast;
import scala.Tuple2;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
public class KMeansArbitraryDimension {
public static void main(String[] args) {
if(!parseParameters(args)) {
return;
}
SparkConf conf = new SparkConf().setAppName("KMeans").setMaster(master);
JavaSparkContext sc = new JavaSparkContext(conf);
// ================================ Standard KMeans =============================
JavaRDD<Point> points = sc
.textFile(pointsPath)
.map(new ConvertToPoint());
JavaPairRDD<Integer, Point> kCenters = sc
.textFile(centersPath)
.mapToPair(new ConvertToCentroid());
for(int i=0; i<numIterations; ++i) {
Broadcast<List<Tuple2<Integer, Point>>> brCenters = sc.broadcast(kCenters.collect());
kCenters = points
// compute closest centroid for each point
.mapToPair(new SelectNearestCentroid(brCenters))
// count and sum point coordinates for each centroid
.mapToPair(new CountAppender())
.reduceByKey(new CentroidSum())
// calculate the mean( the new center ) of each cluster
.mapToPair(new CentroidAverage());
brCenters.unpersist();
}
// kCenters.saveAsTextFile(outputPath);
Broadcast<List<Tuple2<Integer, Point>>> brCenters = sc.broadcast(kCenters.collect());
JavaPairRDD<Integer, Point> clusteredPoints = points.mapToPair(new SelectNearestCentroid(brCenters));
clusteredPoints.saveAsTextFile(outputPath);
}
/** Convert String value into data point **/
public static final class ConvertToPoint implements Function<String, Point> {
@Override
public Point call(String s) throws Exception {
String [] line = s.split(" ");
double [] points = new double[line.length - 1];
for (int i = 1; i < line.length; i++) {
points[i - 1] = Double.parseDouble(line[i]);
}
return new Point(points);
}
}
/** Convert String value into data centroid **/
public static final class ConvertToCentroid implements PairFunction<String, Integer, Point> {
@Override
public Tuple2<Integer, Point> call(String s) throws Exception {
String [] line = s.split(" ");
int id = Integer.parseInt(line[0]);
double [] points = new double[line.length - 1];
for (int i = 1; i < line.length; i++) {
points[i - 1] = Double.parseDouble(line[i]);
}
return new Tuple2<Integer, Point>(id, new Point(points));
}
}
/**
* Assign each point to its closest center
*
*/
public static final class SelectNearestCentroid implements PairFunction<Point, Integer, Point> {
Broadcast<List<Tuple2<Integer, Point>>> brCenters;
public SelectNearestCentroid(Broadcast<List<Tuple2<Integer, Point>>> brCenters) {
this.brCenters = brCenters;
}
public Tuple2<Integer, Point> call(Point v1) throws Exception {
double minDistance = Double.MAX_VALUE;
int centerId = 0;
for(Tuple2<Integer, Point> c : brCenters.getValue()) {
double d = v1.euclideanDistance(c._2());
if(minDistance > d) {
minDistance = d;
centerId = c._1();
}
}
return new Tuple2<Integer, Point>(centerId, v1);
}
}
/**
* Appends a count variable to the tuple.
*/
public static final class CountAppender implements PairFunction<Tuple2<Integer, Point>, Integer, Tuple2<Point, Integer>> {
@Override
public Tuple2<Integer, Tuple2<Point, Integer>> call(Tuple2<Integer, Point> t) throws Exception {
return new Tuple2<Integer, Tuple2<Point, Integer>>(t._1(), new Tuple2<Point, Integer>(t._2(), 1));
}
}
/**
* Aggregate(sum) all the points in each cluster for calculating mean
*
*/
public static final class CentroidSum implements Function2<Tuple2<Point, Integer>, Tuple2<Point, Integer>, Tuple2<Point, Integer>> {
@Override
public Tuple2<Point, Integer> call(Tuple2<Point, Integer> v1, Tuple2<Point, Integer> v2) throws Exception {
return new Tuple2<Point, Integer>(v1._1().add(v2._1()), v1._2() + v2._2());
}
}
/**
* Calculate the mean(new center) of the cluster ( sum of points / number of points )
*
*/
public static final class CentroidAverage implements PairFunction<Tuple2<Integer, Tuple2<Point, Integer>>, Integer, Point> {
@Override
public Tuple2<Integer, Point> call(Tuple2<Integer, Tuple2<Point, Integer>> t) throws Exception {
t._2()._1().div(t._2()._2());
return new Tuple2<Integer, Point>(t._1(), t._2()._1());
}
}
// *************************************************************************
// DATA TYPES
// *************************************************************************
public static class Point implements Serializable {
public double [] points;
public Point() {}
public Point(double [] points) {
this.points = points;
}
public Point add(Point other) {
for (int i = 0; i < points.length; i++) {
points[i] = points[i] + other.points[i];
}
return this;
}
public Point div(long val) {
for (int i = 0; i < points.length; i++) {
points[i] = points[i] / val;
}
return this;
}
public double euclideanDistance(Point other) {
double sum = 0;
for (int i = 0; i < points.length; i++) {
sum = sum + (points[i] - other.points[i]) * (points[i] - other.points[i]);
}
return Math.sqrt(sum);
}
@Override
public String toString() {
return Arrays.toString(points);
}
}
// *************************************************************************
// UTIL METHODS
// *************************************************************************
private static String master = null;
private static String pointsPath = null;
private static String centersPath = null;
private static String outputPath = null;
private static int numIterations = 10;
private static boolean parseParameters(String[] programArguments) {
// parse input arguments
if(programArguments.length == 5) {
master = programArguments[0];
pointsPath = programArguments[1];
centersPath = programArguments[2];
outputPath = programArguments[3];
numIterations = Integer.parseInt(programArguments[4]);
} else {
System.err.println("Usage: KMeans <master> <points path> <centers path> <result path> <num iterations>");
return false;
}
return true;
}
}
| |
/*
* Copyright 2014 Alexey Plotnik
*
* 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.stem.client;
import com.google.common.util.concurrent.AbstractFuture;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.Timer;
import io.netty.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.nio.channels.ClosedChannelException;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class Connection {
private static final Logger logger = LoggerFactory.getLogger(Connection.class);
private final String name;
public final InetSocketAddress address;
private final Factory factory;
private final Channel channel;
private final Dispatcher dispatcher;
private volatile boolean isInitialized;
private volatile boolean isDefunct;
private final AtomicReference<ConnectionCloseFuture> closeFutureRef = new AtomicReference<>();
public final AtomicInteger inFlight = new AtomicInteger(0);
private final AtomicInteger writeCounter = new AtomicInteger(0);
private final Object terminationLock = new Object();
public Connection(String name, InetSocketAddress address, Factory factory) throws ConnectionException {
this.name = name;
this.address = address;
this.factory = factory;
dispatcher = new Dispatcher();
Bootstrap bootstrap = factory.createNewBootstrap();
bootstrap.handler(new ChannelHandler(this));
ChannelFuture future = bootstrap.connect(address);
writeCounter.incrementAndGet();
try {
this.channel = future.awaitUninterruptibly().channel();
if (!future.isSuccess()) {
if (logger.isDebugEnabled())
logger.debug(String.format("%s Error connecting to %s%s", this, address, extractMessage(future.cause())));
throw defunct(new ClientTransportException(address, "Can't connect", future.cause()));
}
}
finally {
writeCounter.decrementAndGet();
}
logger.trace("{} Connection opened successfully", this);
isInitialized = true;
}
private static String extractMessage(Throwable t) {
if (t == null)
return "";
String msg = t.getMessage() == null || t.getMessage().isEmpty()
? t.toString()
: t.getMessage();
return " (" + msg + ')';
}
public int maxAvailableStreams() {
return dispatcher.streamIdPool.maxAvailableStreams();
}
<E extends Exception> E defunct(E e) {
if (logger.isDebugEnabled())
logger.debug("Defuncting connection to " + address, e);
isDefunct = true;
ConnectionException ce = e instanceof ConnectionException
? (ConnectionException) e
: new ConnectionException(address, "Connection problem", e);
Host host = factory.manager.metadata.getHost(address);
if (host != null) {
boolean isReconnectionAttempt = (host.state == Host.State.DOWN || host.state == Host.State.SUSPECT)
&& !(this instanceof PooledConnection);
if (!isReconnectionAttempt) {
boolean isDown = factory.manager.signalConnectionFailure(host, ce, host.wasJustAdded(), isInitialized);
notifyOwnerWhenDefunct(isDown);
}
}
closeAsync().force();
return e;
}
public boolean isDefunct() {
return isDefunct;
}
public Future write(Message.Request request) throws ConnectionBusyException, ConnectionException {
Future future = new Future(request);
write(future);
return future;
}
public ResponseHandler write(ResponseCallback callback) throws ConnectionBusyException, ConnectionException {
Message.Request request = callback.request();
ResponseHandler responseHandler = new ResponseHandler(this, callback);
dispatcher.addHandler(responseHandler);
request.setStreamId(responseHandler.streamId);
if (isDefunct) {
dispatcher.removeHandler(responseHandler.streamId, true);
throw new ConnectionException(address, "Writing on deactivated connection");
}
if (isClosed()) {
dispatcher.removeHandler(responseHandler.streamId, true);
throw new ConnectionException(address, "Connection has been closed");
}
logger.trace("{} writing request {}", this, request);
writeCounter.incrementAndGet();
channel.writeAndFlush(request).addListener(writeHandler(request, responseHandler));
return responseHandler;
}
private ChannelFutureListener writeHandler(final Message.Request request, final ResponseHandler handler) {
return new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
writeCounter.decrementAndGet();
if (!future.isSuccess()) {
logger.debug("{} Error writing request {}", Connection.this, request);
dispatcher.removeHandler(handler.streamId, true);
ConnectionException e;
if (future.cause() instanceof ClosedChannelException) {
e = new ClientTransportException(address, "Error writing to closed channel");
} else {
e = new ClientTransportException(address, "Error writing", future.cause());
}
// No retries yet
handler.callback.onException(Connection.this, defunct(e), System.nanoTime() - handler.startTime);
} else {
logger.trace("{} request sent successfully", Connection.this);
}
}
};
}
public CloseFuture closeAsync() {
ConnectionCloseFuture future = new ConnectionCloseFuture();
if (!closeFutureRef.compareAndSet(null, future)) {
return closeFutureRef.get();
}
logger.debug("{} closing connection", this);
boolean terminated = terminate(false);
// TODO:
//if (!terminated)
//factory.reaper.register(this);
if (dispatcher.pending.isEmpty())
future.force();
return future;
}
private boolean terminate(boolean evenIfPending) {
assert isClosed();
ConnectionCloseFuture future = closeFutureRef.get();
if (future.isDone()) {
logger.debug("{} has already terminated", this);
return true;
} else {
synchronized (terminationLock) {
if (evenIfPending || dispatcher.pending.isEmpty()) {
future.force();
// Bug ?
return true;
} else {
logger.debug("Not terminating {}: there are still pending requests", this);
return false;
}
}
}
}
public boolean isClosed() {
return closeFutureRef.get() != null;
}
protected void notifyOwnerWhenDefunct(boolean hostIsDown) {
}
@Override
public String toString() {
return String.format("Connection[%s, inFlight=%d, closed=%b]", name, inFlight.get(), isClosed());
}
/**
*
*/
private class ConnectionCloseFuture extends CloseFuture {
@Override
public ConnectionCloseFuture force() {
if (null == channel) {
set(null);
return this;
}
ChannelFuture future = channel.close();
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.cause() != null)
ConnectionCloseFuture.this.setException(future.cause());
else
ConnectionCloseFuture.this.set(null);
}
});
return this;
}
}
/**
*
*/
public static class ChannelHandler extends ChannelInitializer<SocketChannel> {
private Connection connection;
public ChannelHandler(Connection connection) {
this.connection = connection;
}
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("packetDecoder", new Frame.Decoder());
pipeline.addLast("packetEncoder", new Frame.Encoder());
pipeline.addLast("messageDecoder", new Message.ProtocolDecoder());
pipeline.addLast("messageEncoder", new Message.ProtocolEncoder());
pipeline.addLast("dispatcher", connection.dispatcher);
}
}
/**
*
*/
public static class Factory {
public static final long TIMER_RESOLUTION = 100L;
EventLoopGroup workerGroup = new NioEventLoopGroup();
private StemCluster.Manager manager;
private final Configuration configuration;
public final Timer timer = new HashedWheelTimer(new ThreadFactoryBuilder().setNameFormat("Timeouter-%d").build(), TIMER_RESOLUTION, TimeUnit.MILLISECONDS);
private volatile boolean isShutdown;
private InetSocketAddress address;
private final ConcurrentMap<Host, AtomicInteger> idGenerators = new ConcurrentHashMap<>();
public Factory(StemCluster.Manager manager, Configuration configuration) {
this.manager = manager;
this.configuration = configuration;
}
public Connection open(Host host) throws ConnectionException {
address = host.getSocketAddress();
if (isShutdown)
throw new ConnectionException(address, "Connection factory is shut down");
String name = address.toString() + '-' + getIdGenerator(host).getAndIncrement();
return new Connection(name, address, this);
}
public PooledConnection open(ConnectionPool pool) throws ConnectionException, InterruptedException {
InetSocketAddress address = pool.host.getSocketAddress();
if (isShutdown)
throw new ConnectionException(address, "Connection factory is shut down");
String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement();
return new PooledConnection(name, address, this, pool);
}
public Bootstrap createNewBootstrap() {
SocketOpts opt = this.configuration.getSocketOpts();
Bootstrap bootstrap = new Bootstrap();
bootstrap
.group(workerGroup)
.channel(NioSocketChannel.class);
bootstrap
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, opt.getConnectTimeoutMs());
bootstrap.option(ChannelOption.SO_KEEPALIVE, true); // TODO: remove (for tests only)
bootstrap.option(ChannelOption.TCP_NODELAY, true); // TODO: remove (for tests only)
Boolean keepAlive = opt.getKeepAlive();
if (null != keepAlive)
bootstrap.option(ChannelOption.SO_KEEPALIVE, keepAlive);
Boolean reuseAddress = opt.getReuseAddress();
if (null != reuseAddress)
bootstrap.option(ChannelOption.SO_REUSEADDR, reuseAddress);
Integer soLinger = opt.getSoLinger();
if (null != soLinger)
bootstrap.option(ChannelOption.SO_LINGER, soLinger);
Boolean topNoDelay = opt.getTcpNoDelay();
if (null != topNoDelay)
bootstrap.option(ChannelOption.TCP_NODELAY, topNoDelay);
Integer receiveBufferSize = opt.getReceiveBufferSize();
if (null != receiveBufferSize)
bootstrap.option(ChannelOption.SO_RCVBUF, receiveBufferSize);
Integer sendBufferSize = opt.getSendBufferSize();
if (null != sendBufferSize)
bootstrap.option(ChannelOption.SO_SNDBUF, sendBufferSize);
return bootstrap;
}
public void shutdown() {
isShutdown = true;
workerGroup.shutdownGracefully().awaitUninterruptibly();
timer.stop();
}
public int getReadTimeoutMs() {
return configuration.getSocketOpts().getReadTimeoutMs();
}
private AtomicInteger getIdGenerator(Host host) {
AtomicInteger g = idGenerators.get(host);
if (g == null) {
g = new AtomicInteger(1);
AtomicInteger old = idGenerators.putIfAbsent(host, g);
if (old != null)
g = old;
}
return g;
}
}
/**
*
*/
private class Dispatcher extends SimpleChannelInboundHandler<Message.Response> {
private final ConcurrentMap<Integer, ResponseHandler> pending = new ConcurrentHashMap<Integer, ResponseHandler>();
public final StreamIdPool streamIdPool = new StreamIdPool();
public void addHandler(ResponseHandler handler) {
ResponseHandler oldHandler = pending.put(handler.streamId, handler);
assert null == oldHandler;
}
public void removeHandler(int streamId, boolean releaseStreamId) {
ResponseHandler removed = pending.remove(streamId);
if (null != removed) {
removed.cancelTimeout();
}
if (releaseStreamId) {
streamIdPool.release(streamId);
}
if (isClosed())
terminate(false);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Message.Response response) throws Exception {
int streamId = response.getStreamId();
logger.trace("{} received: {}", Connection.this, response);
if (streamId < 0) {
// TODO: Handle server-side streams
// factory.defaultHandler.handle(response);
return;
}
ResponseHandler handler = pending.remove(streamId);
streamIdPool.release(streamId);
if (null == handler) {
streamIdPool.unmark();
if (logger.isDebugEnabled())
logger.debug("{} Response received on stream {} but no handler set anymore (either the request has "
+ "timed out or it was closed due to another error). Received message is {}", Connection.this, streamId, asDebugString(response));
return;
}
handler.cancelTimeout();
handler.callback.onSet(Connection.this, response, System.nanoTime() - handler.startTime);
if (isClosed())
terminate(false);
}
private String asDebugString(Object obj) {
if (obj == null)
return "null";
String msg = obj.toString();
if (msg.length() < 500)
return msg;
return msg.substring(0, 500) + "... [message of size " + msg.length() + " truncated]";
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) throws Exception {
if (logger.isDebugEnabled())
logger.debug(String.format("%s connection error", Connection.this), e.getCause());
if (writeCounter.get() > 0)
return;
defunct(new ClientTransportException(address, String.format("Unexpected exception %s", e.getCause()), e.getCause()));
}
public void dropAllHandlers(ConnectionException e) {
Iterator<ResponseHandler> it = pending.values().iterator();
while (it.hasNext()) {
ResponseHandler handler = it.next();
handler.cancelTimeout();
handler.callback.onException(Connection.this, e, System.nanoTime() - handler.startTime);
it.remove();
}
}
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
// TODO: Should we do some work here?
logger.trace("Channel unregistered");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
ConnectionException closeException = new ClientTransportException(address, "Channel has been closed");
if (!isInitialized || isClosed()) {
dropAllHandlers(closeException);
Connection.this.closeAsync().force();
} else {
defunct(closeException);
}
}
}
/**
*
*/
static class Future extends AbstractFuture<Message.Response> implements RequestHandler.Callback {
private final Message.Request request;
private volatile InetSocketAddress address;
Future(Message.Request request) {
this.request = request;
}
@Override
public void register(RequestHandler handler) {
}
@Override
public void onSet(Connection connection, Message.Response response, ExecutionInfo info, long latency) {
onSet(connection, response, latency);
}
@Override
public void onSet(Connection connection, Message.Response response, long latency) {
this.address = connection.address;
super.set(response); // AbstractFuture
}
@Override
public Message.Request request() {
return null;
}
@Override
public void onException(Connection connection, Exception exception, long latency) {
super.setException(exception); // AbstractFuture
}
@Override
public void onTimeout(Connection connection, long latency) {
assert connection != null;
this.address = connection.address;
super.setException(new ConnectionException(connection.address, "Operation timed out"));
}
public InetSocketAddress getAddress() {
return address;
}
}
/**
*
*/
interface ResponseCallback {
public Message.Request request();
public void onSet(Connection connection, Message.Response response, long latency);
public void onException(Connection connection, Exception exception, long latency);
public void onTimeout(Connection connection, long latency);
}
/**
*
*/
static class ResponseHandler {
public final Connection connection;
public final ResponseCallback callback;
public final int streamId;
private final Timeout timeout;
private final long startTime;
ResponseHandler(Connection connection, ResponseCallback callback) throws ConnectionBusyException {
this.connection = connection;
this.callback = callback;
this.streamId = connection.dispatcher.streamIdPool.borrow();
long timeoutMs = connection.factory.getReadTimeoutMs();
this.timeout = connection.factory.timer.newTimeout(onTimeoutTask(), timeoutMs, TimeUnit.MILLISECONDS);
this.startTime = System.nanoTime();
}
/**
* Invoked by Dispatcher
*/
void cancelTimeout() {
if (null != timeout)
timeout.cancel();
}
public void cancelHandler() {
connection.dispatcher.removeHandler(streamId, false);
if (connection instanceof PooledConnection)
((PooledConnection) connection).release();
}
private TimerTask onTimeoutTask() {
return new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
callback.onTimeout(connection, System.nanoTime() - startTime);
cancelHandler();
}
};
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.redisenterprise.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.management.polling.PollResult;
import com.azure.core.util.Context;
import com.azure.core.util.polling.SyncPoller;
import com.azure.resourcemanager.redisenterprise.fluent.models.AccessKeysInner;
import com.azure.resourcemanager.redisenterprise.fluent.models.DatabaseInner;
import com.azure.resourcemanager.redisenterprise.models.DatabaseUpdate;
import com.azure.resourcemanager.redisenterprise.models.ExportClusterParameters;
import com.azure.resourcemanager.redisenterprise.models.ImportClusterParameters;
import com.azure.resourcemanager.redisenterprise.models.RegenerateKeyParameters;
/** An instance of this class provides access to all the operations defined in DatabasesClient. */
public interface DatabasesClient {
/**
* Gets all databases in the specified RedisEnterprise cluster.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.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 databases in the specified RedisEnterprise cluster.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<DatabaseInner> listByCluster(String resourceGroupName, String clusterName);
/**
* Gets all databases in the specified RedisEnterprise cluster.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.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 databases in the specified RedisEnterprise cluster.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<DatabaseInner> listByCluster(String resourceGroupName, String clusterName, Context context);
/**
* Creates a database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Parameters supplied to the create or update database operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return describes a database on the RedisEnterprise cluster.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<DatabaseInner>, DatabaseInner> beginCreate(
String resourceGroupName, String clusterName, String databaseName, DatabaseInner parameters);
/**
* Creates a database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Parameters supplied to the create or update database operation.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return describes a database on the RedisEnterprise cluster.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<DatabaseInner>, DatabaseInner> beginCreate(
String resourceGroupName, String clusterName, String databaseName, DatabaseInner parameters, Context context);
/**
* Creates a database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Parameters supplied to the create or update database operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return describes a database on the RedisEnterprise cluster.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
DatabaseInner create(String resourceGroupName, String clusterName, String databaseName, DatabaseInner parameters);
/**
* Creates a database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Parameters supplied to the create or update database operation.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return describes a database on the RedisEnterprise cluster.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
DatabaseInner create(
String resourceGroupName, String clusterName, String databaseName, DatabaseInner parameters, Context context);
/**
* Updates a database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Parameters supplied to the create or update database operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return describes a database on the RedisEnterprise cluster.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<DatabaseInner>, DatabaseInner> beginUpdate(
String resourceGroupName, String clusterName, String databaseName, DatabaseUpdate parameters);
/**
* Updates a database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Parameters supplied to the create or update database operation.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return describes a database on the RedisEnterprise cluster.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<DatabaseInner>, DatabaseInner> beginUpdate(
String resourceGroupName, String clusterName, String databaseName, DatabaseUpdate parameters, Context context);
/**
* Updates a database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Parameters supplied to the create or update database operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return describes a database on the RedisEnterprise cluster.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
DatabaseInner update(String resourceGroupName, String clusterName, String databaseName, DatabaseUpdate parameters);
/**
* Updates a database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Parameters supplied to the create or update database operation.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return describes a database on the RedisEnterprise cluster.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
DatabaseInner update(
String resourceGroupName, String clusterName, String databaseName, DatabaseUpdate parameters, Context context);
/**
* Gets information about a database in a RedisEnterprise cluster.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return information about a database in a RedisEnterprise cluster.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
DatabaseInner get(String resourceGroupName, String clusterName, String databaseName);
/**
* Gets information about a database in a RedisEnterprise cluster.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return information about a database in a RedisEnterprise cluster.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<DatabaseInner> getWithResponse(
String resourceGroupName, String clusterName, String databaseName, Context context);
/**
* Deletes a single database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<Void>, Void> beginDelete(String resourceGroupName, String clusterName, String databaseName);
/**
* Deletes a single database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<Void>, Void> beginDelete(
String resourceGroupName, String clusterName, String databaseName, Context context);
/**
* Deletes a single database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void delete(String resourceGroupName, String clusterName, String databaseName);
/**
* Deletes a single database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void delete(String resourceGroupName, String clusterName, String databaseName, Context context);
/**
* Retrieves the access keys for the RedisEnterprise database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the secret access keys used for authenticating connections to redis.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
AccessKeysInner listKeys(String resourceGroupName, String clusterName, String databaseName);
/**
* Retrieves the access keys for the RedisEnterprise database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the secret access keys used for authenticating connections to redis.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<AccessKeysInner> listKeysWithResponse(
String resourceGroupName, String clusterName, String databaseName, Context context);
/**
* Regenerates the RedisEnterprise database's access keys.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Specifies which key to regenerate.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the secret access keys used for authenticating connections to redis.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<AccessKeysInner>, AccessKeysInner> beginRegenerateKey(
String resourceGroupName, String clusterName, String databaseName, RegenerateKeyParameters parameters);
/**
* Regenerates the RedisEnterprise database's access keys.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Specifies which key to regenerate.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the secret access keys used for authenticating connections to redis.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<AccessKeysInner>, AccessKeysInner> beginRegenerateKey(
String resourceGroupName,
String clusterName,
String databaseName,
RegenerateKeyParameters parameters,
Context context);
/**
* Regenerates the RedisEnterprise database's access keys.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Specifies which key to regenerate.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the secret access keys used for authenticating connections to redis.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
AccessKeysInner regenerateKey(
String resourceGroupName, String clusterName, String databaseName, RegenerateKeyParameters parameters);
/**
* Regenerates the RedisEnterprise database's access keys.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Specifies which key to regenerate.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the secret access keys used for authenticating connections to redis.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
AccessKeysInner regenerateKey(
String resourceGroupName,
String clusterName,
String databaseName,
RegenerateKeyParameters parameters,
Context context);
/**
* Imports a database file to target database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Storage information for importing into the cluster.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<Void>, Void> beginImportMethod(
String resourceGroupName, String clusterName, String databaseName, ImportClusterParameters parameters);
/**
* Imports a database file to target database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Storage information for importing into the cluster.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<Void>, Void> beginImportMethod(
String resourceGroupName,
String clusterName,
String databaseName,
ImportClusterParameters parameters,
Context context);
/**
* Imports a database file to target database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Storage information for importing into the cluster.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void importMethod(
String resourceGroupName, String clusterName, String databaseName, ImportClusterParameters parameters);
/**
* Imports a database file to target database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Storage information for importing into the cluster.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void importMethod(
String resourceGroupName,
String clusterName,
String databaseName,
ImportClusterParameters parameters,
Context context);
/**
* Exports a database file from target database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Storage information for exporting into the cluster.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<Void>, Void> beginExport(
String resourceGroupName, String clusterName, String databaseName, ExportClusterParameters parameters);
/**
* Exports a database file from target database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Storage information for exporting into the cluster.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
SyncPoller<PollResult<Void>, Void> beginExport(
String resourceGroupName,
String clusterName,
String databaseName,
ExportClusterParameters parameters,
Context context);
/**
* Exports a database file from target database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Storage information for exporting into the cluster.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void export(String resourceGroupName, String clusterName, String databaseName, ExportClusterParameters parameters);
/**
* Exports a database file from target database.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param clusterName The name of the RedisEnterprise cluster.
* @param databaseName The name of the database.
* @param parameters Storage information for exporting into the cluster.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void export(
String resourceGroupName,
String clusterName,
String databaseName,
ExportClusterParameters parameters,
Context context);
}
| |
/*---------------------------------------------------------------
* Copyright 2005 by the Radiological Society of North America
*
* This source software is released under the terms of the
* RSNA Public License (http://mirc.rsna.org/rsnapubliclicense)
*----------------------------------------------------------------*/
package org.rsna.ctp.stdstages;
import org.apache.log4j.Logger;
import org.rsna.ctp.Configuration;
import org.rsna.ctp.objects.DicomObject;
import org.rsna.ctp.objects.FileObject;
import org.rsna.ctp.pipeline.AbstractPipelineStage;
import org.rsna.ctp.pipeline.StorageService;
import org.rsna.ctp.servlets.DecipherServlet;
import org.rsna.ctp.stdstages.storage.AjaxServlet;
import org.rsna.ctp.stdstages.storage.FileSystem;
import org.rsna.ctp.stdstages.storage.FileSystemManager;
import org.rsna.ctp.stdstages.storage.GuestListServlet;
import org.rsna.ctp.stdstages.storage.ImageQualifiers;
import org.rsna.ctp.stdstages.storage.StorageMonitor;
import org.rsna.ctp.stdstages.storage.StorageServlet;
import org.rsna.ctp.stdstages.storage.StoredObject;
import org.rsna.ctp.stdstages.storage.Study;
import org.rsna.server.HttpServer;
import org.rsna.server.ServletSelector;
import org.rsna.server.User;
import org.rsna.server.Users;
import org.rsna.server.UsersXmlFileImpl;
import org.rsna.servlets.LoginServlet;
import org.rsna.servlets.UserServlet;
import org.rsna.util.FileUtil;
import org.rsna.util.StringUtil;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
/**
* A class to store objects in a file system.
*/
public class FileStorageService extends AbstractPipelineStage implements StorageService {
static final Logger logger = Logger.getLogger(FileStorageService.class);
File lastFileStored = null;
long lastTime = 0;
boolean returnStoredFile = true;
FileSystemManager fsm = null;
int[] fsNameTag;
boolean autoCreateUser = false;
int port = 0;
boolean ssl = false;
String type;
int timeDepth = 0;
boolean requireAuthentication = false;
boolean setReadable = false;
boolean setWritable = false;
boolean acceptDuplicateUIDs = true;
List<ImageQualifiers> qualifiers = null;
StorageMonitor storageMonitor = null;
HttpServer httpServer = null;
File exportDirectory = null;
/**
* Construct a FileStorageService.
* @param element the XML element from the configuration file
* specifying the configuration of the stage.
*/
public FileStorageService(Element element) {
super(element);
type = element.getAttribute("type").trim().toLowerCase();
timeDepth = StringUtil.getInt(element.getAttribute("timeDepth").trim());
returnStoredFile = !element.getAttribute("returnStoredFile").trim().toLowerCase().equals("no");
String expDirString = element.getAttribute("exportDirectory").trim();
if (!expDirString.equals("")) exportDirectory = new File(expDirString);
requireAuthentication = element.getAttribute("requireAuthentication").trim().toLowerCase().equals("yes");
setReadable = element.getAttribute("setWorldReadable").trim().toLowerCase().equals("yes");
setWritable = element.getAttribute("setWorldWritable").trim().toLowerCase().equals("yes");
qualifiers = getJPEGQualifiers(element);
fsNameTag = DicomObject.getTagArray(element.getAttribute("fsNameTag").trim());
autoCreateUser = element.getAttribute("auto-create-user").trim().toLowerCase().equals("yes");
acceptDuplicateUIDs = !element.getAttribute("acceptDuplicateUIDs").trim().toLowerCase().equals("no");
port = StringUtil.getInt(element.getAttribute("port").trim());
ssl = element.getAttribute("ssl").equals("yes");
if (root == null) logger.error(name+": No root directory was specified.");
fsm = FileSystemManager
.getInstance(
root,
type,
requireAuthentication,
acceptDuplicateUIDs,
setReadable,
setWritable,
exportDirectory,
qualifiers);
}
//Get the list of qualifiers for jpeg child elements.
private List<ImageQualifiers> getJPEGQualifiers(Element el) {
LinkedList<ImageQualifiers> list = new LinkedList<ImageQualifiers>();
Node child = el.getFirstChild();
while (child != null) {
if ((child.getNodeType() == Node.ELEMENT_NODE)
&& child.getNodeName().equals("jpeg")) {
list.add(new ImageQualifiers((Element)child));
}
child = child.getNextSibling();
}
return list;
}
/**
* Start the pipeline stage. This method is called by the
* Pipeline after all the stages have been constructed.
*/
@Override
public synchronized void start() {
startServer();
startStorageMonitor();
}
/**
* Stop the pipeline stage.
*/
@Override
public void shutdown() {
if (httpServer != null) httpServer.shutdown();
stop = true;
}
/**
* Get the export directory specified in the configuration.
*/
public File getExportDirectory() {
return exportDirectory;
}
/**
* Get the server port specified in the configuration.
* @return the stage's server port, or zero if none is specified.
*/
public int getPort() {
return port;
}
/**
* Get the URL corresponding to a stored object. This method is used to find the URL of
* a stored object corresponding to a queued object.
* @param fileObject the object.
* @param filename the name by which the object is stored in the FileStorage Service.
* This name may be different from the name contained in the File of the FileObject
* because the supplied FileObject may be a copy of the object which was queued under
* another name.
* @return the URL corresponding to the stored object, or null if no object corresponding
* to the supplied object is stored.
*/
public StoredObject getStoredObject(FileObject fileObject, String filename) {
try {
//Now get the FileSystem. Note: the second argument in the getFileSystem
//call is false to prevent creating a FileSystem if the FileSystem for
//this object doesn't exist.
String fsName = getFSName(fileObject);
FileSystem fs = fsm.getFileSystem(fsName, false);
if (fs == null) return null;
//Get the Study
String studyName = Study.makeStudyName(fileObject.getStudyUID());
Study study = fs.getStudyByUID(studyName);
if (study == null) return null;
if (study.contains(filename)) {
//The object exists in the study. Get the context for the URL.
String context = "http://"
+ Configuration.getInstance().getIPAddress()
+ ":" + port
+ "/storage"
+ "/" + fs.getName();
//Construct the URL of the object.
String url = study.getStudyURL(context) + "/" + filename;
//Get the File pointing to the stored object.
File file = study.getFile(filename);
return new StoredObject(file, url);
}
else return null;
}
catch (Exception ex) { return null;}
}
/**
* Store an object if the object is of a type that the StorageService is
* configured to accept. If the StorageService is not configured to accept
* the object type, return the original object; otherwise, return either
* the passed object or the stored object depending on whether the
* returnStoredFile attribute was "no" or "yes".
* If the storage attempt fails, quarantine the input object if a quarantine
* was defined in the configuration, and return null to stop further processing.
* @param fileObject the object to process.
* @return either the original FileObject or the stored FileObject, or null
* if the object could not be stored.
*/
@Override
public FileObject store(FileObject fileObject) {
//See if the StorageService is configured to accept the object type.
if (!acceptable(fileObject)) return fileObject;
//The object is acceptable.
try {
//Get the file system for the object.
String fsName = getFSName(fileObject);
FileSystem fs = fsm.getFileSystem(fsName);
//Store the object
File storedFile = fs.store(fileObject);
if (returnStoredFile) fileObject = FileObject.getInstance(storedFile);
if (autoCreateUser) createUserForFileSystem(fs);
}
catch (Exception ex) {
if (quarantine != null) quarantine.insert(fileObject);
return null;
}
lastFileStored = fileObject.getFile();
lastTime = System.currentTimeMillis();
lastFileOut = lastFileStored;
lastTimeOut = lastTime;
return fileObject;
}
//Get the file system name for the object.
private String getFSName(FileObject fileObject) throws Exception {
String fsName = "";
if ((fileObject instanceof DicomObject) && (fsNameTag.length != 0)) {
DicomObject dob = (DicomObject)fileObject;
byte[] bytes = dob.getElementBytes(fsNameTag);
fsName = new String(bytes);
fsName = fsName.trim();
}
return fsName;
}
private void createUserForFileSystem(FileSystem fs) {
String name = fs.getName();
if (!name.startsWith("__")) {
Users users = Users.getInstance();
if ((users != null) && (users instanceof UsersXmlFileImpl)) {
User user = users.getUser(name);
if (user == null) {
user = new User(name, users.convertPassword(name));
((UsersXmlFileImpl)users).addUser(user);
}
}
}
}
/**
* Get HTML text displaying the current status of the stage.
* @return HTML text displaying the current status of the stage.
*/
@Override
public String getStatusHTML() {
StringBuffer sb = new StringBuffer();
sb.append("<h3>"+name+"</h3>");
sb.append("<table border=\"1\" width=\"100%\">");
sb.append("<tr><td width=\"20%\">Last file stored:</td>");
if (lastTime != 0) {
sb.append("<td>"+lastFileStored+"</td></tr>");
sb.append("<tr><td width=\"20%\">Last file stored at:</td>");
sb.append("<td>"+StringUtil.getDateTime(lastTime," ")+"</td></tr>");
}
else sb.append("<td>No activity</td></tr>");
sb.append("</table>");
return sb.toString();
}
//Start a web server on the root if the port is non-zero.
private void startServer() {
if (port > 0) {
//Install the home page if necessary
File index = new File(root, "index.html");
if (!index.exists()) {
File exampleIndex = new File("examples/example-storage-index.html");
FileUtil.copy(exampleIndex, index);
}
//Create the ServletSelector
ServletSelector selector = new ServletSelector(root, requireAuthentication);
selector.addServlet("login", LoginServlet.class);
selector.addServlet("user", UserServlet.class);
selector.addServlet("storage", StorageServlet.class);
selector.addServlet("guests", GuestListServlet.class);
selector.addServlet("ajax", AjaxServlet.class);
selector.addServlet("decipher", DecipherServlet.class);
//Instantiate the server
httpServer = null;
try { httpServer = new HttpServer(ssl, port, selector); }
catch (Exception ex) {
logger.error(
"Unable to instantiate the HTTP Server for "
+name
+" on port "
+port, ex);
}
//Start it if possible
if (httpServer != null) httpServer.start();
}
}
//Start a thread to delete studies older than the specified timeDepth..
private void startStorageMonitor() {
if (timeDepth > 0) {
storageMonitor = new StorageMonitor(root, timeDepth);
storageMonitor.start();
}
}
}
| |
/*
* 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.wicket.model;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Locale;
import org.apache.wicket.Application;
import org.apache.wicket.Component;
import org.apache.wicket.Localizer;
import org.apache.wicket.Session;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.util.string.Strings;
import org.apache.wicket.util.string.interpolator.PropertyVariableInterpolator;
/**
* This model class encapsulates the full power of localization support within the Wicket framework.
* It combines the flexible Wicket resource loading mechanism with property expressions, property
* models and standard Java <code>MessageFormat</code> substitutions. This combination should be
* able to solve any dynamic localization requirement that a project has.
* <p>
* The model should be created with four parameters, which are described in detail below:
* <ul>
* <li><b>resourceKey </b>- This is the most important parameter as it contains the key that should
* be used to obtain resources from any string resource loaders. This parameter is mandatory: a null
* value will throw an exception. Typically it will contain an ordinary string such as
* "label.username". To add extra power to the key functionality the key may also contain
* a property expression which will be evaluated if the model parameter (see below) is not null.
* This allows keys to be changed dynamically as the application is running. For example, the key
* could be "product.${product.id}" which prior to rendering will call
* model.getObject().getProduct().getId() and substitute this value into the resource key before is
* is passed to the loader.
* <li><b>component </b>- This parameter should be a component that the string resource is relative
* to. In a simple application this will usually be the Page on which the component resides. For
* reusable components/containers that are packaged with their own string resource bundles it should
* be the actual component/container rather than the page. For more information on this please see
* {@link org.apache.wicket.resource.loader.ComponentStringResourceLoader}. The relative component
* may actually be <code>null</code> when all resource loading is to be done from a global resource
* loader. However, we recommend that a relative component is still supplied even in these cases in
* order to 'future proof' your application with regards to changing resource loading strategies.
* <li><b>model </b>- This parameter is mandatory if either the resourceKey, the found string
* resource (see below) or any of the substitution parameters (see below) contain property
* expressions. Where property expressions are present they will all be evaluated relative to this
* model object. If there are no property expressions present then this model parameter may be
* <code>null</code>
* <li><b>parameters </b>- The parameters parameter allows an array of objects to be passed for
* substitution on the found string resource (see below) using a standard
* <code>java.text.MessageFormat</code> object. Each parameter may be an ordinary Object, in which
* case it will be processed by the standard formatting rules associated with
* <code>java.text.MessageFormat</code>. Alternatively, the parameter may be an instance of
* <code>IModel</code> in which case the <code>getObject()</code> method will be applied prior to
* the parameter being passed to the <code>java.text.MessageFormat</code>. This allows such features
* dynamic parameters that are obtained using a <code>PropertyModel</code> object or even nested
* string resource models.
* </ul>
* As well as the supplied parameters, the found string resource can contain formatting information.
* It may contain property expressions in which case these are evaluated using the model object
* supplied when the string resource model is created. The string resource may also contain
* <code>java.text.MessageFormat</code> style markup for replacement of parameters. Where a string
* resource contains both types of formatting information then the property expression will be
* applied first.
* <p>
* <b>Example 1 </b>
* <p>
* In its simplest form, the model can be used as follows:
*
* <pre>
* public MyPage extends WebPage<Void>
* {
* public MyPage(final PageParameters parameters)
* {
* add(new Label("username", new StringResourceModel("label.username", this, null)));
* }
* }
* </pre>
*
* Where the resource bundle for the page contains the entry <code>label.username=Username</code>
* <p>
* <b>Example 2 </b>
* <p>
* In this example, the resource key is selected based on the evaluation of a property expression:
*
* <pre>
* public MyPage extends WebPage<Void>
* {
* public MyPage(final PageParameters parameters)
* {
* WeatherStation ws = new WeatherStation();
* add(new Label("weatherMessage",
* new StringResourceModel("weather.${currentStatus}", this, new Model<String>(ws)));
* }
* }
* </pre>
*
* Which will call the WeatherStation.getCurrentStatus() method each time the string resource model
* is used and where the resource bundle for the page contains the entries:
*
* <pre>
* weather.sunny=Don't forget sunscreen!
* weather.raining=You might need an umbrella
* weather.snowing=Got your skis?
* weather.overcast=Best take a coat to be safe
* </pre>
*
* <p>
* <b>Example 3 </b>
* <p>
* In this example the found resource string contains a property expression that is substituted via
* the model:
*
* <pre>
* public MyPage extends WebPage<Void>
* {
* public MyPage(final PageParameters parameters)
* {
* WeatherStation ws = new WeatherStation();
* add(new Label("weatherMessage",
* new StringResourceModel("weather.message", this, new Model<String>(ws)));
* }
* }
* </pre>
*
* Where the resource bundle contains the entry <code>weather.message=Weather station reports that
* the temperature is ${currentTemperature} ${units}</code>
* <p>
* <b>Example 4 </b>
* <p>
* In this example, the use of substitution parameters is employed to format a quite complex message
* string. This is an example of the most complex and powerful use of the string resource model:
*
* <pre>
* public MyPage extends WebPage<Void>
* {
* public MyPage(final PageParameters parameters)
* {
* WeatherStation ws = new WeatherStation();
* IModel<WeatherStation> model = new Model<WeatherStation>(ws);
* add(new Label("weatherMessage",
* new StringResourceModel(
* "weather.detail", this, model,
* new Object[]
* {
* new Date(),
* new PropertyModel<?>(model, "currentStatus"),
* new PropertyModel<?>(model, "currentTemperature"),
* new PropertyModel<?>(model, "units")
* }));
* }
* }
* </pre>
*
* And where the resource bundle entry is:
*
* <pre>
* weather.detail=The report for {0,date}, shows the temperature as {2,number,###.##} {3} \
* and the weather to be {1}
* </pre>
*
* @author Chris Turner
*/
public class StringResourceModel extends LoadableDetachableModel<String>
implements
IComponentAssignedModel<String>
{
private static final long serialVersionUID = 1L;
/** The locale to use. */
private transient Locale locale;
/**
* The localizer to be used to access localized resources and the associated locale for
* formatting.
*/
private transient Localizer localizer;
/** The wrapped model. */
private final IModel<?> model;
/** Optional parameters. */
private final Object[] parameters;
/** The relative component used for lookups. */
private Component component;
/** The key of message to get. */
private final String resourceKey;
/** The default value of the message. */
private final String defaultValue;
public IWrapModel<String> wrapOnAssignment(Component component)
{
return new AssignmentWrapper(component);
}
private class AssignmentWrapper implements IWrapModel<String>
{
private static final long serialVersionUID = 1L;
private final Component component;
/**
* Construct.
*
* @param component
*/
public AssignmentWrapper(Component component)
{
this.component = component;
}
public void detach()
{
StringResourceModel.this.detach();
}
public String getObject()
{
if (StringResourceModel.this.component != null)
{
return StringResourceModel.this.getObject();
}
else
{
// TODO: Remove this as soon as we can break binary compatibility
StringResourceModel.this.component = component;
String res = StringResourceModel.this.getObject();
StringResourceModel.this.component = null;
return res;
}
}
public void setObject(String object)
{
StringResourceModel.this.setObject(object);
}
public IModel<String> getWrappedModel()
{
return StringResourceModel.this;
}
}
/**
* Construct.
*
* @param resourceKey
* The resource key for this string resource
* @param component
* The component that the resource is relative to
* @param model
* The model to use for property substitutions
* @see #StringResourceModel(String, Component, IModel, Object[])
*/
public StringResourceModel(final String resourceKey, final Component component,
final IModel<?> model)
{
this(resourceKey, component, model, null, null);
}
/**
* Construct.
*
* @param resourceKey
* The resource key for this string resource
* @param component
* The component that the resource is relative to
* @param model
* The model to use for property substitutions
* @param defaultValue
* The default value if the resource key is not found.
*
* @see #StringResourceModel(String, Component, IModel, Object[])
*/
public StringResourceModel(final String resourceKey, final Component component,
final IModel<?> model, final String defaultValue)
{
this(resourceKey, component, model, null, defaultValue);
}
/**
* Creates a new string resource model using the supplied parameters.
* <p>
* The relative component parameter should generally be supplied, as without it resources can
* not be obtained from resource bundles that are held relative to a particular component or
* page. However, for application that use only global resources then this parameter may be
* null.
* <p>
* The model parameter is also optional and only needs to be supplied if value substitutions are
* to take place on either the resource key or the actual resource strings.
* <p>
* The parameters parameter is also optional and is used for substitutions.
*
* @param resourceKey
* The resource key for this string resource
* @param component
* The component that the resource is relative to
* @param model
* The model to use for property substitutions
* @param parameters
* The parameters to substitute using a Java MessageFormat object
*/
public StringResourceModel(final String resourceKey, final Component component,
final IModel<?> model, final Object[] parameters)
{
this(resourceKey, component, model, parameters, null);
}
/**
* Creates a new string resource model using the supplied parameters.
* <p>
* The relative component parameter should generally be supplied, as without it resources can
* not be obtained from resource bundles that are held relative to a particular component or
* page. However, for application that use only global resources then this parameter may be
* null.
* <p>
* The model parameter is also optional and only needs to be supplied if value substitutions are
* to take place on either the resource key or the actual resource strings.
* <p>
* The parameters parameter is also optional and is used for substitutions.
*
* @param resourceKey
* The resource key for this string resource
* @param component
* The component that the resource is relative to
* @param model
* The model to use for property substitutions
* @param parameters
* The parameters to substitute using a Java MessageFormat object
* @param defaultValue
* The default value if the resource key is not found.
*/
public StringResourceModel(final String resourceKey, final Component component,
final IModel<?> model, final Object[] parameters, final String defaultValue)
{
if (resourceKey == null)
{
throw new IllegalArgumentException("Resource key must not be null");
}
this.resourceKey = resourceKey;
this.component = component;
this.model = model;
this.parameters = parameters;
this.defaultValue = defaultValue;
}
/**
* Construct.
*
* @param resourceKey
* The resource key for this string resource
* @param model
* The model to use for property substitutions
* @see #StringResourceModel(String, Component, IModel, Object[])
*/
public StringResourceModel(final String resourceKey, final IModel<?> model)
{
this(resourceKey, null, model, null, null);
}
/**
* Construct.
*
* @param resourceKey
* The resource key for this string resource
* @param model
* The model to use for property substitutions
* @param defaultValue
* The default value if the resource key is not found.
*
* @see #StringResourceModel(String, Component, IModel, Object[])
*/
public StringResourceModel(final String resourceKey, final IModel<?> model,
final String defaultValue)
{
this(resourceKey, null, model, null, defaultValue);
}
/**
* Creates a new string resource model using the supplied parameters.
* <p>
* The model parameter is also optional and only needs to be supplied if value substitutions are
* to take place on either the resource key or the actual resource strings.
* <p>
* The parameters parameter is also optional and is used for substitutions.
*
* @param resourceKey
* The resource key for this string resource
* @param model
* The model to use for property substitutions
* @param parameters
* The parameters to substitute using a Java MessageFormat object
*/
public StringResourceModel(final String resourceKey, final IModel<?> model,
final Object[] parameters)
{
this(resourceKey, null, model, parameters, null);
}
/**
* Creates a new string resource model using the supplied parameters.
* <p>
* The model parameter is also optional and only needs to be supplied if value substitutions are
* to take place on either the resource key or the actual resource strings.
* <p>
* The parameters parameter is also optional and is used for substitutions.
*
* @param resourceKey
* The resource key for this string resource
* @param model
* The model to use for property substitutions
* @param parameters
* The parameters to substitute using a Java MessageFormat object
* @param defaultValue
* The default value if the resource key is not found.
*/
public StringResourceModel(final String resourceKey, final IModel<?> model,
final Object[] parameters, final String defaultValue)
{
this(resourceKey, null, model, parameters, defaultValue);
}
/**
* Gets the localizer that is being used by this string resource model.
*
* @return The localizer
*/
public Localizer getLocalizer()
{
return localizer;
}
/**
* Gets the string currently represented by this string resource model. The string that is
* returned may vary for each call to this method depending on the values contained in the model
* and an the parameters that were passed when this string resource model was created.
*
* @return The string
*/
public final String getString()
{
// Make sure we have a localizer before commencing
if (getLocalizer() == null)
{
if (component != null)
{
setLocalizer(component.getLocalizer());
}
else
{
throw new IllegalStateException("No localizer has been set");
}
}
// Make sure we have the locale
if (locale == null)
{
locale = Session.get().getLocale();
}
String value = null;
// Substitute any parameters if necessary
Object[] parameters = getParameters();
if (parameters == null)
{
// Get the string resource, doing any property substitutions as part
// of the get operation
value = localizer.getString(getResourceKey(), component, model, defaultValue);
if (value == null)
{
value = defaultValue;
}
}
else
{
// Get the string resource, doing not any property substitutions
// that has to be done later after MessageFormat
value = localizer.getString(getResourceKey(), component, null, defaultValue);
if (value == null)
{
value = defaultValue;
}
if (value != null)
{
// Build the real parameters
Object[] realParams = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++)
{
if (parameters[i] instanceof IModel)
{
realParams[i] = ((IModel<?>)parameters[i]).getObject();
}
else if (model != null && parameters[i] instanceof String)
{
realParams[i] = PropertyVariableInterpolator.interpolate(
(String)parameters[i], model.getObject());
}
else
{
realParams[i] = parameters[i];
}
}
if (model != null)
{
// First escape all substitute properties so that message format doesn't try to
// parse that.
value = Strings.replaceAll(value, "${", "$'{'").toString();
}
// Apply the parameters
final MessageFormat format = new MessageFormat(value, component != null
? component.getLocale() : locale);
value = format.format(realParams);
if (model != null)
{
// un escape the substitute properties
value = Strings.replaceAll(value, "$'{'", "${").toString();
// now substitute the properties
value = localizer.substitutePropertyExpressions(component, value, model);
}
}
}
// Return the string resource
return value;
}
/**
* Sets the localizer that is being used by this string resource model. This method is provided
* to allow the default application localizer to be overridden if required.
*
* @param localizer
* The localizer to use
*/
public void setLocalizer(final Localizer localizer)
{
this.localizer = localizer;
}
/**
* This method just returns debug information, so it won't return the localized string. Please
* use getString() for that.
*
* @return The string for this model object
*/
@Override
public String toString()
{
StringBuffer sb = new StringBuffer("StringResourceModel[");
sb.append("key:");
sb.append(resourceKey);
sb.append(",default:");
sb.append(defaultValue);
sb.append(",params:");
if (parameters != null)
{
sb.append(Arrays.asList(parameters));
}
sb.append("]");
return sb.toString();
}
/**
* Gets the Java MessageFormat substitution parameters.
*
* @return The substitution parameters
*/
protected Object[] getParameters()
{
return parameters;
}
/**
* Gets the resource key for this string resource. If the resource key contains property
* expressions and the model is not null then the returned value is the actual resource key with
* all substitutions undertaken.
*
* @return The (possibly substituted) resource key
*/
protected final String getResourceKey()
{
if (model != null)
{
return PropertyVariableInterpolator.interpolate(resourceKey, model.getObject());
}
else
{
return resourceKey;
}
}
/**
* Gets the string that this string resource model currently represents. The string is returned
* as an object to allow it to be used generically within components.
*
*/
@Override
protected String load()
{
// Initialize information that we need to work successfully
final Session session = Session.get();
if (session != null)
{
localizer = Application.get().getResourceSettings().getLocalizer();
locale = session.getLocale();
}
else
{
throw new WicketRuntimeException(
"Cannot attach a string resource model without a Session context because that is required to get a Localizer");
}
return getString();
}
/**
* Detaches from the given session
*/
@Override
protected final void onDetach()
{
// Detach any model
if (model != null)
{
model.detach();
}
// Null out references
localizer = null;
locale = null;
}
}
| |
/*
* Copyright 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.uberfire.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.uberfire.java.nio.IOException;
import org.uberfire.java.nio.channels.SeekableByteChannel;
import org.uberfire.java.nio.file.AtomicMoveNotSupportedException;
import org.uberfire.java.nio.file.CopyOption;
import org.uberfire.java.nio.file.DeleteOption;
import org.uberfire.java.nio.file.DirectoryNotEmptyException;
import org.uberfire.java.nio.file.DirectoryStream;
import org.uberfire.java.nio.file.FileAlreadyExistsException;
import org.uberfire.java.nio.file.FileSystem;
import org.uberfire.java.nio.file.FileSystemAlreadyExistsException;
import org.uberfire.java.nio.file.FileSystemNotFoundException;
import org.uberfire.java.nio.file.NoSuchFileException;
import org.uberfire.java.nio.file.NotDirectoryException;
import org.uberfire.java.nio.file.OpenOption;
import org.uberfire.java.nio.file.Option;
import org.uberfire.java.nio.file.Path;
import org.uberfire.java.nio.file.ProviderNotFoundException;
import org.uberfire.java.nio.file.attribute.FileAttribute;
import org.uberfire.java.nio.file.attribute.FileAttributeView;
import org.uberfire.java.nio.file.attribute.FileTime;
/**
*
*/
public interface IOService {
public static Set<OpenOption> EMPTY_OPTIONS = new HashSet<OpenOption>();
void dispose();
void startBatch( final FileSystem fs );
void startBatch( final FileSystem[] fs,
final Option... options );
void startBatch( final FileSystem fs,
final Option... options );
void startBatch( final FileSystem... fs );
void endBatch();
FileAttribute<?>[] convert( final Map<String, ?> attrs );
Path get( final String first,
final String... more )
throws IllegalArgumentException;
Path get( final URI uri )
throws IllegalArgumentException, FileSystemNotFoundException, SecurityException;
Iterable<FileSystem> getFileSystems();
FileSystem getFileSystem( final URI uri )
throws IllegalArgumentException, FileSystemNotFoundException,
ProviderNotFoundException, SecurityException;
FileSystem newFileSystem( final URI uri,
final Map<String, ?> env )
throws IllegalArgumentException, FileSystemAlreadyExistsException,
ProviderNotFoundException, IOException, SecurityException;
void onNewFileSystem( final NewFileSystemListener listener );
InputStream newInputStream( final Path path,
final OpenOption... options )
throws IllegalArgumentException, NoSuchFileException,
UnsupportedOperationException, IOException, SecurityException;
OutputStream newOutputStream( final Path path,
final OpenOption... options )
throws IllegalArgumentException, UnsupportedOperationException,
IOException, SecurityException;
SeekableByteChannel newByteChannel( final Path path,
final OpenOption... options )
throws IllegalArgumentException, UnsupportedOperationException, FileAlreadyExistsException,
IOException, SecurityException;
SeekableByteChannel newByteChannel( final Path path,
final Set<? extends OpenOption> options,
final FileAttribute<?>... attrs )
throws IllegalArgumentException, UnsupportedOperationException, FileAlreadyExistsException,
IOException, SecurityException;
DirectoryStream<Path> newDirectoryStream( final Path dir )
throws IllegalArgumentException, NotDirectoryException, IOException, SecurityException;
DirectoryStream<Path> newDirectoryStream( final Path dir,
final DirectoryStream.Filter<Path> filter )
throws IllegalArgumentException, NotDirectoryException, IOException, SecurityException;
Path createFile( final Path path,
final FileAttribute<?>... attrs )
throws IllegalArgumentException, UnsupportedOperationException,
FileAlreadyExistsException, IOException, SecurityException;
Path createDirectory( final Path dir,
final FileAttribute<?>... attrs )
throws IllegalArgumentException, UnsupportedOperationException,
FileAlreadyExistsException, IOException, SecurityException;
Path createDirectories( final Path dir,
final FileAttribute<?>... attrs )
throws UnsupportedOperationException, FileAlreadyExistsException,
IOException, SecurityException;
Path createDirectory( final Path dir,
final Map<String, ?> attrs )
throws IllegalArgumentException, UnsupportedOperationException,
FileAlreadyExistsException, IOException, SecurityException;
Path createDirectories( final Path dir,
final Map<String, ?> attrs )
throws UnsupportedOperationException, FileAlreadyExistsException,
IOException, SecurityException;
void delete( final Path path,
final DeleteOption... options )
throws IllegalArgumentException, NoSuchFileException,
DirectoryNotEmptyException, IOException, SecurityException;
boolean deleteIfExists( final Path path,
final DeleteOption... options )
throws IllegalArgumentException, DirectoryNotEmptyException,
IOException, SecurityException;
Path createTempFile( final String prefix,
final String suffix,
final FileAttribute<?>... attrs )
throws IllegalArgumentException, UnsupportedOperationException,
IOException, SecurityException;
Path createTempFile( final Path dir,
final String prefix,
final String suffix,
final FileAttribute<?>... attrs )
throws IllegalArgumentException, UnsupportedOperationException,
IOException, SecurityException;
Path createTempDirectory( final String prefix,
final FileAttribute<?>... attrs )
throws IllegalArgumentException, UnsupportedOperationException,
IOException, SecurityException;
Path createTempDirectory( final Path dir,
final String prefix,
final FileAttribute<?>... attrs )
throws IllegalArgumentException, UnsupportedOperationException,
IOException, SecurityException;
Path copy( final Path source,
final Path target,
final CopyOption... options )
throws UnsupportedOperationException, FileAlreadyExistsException,
DirectoryNotEmptyException, IOException, SecurityException;
Path move( final Path source,
final Path target,
final CopyOption... options )
throws UnsupportedOperationException, FileAlreadyExistsException,
DirectoryNotEmptyException, AtomicMoveNotSupportedException,
IOException, SecurityException;
<V extends FileAttributeView> V getFileAttributeView( final Path path,
final Class<V> type )
throws IllegalArgumentException;
Map<String, Object> readAttributes( final Path path )
throws UnsupportedOperationException, NoSuchFileException,
IllegalArgumentException, IOException, SecurityException;
Map<String, Object> readAttributes( final Path path,
final String attributes )
throws UnsupportedOperationException, NoSuchFileException,
IllegalArgumentException, IOException, SecurityException;
Path setAttributes( final Path path,
final FileAttribute<?>... attrs )
throws UnsupportedOperationException, IllegalArgumentException,
ClassCastException, IOException, SecurityException;
Path setAttributes( final Path path,
final Map<String, Object> attrs )
throws UnsupportedOperationException, IllegalArgumentException,
ClassCastException, IOException, SecurityException;
Path setAttribute( final Path path,
final String attribute,
final Object value )
throws UnsupportedOperationException, IllegalArgumentException,
ClassCastException, IOException, SecurityException;
Object getAttribute( final Path path,
final String attribute )
throws UnsupportedOperationException, IllegalArgumentException,
IOException, SecurityException;
FileTime getLastModifiedTime( final Path path )
throws IllegalArgumentException, IOException, SecurityException;
long size( final Path path )
throws IllegalArgumentException, IOException, SecurityException;
boolean exists( final Path path )
throws IllegalArgumentException, SecurityException;
boolean notExists( final Path path )
throws IllegalArgumentException, SecurityException;
boolean isSameFile( final Path path,
final Path path2 )
throws IllegalArgumentException, IOException, SecurityException;
BufferedReader newBufferedReader( final Path path,
final Charset cs )
throws IllegalArgumentException, NoSuchFileException, IOException, SecurityException;
BufferedWriter newBufferedWriter( final Path path,
final Charset cs,
final OpenOption... options )
throws IllegalArgumentException, IOException, UnsupportedOperationException, SecurityException;
long copy( final InputStream in,
final Path target,
final CopyOption... options )
throws IOException, FileAlreadyExistsException, DirectoryNotEmptyException,
UnsupportedOperationException, SecurityException;
long copy( final Path source,
final OutputStream out )
throws IOException, SecurityException;
byte[] readAllBytes( final Path path )
throws IOException, OutOfMemoryError, SecurityException;
List<String> readAllLines( final Path path )
throws IllegalArgumentException, NoSuchFileException, IOException, SecurityException;
List<String> readAllLines( final Path path,
final Charset cs )
throws IllegalArgumentException, NoSuchFileException, IOException, SecurityException;
String readAllString( final Path path,
final Charset cs )
throws IllegalArgumentException, NoSuchFileException, IOException;
String readAllString( final Path path )
throws IllegalArgumentException, NoSuchFileException, IOException;
Path write( final Path path,
final byte[] bytes,
final OpenOption... options )
throws IOException, UnsupportedOperationException, SecurityException;
Path write( final Path path,
final byte[] bytes,
final Map<String, ?> attrs,
final OpenOption... options )
throws IOException, UnsupportedOperationException, SecurityException;
Path write( final Path path,
final byte[] bytes,
final Set<? extends OpenOption> options,
final FileAttribute<?>... attrs )
throws IllegalArgumentException, IOException, UnsupportedOperationException;
Path write( final Path path,
final Iterable<? extends CharSequence> lines,
final Charset cs,
final OpenOption... options )
throws IllegalArgumentException, IOException, UnsupportedOperationException, SecurityException;
Path write( final Path path,
final String content,
final OpenOption... options )
throws IllegalArgumentException, IOException, UnsupportedOperationException;
Path write( final Path path,
final String content,
final Charset cs,
final OpenOption... options )
throws IllegalArgumentException, IOException, UnsupportedOperationException;
Path write( final Path path,
final String content,
final Set<? extends OpenOption> options,
final FileAttribute<?>... attrs )
throws IllegalArgumentException, IOException, UnsupportedOperationException;
Path write( final Path path,
final String content,
final Charset cs,
final Set<? extends OpenOption> options,
final FileAttribute<?>... attrs )
throws IllegalArgumentException, IOException, UnsupportedOperationException;
Path write( final Path path,
final String content,
final Map<String, ?> attrs,
final OpenOption... options )
throws IllegalArgumentException, IOException, UnsupportedOperationException;
Path write( final Path path,
final String content,
final Charset cs,
final Map<String, ?> attrs,
final OpenOption... options )
throws IllegalArgumentException, IOException, UnsupportedOperationException;
public abstract static class NewFileSystemListener {
public abstract void execute( final FileSystem newFileSystem,
final String scheme,
final String name,
final Map<String, ?> env );
}
}
| |
package liquibase.change.core;
import liquibase.change.*;
import liquibase.database.Database;
import liquibase.database.core.SQLiteDatabase;
import liquibase.database.core.SQLiteDatabase.AlterTableVisitor;
import liquibase.snapshot.SnapshotGeneratorFactory;
import liquibase.statement.SqlStatement;
import liquibase.statement.core.RenameColumnStatement;
import liquibase.structure.core.Column;
import liquibase.structure.core.Index;
import liquibase.structure.core.Table;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Renames an existing column.
*/
@DatabaseChange(
name="renameColumn",
description = "Renames an existing column",
priority = ChangeMetaData.PRIORITY_DEFAULT,
appliesTo = "column"
)
public class RenameColumnChange extends AbstractChange {
private String catalogName;
private String schemaName;
private String tableName;
private String oldColumnName;
private String newColumnName;
private String columnDataType;
private String remarks;
@DatabaseChangeProperty(since = "3.0", mustEqualExisting ="column.relation.catalog")
public String getCatalogName() {
return catalogName;
}
public void setCatalogName(String catalogName) {
this.catalogName = catalogName;
}
@DatabaseChangeProperty(mustEqualExisting ="column.relation.schema")
public String getSchemaName() {
return schemaName;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
@DatabaseChangeProperty(
description = "Name of the table containing that the column to rename",
mustEqualExisting = "column.relation"
)
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
@DatabaseChangeProperty(
description = "Name of the existing column to rename",
exampleValue = "name",
mustEqualExisting = "column"
)
public String getOldColumnName() {
return oldColumnName;
}
public void setOldColumnName(String oldColumnName) {
this.oldColumnName = oldColumnName;
}
@DatabaseChangeProperty(description = "Name to rename the column to", exampleValue = "full_name")
public String getNewColumnName() {
return newColumnName;
}
public void setNewColumnName(String newColumnName) {
this.newColumnName = newColumnName;
}
@DatabaseChangeProperty(description = "Data type of the column")
public String getColumnDataType() {
return columnDataType;
}
public void setColumnDataType(String columnDataType) {
this.columnDataType = columnDataType;
}
@DatabaseChangeProperty(description = "Remarks of the column")
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
@Override
public SqlStatement[] generateStatements(Database database) {
return new SqlStatement[] { new RenameColumnStatement(
getCatalogName(),
getSchemaName(),
getTableName(), getOldColumnName(), getNewColumnName(),
getColumnDataType(),getRemarks())
};
}
@Override
public ChangeStatus checkStatus(Database database) {
try {
ChangeStatus changeStatus = new ChangeStatus();
Column newColumn = SnapshotGeneratorFactory.getInstance().createSnapshot(
new Column(Table.class, getCatalogName(), getSchemaName(), getTableName(), getNewColumnName()),
database
);
Column oldColumn = SnapshotGeneratorFactory.getInstance().createSnapshot(
new Column(Table.class, getCatalogName(), getSchemaName(), getTableName(), getOldColumnName()),
database
);
if ((newColumn == null) && (oldColumn == null)) {
return changeStatus.unknown("Neither column exists");
}
if ((newColumn != null) && (oldColumn != null)) {
return changeStatus.unknown("Both columns exist");
}
changeStatus.assertComplete(newColumn != null, "New column does not exist");
return changeStatus;
} catch (Exception e) {
return new ChangeStatus().unknown(e);
}
}
private SqlStatement[] generateStatementsForSQLiteDatabase(Database database) {
// SQLite does not support this ALTER TABLE operation until now.
// For more information see: http://www.sqlite.org/omitted.html.
// This is a small work around...
// define alter table logic
AlterTableVisitor renameAlterVisitor =
new AlterTableVisitor() {
@Override
public ColumnConfig[] getColumnsToAdd() {
return new ColumnConfig[0];
}
@Override
public boolean copyThisColumn(ColumnConfig column) {
return true;
}
@Override
public boolean createThisColumn(ColumnConfig column) {
if (column.getName().equals(getOldColumnName())) {
column.setName(getNewColumnName());
}
return true;
}
@Override
public boolean createThisIndex(Index index) {
if (index.getColumnNames().contains(getOldColumnName())) {
Iterator<Column> columnIterator = index.getColumns().iterator();
while (columnIterator.hasNext()) {
Column column = columnIterator.next();
if (column.getName().equals(getOldColumnName())) {
columnIterator.remove();
break;
}
}
index.addColumn(new Column(getNewColumnName()).setRelation(index.getTable()));
}
return true;
}
};
List<SqlStatement> statements = new ArrayList<>();
try {
// alter table
statements.addAll(SQLiteDatabase.getAlterTableStatements(
renameAlterVisitor,
database,getCatalogName(), getSchemaName(),getTableName()));
} catch (Exception e) {
System.err.println(e);
e.printStackTrace();
}
return statements.toArray(new SqlStatement[statements.size()]);
}
@Override
protected Change[] createInverses() {
RenameColumnChange inverse = new RenameColumnChange();
inverse.setSchemaName(getSchemaName());
inverse.setTableName(getTableName());
inverse.setOldColumnName(getNewColumnName());
inverse.setNewColumnName(getOldColumnName());
inverse.setColumnDataType(getColumnDataType());
return new Change[]{
inverse
};
}
@Override
public String getConfirmationMessage() {
return "Column "+tableName+"."+ oldColumnName + " renamed to " + newColumnName;
}
@Override
public String getSerializedObjectNamespace() {
return STANDARD_CHANGELOG_NAMESPACE;
}
}
| |
/*
* $Header: /home/cvs/jakarta-tomcat-jasper/jasper2/src/share/org/apache/jasper/compiler/Validator.java,v 1.114 2003/09/02 21:39:58 remm Exp $
* $Revision: 1.114 $
* $Date: 2003/09/02 21:39:58 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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 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.jasper.compiler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import javax.servlet.jsp.el.FunctionMapper;
import javax.servlet.jsp.tagext.FunctionInfo;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.PageData;
import javax.servlet.jsp.tagext.TagAttributeInfo;
import javax.servlet.jsp.tagext.TagData;
import javax.servlet.jsp.tagext.TagExtraInfo;
import javax.servlet.jsp.tagext.TagInfo;
import javax.servlet.jsp.tagext.TagLibraryInfo;
import javax.servlet.jsp.tagext.ValidationMessage;
import org.apache.jasper.Constants;
import org.apache.jasper.JasperException;
import org.apache.jasper.JspCompilationContext;
import org.xml.sax.Attributes;
/**
* Performs validation on the page elements. Attributes are checked for
* mandatory presence, entry value validity, and consistency. As a
* side effect, some page global value (such as those from page direcitves)
* are stored, for later use.
*
* @author Kin-man Chung
* @author Jan Luehe
* @author Shawn Bayern
* @author Mark Roth
*/
class Validator {
/**
* A visitor to validate and extract page directive info
*/
static class DirectiveVisitor extends Node.Visitor {
private PageInfo pageInfo;
private ErrorDispatcher err;
private static final JspUtil.ValidAttribute[] pageDirectiveAttrs = {
new JspUtil.ValidAttribute("language"),
new JspUtil.ValidAttribute("extends"),
new JspUtil.ValidAttribute("import"),
new JspUtil.ValidAttribute("session"),
new JspUtil.ValidAttribute("buffer"),
new JspUtil.ValidAttribute("autoFlush"),
new JspUtil.ValidAttribute("isThreadSafe"),
new JspUtil.ValidAttribute("info"),
new JspUtil.ValidAttribute("errorPage"),
new JspUtil.ValidAttribute("isErrorPage"),
new JspUtil.ValidAttribute("contentType"),
new JspUtil.ValidAttribute("pageEncoding"),
new JspUtil.ValidAttribute("isELIgnored")
};
private boolean pageEncodingSeen = false;
/*
* Constructor
*/
DirectiveVisitor(Compiler compiler) throws JasperException {
this.pageInfo = compiler.getPageInfo();
this.err = compiler.getErrorDispatcher();
JspCompilationContext ctxt = compiler.getCompilationContext();
}
public void visit(Node.IncludeDirective n) throws JasperException {
// Since pageDirectiveSeen flag only applies to the Current page
// save it here and restore it after the file is included.
boolean pageEncodingSeenSave = pageEncodingSeen;
pageEncodingSeen = false;
visitBody(n);
pageEncodingSeen = pageEncodingSeenSave;
}
public void visit(Node.PageDirective n) throws JasperException {
JspUtil.checkAttributes("Page directive", n,
pageDirectiveAttrs, err);
// JSP.2.10.1
Attributes attrs = n.getAttributes();
for (int i = 0; attrs != null && i < attrs.getLength(); i++) {
String attr = attrs.getQName(i);
String value = attrs.getValue(i);
if ("language".equals(attr)) {
if (pageInfo.getLanguage(false) == null) {
pageInfo.setLanguage(value, n, err, true);
} else if (!pageInfo.getLanguage(false).equals(value)) {
err.jspError(n, "jsp.error.page.conflict.language",
pageInfo.getLanguage(false), value);
}
} else if ("extends".equals(attr)) {
if (pageInfo.getExtends(false) == null) {
pageInfo.setExtends(value, n);
} else if (!pageInfo.getExtends(false).equals(value)) {
err.jspError(n, "jsp.error.page.conflict.extends",
pageInfo.getExtends(false), value);
}
} else if ("contentType".equals(attr)) {
if (pageInfo.getContentType() == null) {
pageInfo.setContentType(value);
} else if (!pageInfo.getContentType().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.contenttype",
pageInfo.getContentType(), value);
}
} else if ("session".equals(attr)) {
if (pageInfo.getSession() == null) {
pageInfo.setSession(value, n, err);
} else if (!pageInfo.getSession().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.session",
pageInfo.getSession(), value);
}
} else if ("buffer".equals(attr)) {
if (pageInfo.getBufferValue() == null) {
pageInfo.setBufferValue(value, n, err);
} else if (!pageInfo.getBufferValue().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.buffer",
pageInfo.getBufferValue(), value);
}
} else if ("autoFlush".equals(attr)) {
if (pageInfo.getAutoFlush() == null) {
pageInfo.setAutoFlush(value, n, err);
} else if (!pageInfo.getAutoFlush().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.autoflush",
pageInfo.getAutoFlush(), value);
}
} else if ("isThreadSafe".equals(attr)) {
if (pageInfo.getIsThreadSafe() == null) {
pageInfo.setIsThreadSafe(value, n, err);
} else if (!pageInfo.getIsThreadSafe().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.isthreadsafe",
pageInfo.getIsThreadSafe(), value);
}
} else if ("isELIgnored".equals(attr)) {
if (pageInfo.getIsELIgnored() == null) {
pageInfo.setIsELIgnored(value, n, err, true);
} else if (!pageInfo.getIsELIgnored().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.iselignored",
pageInfo.getIsELIgnored(), value);
}
} else if ("isErrorPage".equals(attr)) {
if (pageInfo.getIsErrorPage() == null) {
pageInfo.setIsErrorPage(value, n, err);
} else if (!pageInfo.getIsErrorPage().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.iserrorpage",
pageInfo.getIsErrorPage(), value);
}
} else if ("errorPage".equals(attr)) {
if (pageInfo.getErrorPage() == null) {
pageInfo.setErrorPage(value);
} else if (!pageInfo.getErrorPage().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.errorpage",
pageInfo.getErrorPage(), value);
}
} else if ("info".equals(attr)) {
if (pageInfo.getInfo() == null) {
pageInfo.setInfo(value);
} else if (!pageInfo.getInfo().equals(value)) {
err.jspError(n, "jsp.error.page.conflict.info",
pageInfo.getInfo(), value);
}
} else if ("pageEncoding".equals(attr)) {
if (pageEncodingSeen)
err.jspError(n, "jsp.error.page.multi.pageencoding");
// 'pageEncoding' can occur at most once per file
pageEncodingSeen = true;
/*
* Report any encoding conflict, treating "UTF-16",
* "UTF-16BE", and "UTF-16LE" as identical.
*/
comparePageEncodings(value, n);
}
}
// Check for bad combinations
if (pageInfo.getBuffer() == 0 && !pageInfo.isAutoFlush())
err.jspError(n, "jsp.error.page.badCombo");
// Attributes for imports for this node have been processed by
// the parsers, just add them to pageInfo.
pageInfo.addImports(n.getImports());
}
public void visit(Node.TagDirective n) throws JasperException {
// Note: Most of the validation is done in TagFileProcessor
// when it created a TagInfo object from the
// tag file in which the directive appeared.
// This method does additional processing to collect page info
Attributes attrs = n.getAttributes();
for (int i = 0; attrs != null && i < attrs.getLength(); i++) {
String attr = attrs.getQName(i);
String value = attrs.getValue(i);
if ("language".equals(attr)) {
if (pageInfo.getLanguage(false) == null) {
pageInfo.setLanguage(value, n, err, false);
} else if (!pageInfo.getLanguage(false).equals(value)) {
err.jspError(n, "jsp.error.tag.conflict.language",
pageInfo.getLanguage(false), value);
}
} else if ("isELIgnored".equals(attr)) {
if (pageInfo.getIsELIgnored() == null) {
pageInfo.setIsELIgnored(value, n, err, false);
} else if (!pageInfo.getIsELIgnored().equals(value)) {
err.jspError(n, "jsp.error.tag.conflict.iselignored",
pageInfo.getIsELIgnored(), value);
}
} else if ("pageEncoding".equals(attr)) {
if (pageEncodingSeen)
err.jspError(n, "jsp.error.tag.multi.pageencoding");
pageEncodingSeen = true;
n.getRoot().setPageEncoding(value);
}
}
// Attributes for imports for this node have been processed by
// the parsers, just add them to pageInfo.
pageInfo.addImports(n.getImports());
}
public void visit(Node.AttributeDirective n) throws JasperException {
// Do nothing, since this attribute directive has already been
// validated by TagFileProcessor when it created a TagInfo object
// from the tag file in which the directive appeared
}
public void visit(Node.VariableDirective n) throws JasperException {
// Do nothing, since this variable directive has already been
// validated by TagFileProcessor when it created a TagInfo object
// from the tag file in which the directive appeared
}
/*
* Compares the page encoding specified in the 'pageEncoding'
* attribute of the page directive with the encoding explicitly
* specified in the XML prolog (only for XML syntax) and the encoding
* specified in the JSP config element whose URL pattern matches the
* page, and throws an error in case of a mismatch.
*/
private void comparePageEncodings(String pageDirEnc,
Node.PageDirective n)
throws JasperException {
String configEnc = n.getRoot().getJspConfigPageEncoding();
if (configEnc != null && !pageDirEnc.equals(configEnc)
&& (!pageDirEnc.startsWith("UTF-16")
|| !configEnc.startsWith("UTF-16"))) {
err.jspError(n, "jsp.error.config_pagedir_encoding_mismatch",
configEnc, pageDirEnc);
}
if (n.getRoot().isXmlSyntax()
&& n.getRoot().isEncodingSpecifiedInProlog()) {
String pageEnc = n.getRoot().getPageEncoding();
if (!pageDirEnc.equals(pageEnc)
&& (!pageDirEnc.startsWith("UTF-16")
|| !pageEnc.startsWith("UTF-16"))) {
err.jspError(n, "jsp.error.prolog_pagedir_encoding_mismatch",
pageEnc, pageDirEnc);
}
}
}
}
/**
* A visitor for validating nodes other than page directives
*/
static class ValidateVisitor extends Node.Visitor {
private PageInfo pageInfo;
private ErrorDispatcher err;
private TagInfo tagInfo;
private ClassLoader loader;
private static final JspUtil.ValidAttribute[] jspRootAttrs = {
new JspUtil.ValidAttribute("version", true) };
private static final JspUtil.ValidAttribute[] includeDirectiveAttrs = {
new JspUtil.ValidAttribute("file", true) };
private static final JspUtil.ValidAttribute[] taglibDirectiveAttrs = {
new JspUtil.ValidAttribute("uri"),
new JspUtil.ValidAttribute("tagdir"),
new JspUtil.ValidAttribute("prefix", true) };
private static final JspUtil.ValidAttribute[] includeActionAttrs = {
new JspUtil.ValidAttribute("page", true, true),
new JspUtil.ValidAttribute("flush") };
private static final JspUtil.ValidAttribute[] paramActionAttrs = {
new JspUtil.ValidAttribute("name", true),
new JspUtil.ValidAttribute("value", true, true) };
private static final JspUtil.ValidAttribute[] forwardActionAttrs = {
new JspUtil.ValidAttribute("page", true, true) };
private static final JspUtil.ValidAttribute[] getPropertyAttrs = {
new JspUtil.ValidAttribute("name", true),
new JspUtil.ValidAttribute("property", true) };
private static final JspUtil.ValidAttribute[] setPropertyAttrs = {
new JspUtil.ValidAttribute("name", true),
new JspUtil.ValidAttribute("property", true),
new JspUtil.ValidAttribute("value", false, true),
new JspUtil.ValidAttribute("param") };
private static final JspUtil.ValidAttribute[] useBeanAttrs = {
new JspUtil.ValidAttribute("id", true),
new JspUtil.ValidAttribute("scope"),
new JspUtil.ValidAttribute("class"),
new JspUtil.ValidAttribute("type"),
new JspUtil.ValidAttribute("beanName", false, true) };
private static final JspUtil.ValidAttribute[] plugInAttrs = {
new JspUtil.ValidAttribute("type",true),
new JspUtil.ValidAttribute("code", true),
new JspUtil.ValidAttribute("codebase"),
new JspUtil.ValidAttribute("align"),
new JspUtil.ValidAttribute("archive"),
new JspUtil.ValidAttribute("height", false, true),
new JspUtil.ValidAttribute("hspace"),
new JspUtil.ValidAttribute("jreversion"),
new JspUtil.ValidAttribute("name"),
new JspUtil.ValidAttribute("vspace"),
new JspUtil.ValidAttribute("width", false, true),
new JspUtil.ValidAttribute("nspluginurl"),
new JspUtil.ValidAttribute("iepluginurl") };
private static final JspUtil.ValidAttribute[] attributeAttrs = {
new JspUtil.ValidAttribute("name", true),
new JspUtil.ValidAttribute("trim") };
private static final JspUtil.ValidAttribute[] invokeAttrs = {
new JspUtil.ValidAttribute("fragment", true),
new JspUtil.ValidAttribute("var"),
new JspUtil.ValidAttribute("varReader"),
new JspUtil.ValidAttribute("scope") };
private static final JspUtil.ValidAttribute[] doBodyAttrs = {
new JspUtil.ValidAttribute("var"),
new JspUtil.ValidAttribute("varReader"),
new JspUtil.ValidAttribute("scope") };
private static final JspUtil.ValidAttribute[] jspOutputAttrs = {
new JspUtil.ValidAttribute("omit-xml-declaration"),
new JspUtil.ValidAttribute("doctype-root-element"),
new JspUtil.ValidAttribute("doctype-public"),
new JspUtil.ValidAttribute("doctype-system") };
/*
* Constructor
*/
ValidateVisitor(Compiler compiler) {
this.pageInfo = compiler.getPageInfo();
this.err = compiler.getErrorDispatcher();
this.tagInfo = compiler.getCompilationContext().getTagInfo();
this.loader = compiler.getCompilationContext().getClassLoader();
}
public void visit(Node.JspRoot n) throws JasperException {
JspUtil.checkAttributes("Jsp:root", n,
jspRootAttrs, err);
String version = n.getTextAttribute("version");
if (!version.equals("1.2") && !version.equals("2.0")) {
err.jspError(n, "jsp.error.jsproot.version.invalid", version);
}
visitBody(n);
}
public void visit(Node.IncludeDirective n) throws JasperException {
JspUtil.checkAttributes("Include directive", n,
includeDirectiveAttrs, err);
visitBody(n);
}
public void visit(Node.TaglibDirective n) throws JasperException {
JspUtil.checkAttributes("Taglib directive", n,
taglibDirectiveAttrs, err);
// Either 'uri' or 'tagdir' attribute must be specified
String uri = n.getAttributeValue("uri");
String tagdir = n.getAttributeValue("tagdir");
if (uri == null && tagdir == null) {
err.jspError(n, "jsp.error.taglibDirective.missing.location");
}
if (uri != null && tagdir != null) {
err.jspError(n, "jsp.error.taglibDirective.both_uri_and_tagdir");
}
}
public void visit(Node.ParamAction n) throws JasperException {
JspUtil.checkAttributes("Param action", n,
paramActionAttrs, err);
// make sure the value of the 'name' attribute is not a
// request-time expression
throwErrorIfExpression(n, "name", "jsp:param");
n.setValue(getJspAttribute("value", null, null,
n.getAttributeValue("value"),
java.lang.String.class,
n, false));
visitBody(n);
}
public void visit(Node.ParamsAction n) throws JasperException {
// Make sure we've got at least one nested jsp:param
Node.Nodes subElems = n.getBody();
if (subElems == null) {
err.jspError(n, "jsp.error.params.emptyBody");
}
visitBody(n);
}
public void visit(Node.IncludeAction n) throws JasperException {
JspUtil.checkAttributes("Include action", n,
includeActionAttrs, err);
n.setPage(getJspAttribute("page", null, null,
n.getAttributeValue("page"),
java.lang.String.class, n, false));
visitBody(n);
};
public void visit(Node.ForwardAction n) throws JasperException {
JspUtil.checkAttributes("Forward", n,
forwardActionAttrs, err);
n.setPage(getJspAttribute("page", null, null,
n.getAttributeValue("page"),
java.lang.String.class, n, false));
visitBody(n);
}
public void visit(Node.GetProperty n) throws JasperException {
JspUtil.checkAttributes("GetProperty", n,
getPropertyAttrs, err);
}
public void visit(Node.SetProperty n) throws JasperException {
JspUtil.checkAttributes("SetProperty", n,
setPropertyAttrs, err);
String name = n.getTextAttribute("name");
String property = n.getTextAttribute("property");
String param = n.getTextAttribute("param");
String value = n.getAttributeValue("value");
n.setValue(getJspAttribute("value", null, null, value,
java.lang.Object.class, n, false));
boolean valueSpecified = n.getValue() != null;
if ("*".equals(property)) {
if (param != null || valueSpecified)
err.jspError(n, "jsp.error.setProperty.invalid");
} else if (param != null && valueSpecified) {
err.jspError(n, "jsp.error.setProperty.invalid");
}
visitBody(n);
}
public void visit(Node.UseBean n) throws JasperException {
JspUtil.checkAttributes("UseBean", n,
useBeanAttrs, err);
String name = n.getTextAttribute ("id");
String scope = n.getTextAttribute ("scope");
JspUtil.checkScope(scope, n, err);
String className = n.getTextAttribute ("class");
String type = n.getTextAttribute ("type");
BeanRepository beanInfo = pageInfo.getBeanRepository();
if (className == null && type == null)
err.jspError(n, "jsp.error.useBean.missingType");
if (beanInfo.checkVariable(name))
err.jspError(n, "jsp.error.useBean.duplicate");
if ("session".equals(scope) && !pageInfo.isSession())
err.jspError(n, "jsp.error.useBean.noSession");
Node.JspAttribute jattr
= getJspAttribute("beanName", null, null,
n.getAttributeValue("beanName"),
java.lang.String.class, n, false);
n.setBeanName(jattr);
if (className != null && jattr != null)
err.jspError(n, "jsp.error.useBean.notBoth");
if (className == null)
className = type;
beanInfo.addBean(n, name, className, scope);
visitBody(n);
}
public void visit(Node.PlugIn n) throws JasperException {
JspUtil.checkAttributes("Plugin", n, plugInAttrs, err);
throwErrorIfExpression(n, "type", "jsp:plugin");
throwErrorIfExpression(n, "code", "jsp:plugin");
throwErrorIfExpression(n, "codebase", "jsp:plugin");
throwErrorIfExpression(n, "align", "jsp:plugin");
throwErrorIfExpression(n, "archive", "jsp:plugin");
throwErrorIfExpression(n, "hspace", "jsp:plugin");
throwErrorIfExpression(n, "jreversion", "jsp:plugin");
throwErrorIfExpression(n, "name", "jsp:plugin");
throwErrorIfExpression(n, "vspace", "jsp:plugin");
throwErrorIfExpression(n, "nspluginurl", "jsp:plugin");
throwErrorIfExpression(n, "iepluginurl", "jsp:plugin");
String type = n.getTextAttribute("type");
if (type == null)
err.jspError(n, "jsp.error.plugin.notype");
if (!type.equals("bean") && !type.equals("applet"))
err.jspError(n, "jsp.error.plugin.badtype");
if (n.getTextAttribute("code") == null)
err.jspError(n, "jsp.error.plugin.nocode");
Node.JspAttribute width
= getJspAttribute("width", null, null,
n.getAttributeValue("width"),
java.lang.String.class, n, false);
n.setWidth( width );
Node.JspAttribute height
= getJspAttribute("height", null, null,
n.getAttributeValue("height"),
java.lang.String.class, n, false);
n.setHeight( height );
visitBody(n);
}
public void visit(Node.NamedAttribute n) throws JasperException {
JspUtil.checkAttributes("Attribute", n,
attributeAttrs, err);
visitBody(n);
}
public void visit(Node.JspBody n) throws JasperException {
visitBody(n);
}
public void visit(Node.Declaration n) throws JasperException {
if (pageInfo.isScriptingInvalid()) {
err.jspError(n.getStart(), "jsp.error.no.scriptlets");
}
}
public void visit(Node.Expression n) throws JasperException {
if (pageInfo.isScriptingInvalid()) {
err.jspError(n.getStart(), "jsp.error.no.scriptlets");
}
}
public void visit(Node.Scriptlet n) throws JasperException {
if (pageInfo.isScriptingInvalid()) {
err.jspError(n.getStart(), "jsp.error.no.scriptlets");
}
}
public void visit(Node.ELExpression n) throws JasperException {
if ( !pageInfo.isELIgnored() ) {
String expressions = "${" + new String(n.getText()) + "}";
ELNode.Nodes el = ELParser.parse(expressions);
validateFunctions(el, n);
JspUtil.validateExpressions(
n.getStart(),
expressions,
java.lang.String.class, // XXX - Should template text
// always evaluate to String?
getFunctionMapper(el),
err);
n.setEL(el);
}
}
public void visit(Node.UninterpretedTag n) throws JasperException {
if (n.getNamedAttributeNodes().size() != 0) {
err.jspError(n, "jsp.error.namedAttribute.invalidUse");
}
Attributes attrs = n.getAttributes();
if (attrs != null) {
int attrSize = attrs.getLength();
Node.JspAttribute[] jspAttrs = new Node.JspAttribute[attrSize];
for (int i=0; i < attrSize; i++) {
jspAttrs[i] = getJspAttribute(attrs.getQName(i),
attrs.getURI(i),
attrs.getLocalName(i),
attrs.getValue(i),
java.lang.Object.class,
n,
false);
}
n.setJspAttributes(jspAttrs);
}
visitBody(n);
}
public void visit(Node.CustomTag n) throws JasperException {
TagInfo tagInfo = n.getTagInfo();
if (tagInfo == null) {
err.jspError(n, "jsp.error.missing.tagInfo", n.getQName());
}
/*
* The bodyconet of a SimpleTag cannot be JSP.
*/
if (n.implementsSimpleTag() &&
tagInfo.getBodyContent().equalsIgnoreCase(TagInfo.BODY_CONTENT_JSP)) {
err.jspError(n, "jsp.error.simpletag.badbodycontent",
tagInfo.getTagClassName());
}
/*
* If the tag handler declares in the TLD that it supports dynamic
* attributes, it also must implement the DynamicAttributes
* interface.
*/
if (tagInfo.hasDynamicAttributes()
&& !n.implementsDynamicAttributes()) {
err.jspError(n, "jsp.error.dynamic.attributes.not.implemented",
n.getQName());
}
/*
* Make sure all required attributes are present, either as
* attributes or named attributes (<jsp:attribute>).
* Also make sure that the same attribute is not specified in
* both attributes or named attributes.
*/
TagAttributeInfo[] tldAttrs = tagInfo.getAttributes();
String customActionUri = n.getURI();
Attributes attrs = n.getAttributes();
int attrsSize = (attrs == null) ? 0 : attrs.getLength();
for (int i=0; i<tldAttrs.length; i++) {
String attr = null;
if (attrs != null) {
attr = attrs.getValue(tldAttrs[i].getName());
if (attr == null) {
attr = attrs.getValue(customActionUri,
tldAttrs[i].getName());
}
}
Node.NamedAttribute na =
n.getNamedAttributeNode(tldAttrs[i].getName());
if (tldAttrs[i].isRequired() && attr == null && na == null) {
err.jspError(n, "jsp.error.missing_attribute",
tldAttrs[i].getName(), n.getLocalName());
}
if (attr != null && na != null) {
err.jspError(n, "jsp.error.duplicate.name.jspattribute",
tldAttrs[i].getName());
}
}
Node.Nodes naNodes = n.getNamedAttributeNodes();
int jspAttrsSize = naNodes.size() + attrsSize;
Node.JspAttribute[] jspAttrs = null;
if (jspAttrsSize > 0) {
jspAttrs = new Node.JspAttribute[jspAttrsSize];
}
Hashtable tagDataAttrs = new Hashtable(attrsSize);
checkXmlAttributes(n, jspAttrs, tagDataAttrs);
checkNamedAttributes(n, jspAttrs, attrsSize, tagDataAttrs);
TagData tagData = new TagData(tagDataAttrs);
// JSP.C1: It is a (translation time) error for an action that
// has one or more variable subelements to have a TagExtraInfo
// class that returns a non-null object.
TagExtraInfo tei = tagInfo.getTagExtraInfo();
if (tei != null
&& tei.getVariableInfo(tagData) != null
&& tei.getVariableInfo(tagData).length > 0
&& tagInfo.getTagVariableInfos().length > 0) {
err.jspError("jsp.error.non_null_tei_and_var_subelems",
n.getQName());
}
n.setTagData(tagData);
n.setJspAttributes(jspAttrs);
visitBody(n);
}
public void visit(Node.JspElement n) throws JasperException {
Attributes attrs = n.getAttributes();
if (attrs == null) {
err.jspError(n, "jsp.error.jspelement.missing.name");
}
int xmlAttrLen = attrs.getLength();
Node.Nodes namedAttrs = n.getNamedAttributeNodes();
// XML-style 'name' attribute, which is mandatory, must not be
// included in JspAttribute array
int jspAttrSize = xmlAttrLen-1 + namedAttrs.size();
Node.JspAttribute[] jspAttrs = new Node.JspAttribute[jspAttrSize];
int jspAttrIndex = 0;
// Process XML-style attributes
for (int i=0; i<xmlAttrLen; i++) {
if ("name".equals(attrs.getLocalName(i))) {
n.setNameAttribute(getJspAttribute(attrs.getQName(i),
attrs.getURI(i),
attrs.getLocalName(i),
attrs.getValue(i),
java.lang.String.class,
n,
false));
} else {
if (jspAttrIndex<jspAttrSize) {
jspAttrs[jspAttrIndex++]
= getJspAttribute(attrs.getQName(i),
attrs.getURI(i),
attrs.getLocalName(i),
attrs.getValue(i),
java.lang.Object.class,
n,
false);
}
}
}
if (n.getNameAttribute() == null) {
err.jspError(n, "jsp.error.jspelement.missing.name");
}
// Process named attributes
for (int i=0; i<namedAttrs.size(); i++) {
Node.NamedAttribute na = (Node.NamedAttribute) namedAttrs.getNode(i);
jspAttrs[jspAttrIndex++] = new Node.JspAttribute(na, false);
}
n.setJspAttributes(jspAttrs);
visitBody(n);
}
public void visit(Node.JspOutput n) throws JasperException {
JspUtil.checkAttributes("jsp:output", n, jspOutputAttrs, err);
if (n.getBody() != null) {
err.jspError(n, "jsp.error.jspoutput.nonemptybody");
}
String omitXmlDecl = n.getAttributeValue("omit-xml-declaration");
String doctypeName = n.getAttributeValue("doctype-root-element");
String doctypePublic = n.getAttributeValue("doctype-public");
String doctypeSystem = n.getAttributeValue("doctype-system");
String omitXmlDeclOld = pageInfo.getOmitXmlDecl();
String doctypeNameOld = pageInfo.getDoctypeName();
String doctypePublicOld = pageInfo.getDoctypePublic();
String doctypeSystemOld = pageInfo.getDoctypeSystem();
if (omitXmlDecl != null && omitXmlDeclOld != null &&
!omitXmlDecl.equals(omitXmlDeclOld) ) {
err.jspError(n, "jsp.error.jspoutput.conflict",
"omit-xml-declaration", omitXmlDeclOld, omitXmlDecl);
}
if (doctypeName != null && doctypeNameOld != null &&
!doctypeName.equals(doctypeNameOld) ) {
err.jspError(n, "jsp.error.jspoutput.conflict",
"doctype-root-element", doctypeNameOld, doctypeName);
}
if (doctypePublic != null && doctypePublicOld != null &&
!doctypePublic.equals(doctypePublicOld) ) {
err.jspError(n, "jsp.error.jspoutput.conflict",
"doctype-public", doctypePublicOld, doctypePublic);
}
if (doctypeSystem != null && doctypeSystemOld != null &&
!doctypeSystem.equals(doctypeSystemOld) ) {
err.jspError(n, "jsp.error.jspoutput.conflict",
"doctype-system", doctypeSystemOld, doctypeSystem);
}
if (doctypeName == null && doctypeSystem != null ||
doctypeName != null && doctypeSystem == null) {
err.jspError(n, "jsp.error.jspoutput.doctypenamesystem");
}
if (doctypePublic != null && doctypeSystem == null) {
err.jspError(n, "jsp.error.jspoutput.doctypepulicsystem");
}
if (omitXmlDecl != null) {
pageInfo.setOmitXmlDecl(omitXmlDecl);
}
if (doctypeName != null) {
pageInfo.setDoctypeName(doctypeName);
}
if (doctypeSystem != null) {
pageInfo.setDoctypeSystem(doctypeSystem);
}
if (doctypePublic != null) {
pageInfo.setDoctypePublic(doctypePublic);
}
}
public void visit(Node.InvokeAction n) throws JasperException {
JspUtil.checkAttributes("Invoke", n, invokeAttrs, err);
String scope = n.getTextAttribute ("scope");
JspUtil.checkScope(scope, n, err);
String var = n.getTextAttribute("var");
String varReader = n.getTextAttribute("varReader");
if (scope != null && var == null && varReader == null) {
err.jspError(n, "jsp.error.missing_var_or_varReader");
}
if (var != null && varReader != null) {
err.jspError(n, "jsp.error.var_and_varReader");
}
}
public void visit(Node.DoBodyAction n) throws JasperException {
JspUtil.checkAttributes("DoBody", n, doBodyAttrs, err);
String scope = n.getTextAttribute ("scope");
JspUtil.checkScope(scope, n, err);
String var = n.getTextAttribute("var");
String varReader = n.getTextAttribute("varReader");
if (scope != null && var == null && varReader == null) {
err.jspError(n, "jsp.error.missing_var_or_varReader");
}
if (var != null && varReader != null) {
err.jspError(n, "jsp.error.var_and_varReader");
}
}
/*
* Make sure the given custom action does not have any invalid
* attributes.
*
* A custom action and its declared attributes always belong to the
* same namespace, which is identified by the prefix name of the
* custom tag invocation. For example, in this invocation:
*
* <my:test a="1" b="2" c="3"/>, the action
*
* "test" and its attributes "a", "b", and "c" all belong to the
* namespace identified by the prefix "my". The above invocation would
* be equivalent to:
*
* <my:test my:a="1" my:b="2" my:c="3"/>
*
* An action attribute may have a prefix different from that of the
* action invocation only if the underlying tag handler supports
* dynamic attributes, in which case the attribute with the different
* prefix is considered a dynamic attribute.
*/
private void checkXmlAttributes(Node.CustomTag n,
Node.JspAttribute[] jspAttrs,
Hashtable tagDataAttrs)
throws JasperException {
TagInfo tagInfo = n.getTagInfo();
if (tagInfo == null) {
err.jspError(n, "jsp.error.missing.tagInfo", n.getQName());
}
TagAttributeInfo[] tldAttrs = tagInfo.getAttributes();
Attributes attrs = n.getAttributes();
for (int i=0; attrs != null && i<attrs.getLength(); i++) {
boolean found = false;
for (int j=0; tldAttrs != null && j<tldAttrs.length; j++) {
if (attrs.getLocalName(i).equals(tldAttrs[j].getName())
&& (attrs.getURI(i) == null
|| attrs.getURI(i).length() == 0
|| attrs.getURI(i).equals(n.getURI()))) {
if (tldAttrs[j].canBeRequestTime()) {
Class expectedType = String.class;
try {
String typeStr = tldAttrs[j].getTypeName();
if( tldAttrs[j].isFragment() ) {
expectedType = JspFragment.class;
}
else if( typeStr != null ) {
expectedType = JspUtil.toClass(typeStr,
loader);
}
jspAttrs[i]
= getJspAttribute(attrs.getQName(i),
attrs.getURI(i),
attrs.getLocalName(i),
attrs.getValue(i),
expectedType,
n,
false);
} catch (ClassNotFoundException e) {
err.jspError(n,
"jsp.error.unknown_attribute_type",
tldAttrs[j].getName(),
tldAttrs[j].getTypeName() );
}
} else {
// Attribute does not accept any expressions.
// Make sure its value does not contain any.
if (isExpression(n, attrs.getValue(i))) {
err.jspError(n,
"jsp.error.attribute.custom.non_rt_with_expr",
tldAttrs[j].getName());
}
jspAttrs[i]
= new Node.JspAttribute(attrs.getQName(i),
attrs.getURI(i),
attrs.getLocalName(i),
attrs.getValue(i),
false,
null,
false);
}
if (jspAttrs[i].isExpression()) {
tagDataAttrs.put(attrs.getQName(i),
TagData.REQUEST_TIME_VALUE);
} else {
tagDataAttrs.put(attrs.getQName(i),
attrs.getValue(i));
}
found = true;
break;
}
}
if (!found) {
if (tagInfo.hasDynamicAttributes()) {
jspAttrs[i] = getJspAttribute(attrs.getQName(i),
attrs.getURI(i),
attrs.getLocalName(i),
attrs.getValue(i),
java.lang.Object.class,
n,
true);
} else {
err.jspError(n, "jsp.error.bad_attribute",
attrs.getQName(i), n.getLocalName());
}
}
}
}
/*
* Make sure the given custom action does not have any invalid named
* attributes
*/
private void checkNamedAttributes(Node.CustomTag n,
Node.JspAttribute[] jspAttrs,
int start,
Hashtable tagDataAttrs)
throws JasperException {
TagInfo tagInfo = n.getTagInfo();
if (tagInfo == null) {
err.jspError(n, "jsp.error.missing.tagInfo", n.getQName());
}
TagAttributeInfo[] tldAttrs = tagInfo.getAttributes();
Node.Nodes naNodes = n.getNamedAttributeNodes();
for (int i=0; i<naNodes.size(); i++) {
Node.NamedAttribute na = (Node.NamedAttribute)
naNodes.getNode(i);
boolean found = false;
for (int j=0; j<tldAttrs.length; j++) {
/*
* See above comment about namespace matches. For named
* attributes, we use the prefix instead of URI as the
* match criterion, because in the case of a JSP document,
* we'd have to keep track of which namespaces are in scope
* when parsing a named attribute, in order to determine
* the URI that the prefix of the named attribute's name
* matches to.
*/
String attrPrefix = na.getPrefix();
if (na.getLocalName().equals(tldAttrs[j].getName())
&& (attrPrefix == null || attrPrefix.length() == 0
|| attrPrefix.equals(n.getPrefix()))) {
jspAttrs[start + i] = new Node.JspAttribute(na, false);
NamedAttributeVisitor nav = null;
if (na.getBody() != null) {
nav = new NamedAttributeVisitor();
na.getBody().visit(nav);
}
if (nav != null && nav.hasDynamicContent()) {
tagDataAttrs.put(na.getName(),
TagData.REQUEST_TIME_VALUE);
} else {
tagDataAttrs.put(na.getName(), na.getText());
}
found = true;
break;
}
}
if (!found) {
if (tagInfo.hasDynamicAttributes()) {
jspAttrs[start + i] = new Node.JspAttribute(na, true);
} else {
err.jspError(n, "jsp.error.bad_attribute",
na.getName(), n.getLocalName());
}
}
}
}
/**
* Preprocess attributes that can be expressions. Expression
* delimiters are stripped.
* <p>
* If value is null, checks if there are any
* NamedAttribute subelements in the tree node, and if so,
* constructs a JspAttribute out of a child NamedAttribute node.
*/
private Node.JspAttribute getJspAttribute(String qName,
String uri,
String localName,
String value,
Class expectedType,
Node n,
boolean dynamic)
throws JasperException {
Node.JspAttribute result = null;
// XXX Is it an error to see "%=foo%" in non-Xml page?
// (We won't see "<%=foo%> in xml page because '<' is not a
// valid attribute value in xml).
if (value != null) {
if (n.getRoot().isXmlSyntax() && value.startsWith("%=")) {
result = new Node.JspAttribute(
qName,
uri,
localName,
value.substring(2, value.length()-1),
true,
null,
dynamic);
}
else if(!n.getRoot().isXmlSyntax() && value.startsWith("<%=")) {
result = new Node.JspAttribute(
qName,
uri,
localName,
value.substring(3, value.length()-2),
true,
null,
dynamic);
}
else {
// The attribute can contain expressions but is not a
// scriptlet expression; thus, we want to run it through
// the expression interpreter
// validate expression syntax if string contains
// expression(s)
ELNode.Nodes el = ELParser.parse(value);
if (el.containsEL() && !pageInfo.isELIgnored()) {
validateFunctions(el, n);
JspUtil.validateExpressions(
n.getStart(),
value,
expectedType,
getFunctionMapper(el),
this.err);
result = new Node.JspAttribute(qName, uri, localName,
value, false, el,
dynamic);
} else {
value = value.replace(Constants.ESC, '$');
result = new Node.JspAttribute(qName, uri, localName,
value, false, null,
dynamic);
}
}
}
else {
// Value is null. Check for any NamedAttribute subnodes
// that might contain the value for this attribute.
// Otherwise, the attribute wasn't found so we return null.
Node.NamedAttribute namedAttributeNode =
n.getNamedAttributeNode( qName );
if( namedAttributeNode != null ) {
result = new Node.JspAttribute(namedAttributeNode,
dynamic);
}
}
return result;
}
/*
* Checks to see if the given attribute value represents a runtime or
* EL expression.
*/
private boolean isExpression(Node n, String value) {
if ((n.getRoot().isXmlSyntax() && value.startsWith("%="))
|| (!n.getRoot().isXmlSyntax() && value.startsWith("<%="))
|| (value.indexOf("${") != -1 && !pageInfo.isELIgnored()))
return true;
else
return false;
}
/*
* Throws exception if the value of the attribute with the given
* name in the given node is given as an RT or EL expression, but the
* spec requires a static value.
*/
private void throwErrorIfExpression(Node n, String attrName,
String actionName)
throws JasperException {
if (n.getAttributes() != null
&& n.getAttributes().getValue(attrName) != null
&& isExpression(n, n.getAttributes().getValue(attrName))) {
err.jspError(n,
"jsp.error.attribute.standard.non_rt_with_expr",
attrName, actionName);
}
}
private static class NamedAttributeVisitor extends Node.Visitor {
private boolean hasDynamicContent;
public void doVisit(Node n) throws JasperException {
if (!(n instanceof Node.JspText)
&& !(n instanceof Node.TemplateText)) {
hasDynamicContent = true;
}
visitBody(n);
}
public boolean hasDynamicContent() {
return hasDynamicContent;
}
}
private String findUri(String prefix, Node n) {
for (Node p = n; p != null; p = p.getParent()) {
Attributes attrs = p.getTaglibAttributes();
if (attrs == null) {
continue;
}
for (int i = 0; i < attrs.getLength(); i++) {
String name = attrs.getQName(i);
int k = name.indexOf(':');
if (prefix == null && k < 0) {
// prefix not specified and a default ns found
return attrs.getValue(i);
}
if (prefix != null && k >= 0 &&
prefix.equals(name.substring(k+1))) {
return attrs.getValue(i);
}
}
}
return null;
}
/**
* Validate functions in EL expressions
*/
private void validateFunctions(ELNode.Nodes el, Node n)
throws JasperException {
class FVVisitor extends ELNode.Visitor {
Node n;
FVVisitor(Node n) {
this.n = n;
}
public void visit(ELNode.Function func) throws JasperException {
String prefix = func.getPrefix();
String function = func.getName();
String uri = null;
if (n.getRoot().isXmlSyntax()) {
uri = findUri(prefix, n);
} else if (prefix != null) {
uri = pageInfo.getURI(prefix);
}
if (uri == null) {
if (prefix == null) {
err.jspError(n, "jsp.error.noFunctionPrefix",
function);
}
else {
err.jspError(n,
"jsp.error.attribute.invalidPrefix", prefix);
}
}
TagLibraryInfo taglib = pageInfo.getTaglib(uri);
FunctionInfo funcInfo = null;
if (taglib != null) {
funcInfo = taglib.getFunction(function);
}
if (funcInfo == null) {
err.jspError(n, "jsp.error.noFunction", function);
}
// Skip TLD function uniqueness check. Done by Schema ?
func.setUri(uri);
func.setFunctionInfo(funcInfo);
processSignature(func);
}
}
el.visit(new FVVisitor(n));
}
private void processSignature(ELNode.Function func)
throws JasperException {
func.setMethodName(getMethod(func));
func.setParameters(getParameters(func));
}
/**
* Get the method name from the signature.
*/
private String getMethod(ELNode.Function func)
throws JasperException {
FunctionInfo funcInfo = func.getFunctionInfo();
String signature = funcInfo.getFunctionSignature();
int start = signature.indexOf(' ');
if (start < 0) {
err.jspError("jsp.error.tld.fn.invalid.signature",
func.getPrefix(), func.getName());
}
int end = signature.indexOf('(');
if (end < 0) {
err.jspError("jsp.error.tld.fn.invalid.signature.parenexpected",
func.getPrefix(), func.getName());
}
return signature.substring(start+1, end).trim();
}
/**
* Get the parameters types from the function signature.
* @return An array of parameter class names
*/
private String[] getParameters(ELNode.Function func)
throws JasperException {
FunctionInfo funcInfo = func.getFunctionInfo();
String signature = funcInfo.getFunctionSignature();
ArrayList params = new ArrayList();
// Signature is of the form
// <return-type> S <method-name S? '('
// < <arg-type> ( ',' <arg-type> )* )? ')'
int start = signature.indexOf('(') + 1;
boolean lastArg = false;
while (true) {
int p = signature.indexOf(',', start);
if (p < 0) {
p = signature.indexOf(')', start);
if (p < 0) {
err.jspError("jsp.error.tld.fn.invalid.signature",
func.getPrefix(), func.getName());
}
lastArg = true;
}
params.add(signature.substring(start, p).trim());
if (lastArg) {
break;
}
start = p+1;
}
return (String[]) params.toArray(new String[params.size()]);
}
private FunctionMapper getFunctionMapper(ELNode.Nodes el)
throws JasperException {
class ValidateFunctionMapper implements FunctionMapper {
private HashMap fnmap = new java.util.HashMap();
public void mapFunction(String fnQName, Method method) {
fnmap.put(fnQName, method);
}
public Method resolveFunction(String prefix,
String localName) {
return (Method) this.fnmap.get(prefix + ":" + localName);
}
}
class MapperELVisitor extends ELNode.Visitor {
ValidateFunctionMapper fmapper;
MapperELVisitor(ValidateFunctionMapper fmapper) {
this.fmapper = fmapper;
}
public void visit(ELNode.Function n) throws JasperException {
Class c = null;
Method method = null;
try {
c = loader.loadClass(
n.getFunctionInfo().getFunctionClass());
} catch (ClassNotFoundException e) {
err.jspError("jsp.error.function.classnotfound",
n.getFunctionInfo().getFunctionClass(),
n.getPrefix() + ':' + n.getName(),
e.getMessage());
}
String paramTypes[] = n.getParameters();
int size = paramTypes.length;
Class params[] = new Class[size];
int i = 0;
try {
for (i = 0; i < size; i++) {
params[i] = JspUtil.toClass(paramTypes[i], loader);
}
method = c.getDeclaredMethod(n.getMethodName(),
params);
} catch (ClassNotFoundException e) {
err.jspError("jsp.error.signature.classnotfound",
paramTypes[i],
n.getPrefix() + ':' + n.getName(),
e.getMessage());
} catch (NoSuchMethodException e ) {
err.jspError("jsp.error.noFunctionMethod",
n.getMethodName(), n.getName(),
c.getName());
}
fmapper.mapFunction(n.getPrefix() + ':' + n.getName(),
method);
}
}
ValidateFunctionMapper fmapper = new ValidateFunctionMapper();
el.visit(new MapperELVisitor(fmapper));
return fmapper;
}
} // End of ValidateVisitor
/**
* A visitor for validating TagExtraInfo classes of all tags
*/
static class TagExtraInfoVisitor extends Node.Visitor {
private PageInfo pageInfo;
private ErrorDispatcher err;
/*
* Constructor
*/
TagExtraInfoVisitor(Compiler compiler) {
this.pageInfo = compiler.getPageInfo();
this.err = compiler.getErrorDispatcher();
}
public void visit(Node.CustomTag n) throws JasperException {
TagInfo tagInfo = n.getTagInfo();
if (tagInfo == null) {
err.jspError(n, "jsp.error.missing.tagInfo", n.getQName());
}
ValidationMessage[] errors = tagInfo.validate(n.getTagData());
if (errors != null && errors.length != 0) {
StringBuffer errMsg = new StringBuffer();
errMsg.append("<h3>");
errMsg.append(Localizer.getMessage("jsp.error.tei.invalid.attributes",
n.getQName()));
errMsg.append("</h3>");
for (int i=0; i<errors.length; i++) {
errMsg.append("<p>");
if (errors[i].getId() != null) {
errMsg.append(errors[i].getId());
errMsg.append(": ");
}
errMsg.append(errors[i].getMessage());
errMsg.append("</p>");
}
err.jspError(n, errMsg.toString());
}
visitBody(n);
}
}
public static void validate(Compiler compiler,
Node.Nodes page) throws JasperException {
/*
* Visit the page/tag directives first, as they are global to the page
* and are position independent.
*/
page.visit(new DirectiveVisitor(compiler));
// Determine the default output content type
PageInfo pageInfo = compiler.getPageInfo();
String contentType = pageInfo.getContentType();
if (contentType == null || contentType.indexOf("charset=") < 0) {
boolean isXml = page.getRoot().isXmlSyntax();
String defaultType;
if (contentType == null) {
defaultType = isXml? "text/xml": "text/html";
} else {
defaultType = contentType;
}
String charset = null;
if (isXml) {
charset = "UTF-8";
} else {
if (!page.getRoot().isDefaultPageEncoding()) {
charset = page.getRoot().getPageEncoding();
}
}
if (charset != null) {
pageInfo.setContentType(defaultType + ";charset=" + charset);
} else {
pageInfo.setContentType(defaultType);
}
}
/*
* Validate all other nodes.
* This validation step includes checking a custom tag's mandatory and
* optional attributes against information in the TLD (first validation
* step for custom tags according to JSP.10.5).
*/
page.visit(new ValidateVisitor(compiler));
/*
* Invoke TagLibraryValidator classes of all imported tags
* (second validation step for custom tags according to JSP.10.5).
*/
validateXmlView(new PageDataImpl(page, compiler), compiler);
/*
* Invoke TagExtraInfo method isValid() for all imported tags
* (third validation step for custom tags according to JSP.10.5).
*/
page.visit(new TagExtraInfoVisitor(compiler));
}
//*********************************************************************
// Private (utility) methods
/**
* Validate XML view against the TagLibraryValidator classes of all
* imported tag libraries.
*/
private static void validateXmlView(PageData xmlView, Compiler compiler)
throws JasperException {
StringBuffer errMsg = null;
ErrorDispatcher errDisp = compiler.getErrorDispatcher();
for (Iterator iter=compiler.getPageInfo().getTaglibs().iterator();
iter.hasNext(); ) {
Object o = iter.next();
if (!(o instanceof TagLibraryInfoImpl))
continue;
TagLibraryInfoImpl tli = (TagLibraryInfoImpl) o;
ValidationMessage[] errors = tli.validate(xmlView);
if ((errors != null) && (errors.length != 0)) {
if (errMsg == null) {
errMsg = new StringBuffer();
}
errMsg.append("<h3>");
errMsg.append(Localizer.getMessage("jsp.error.tlv.invalid.page",
tli.getShortName()));
errMsg.append("</h3>");
for (int i=0; i<errors.length; i++) {
if (errors[i] != null) {
errMsg.append("<p>");
errMsg.append(errors[i].getId());
errMsg.append(": ");
errMsg.append(errors[i].getMessage());
errMsg.append("</p>");
}
}
}
}
if (errMsg != null) {
errDisp.jspError(errMsg.toString());
}
}
}
| |
package org.mediterraneancoin.proxy;
import java.io.IOException;
import java.net.Socket;
import java.io.PrintStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.Scanner;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;
import java.security.SecureRandom;
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingDeque;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.ArrayNode;
public class StratumConnection
{
private static StratumConnection instance;
public static synchronized StratumConnection getInstance() {
if (instance == null)
instance = new StratumConnection();
return instance;
}
public static synchronized StratumConnection reset() {
instance = new StratumConnection();
return instance;
}
private Socket sock;
//private AtomicLong last_network_action;
private AtomicLong lastOutputNetworkAction = new AtomicLong(System.currentTimeMillis());
private AtomicLong lastInputNetworkAction = new AtomicLong(System.currentTimeMillis());
private volatile boolean open;
private volatile boolean miningSubscribed;
private String workerName, workerPassword;
//private byte[] extranonce1;
private String extraNonce1Str;
private long extranonce2_size;
private AtomicLong nextRequestId = new AtomicLong(0);
private LinkedBlockingQueue<ObjectNode> out_queue = new LinkedBlockingQueue<ObjectNode>();
private SecureRandom rnd;
private LinkedBlockingQueue<String> okJobs = new LinkedBlockingQueue<String>();
static final ObjectMapper mapper = new ObjectMapper();
String serverAddress;
int port;
String notifySubscription;
boolean lastOperationResult;
long difficulty;
private LinkedBlockingDeque<ServerWork> workQueue = new LinkedBlockingDeque<ServerWork>();
private LinkedBlockingDeque<StratumResult> stratumResults = new LinkedBlockingDeque<StratumResult>();
public static boolean DEBUG = true;
private static final String prefix = "STRATUM-CONNECTION ";
public static class StratumResult {
long id;
boolean result;
String error;
long timestamp = System.currentTimeMillis();
@Override
public int hashCode() {
int hash = 7;
hash = 67 * hash + (int) (this.id ^ (this.id >>> 32));
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final StratumResult other = (StratumResult) obj;
if (this.id != other.id) {
return false;
}
return true;
}
@Override
public String toString() {
return "StratumResult{" + "id=" + id + ", result=" + result + ", error=" + error + '}';
}
}
public static void main(String [] arg) throws IOException, InterruptedException, NoSuchAlgorithmException, CloneNotSupportedException {
if (true) {
String s1 = "00000000000000000000000000000000000000000000000028ac010000000000";
String s2 = "00000000FFFF0000000000000000000000000000000000000000000000000000";
System.out.println(new BigInteger(s1, 16).toString(16));
BigInteger b0 = new BigInteger(s2, 16);
BigInteger b1 = new BigInteger(new StringBuilder(s1).reverse().toString(), 16);
System.out.println(b1.toString(16));
System.out.println(b0.toString(16));
BigInteger d = b0.divide(b1);
System.out.println(d.toString(16));
System.out.println(d.toString());
return;
}
StratumConnection connection = new StratumConnection();
if (true) {
connection.doTests();
return;
}
connection.open("node4.mediterraneancoin.org", 3333);
connection.sendWorkerAuthorization("mrtexaznl.1", "xxx");
Thread.sleep(500);
connection.sendMiningSubscribe();
Thread.sleep(300);
while (connection.workQueue.size() == 0) {
Thread.sleep(50);
}
ServerWork work = connection.getWork();
System.out.println(work);
System.out.println("HEADER: " + work.block_header);
Thread.sleep(25000);
//"{\"id\": 1, \"method\": \"mining.subscribe\", \"params\": []}\\n"
//ObjectNode o = new ObjectNode(JsonNodeFactory.instance)
}
public StratumConnection()
{
rnd = new SecureRandom();
}
public void open(String serverAddress, int port) throws IOException {
this.serverAddress = serverAddress;
this.port = port;
this.sock = new Socket(serverAddress, port);
//last_network_action=new AtomicLong(System.nanoTime());
open=true;
new OutThread().start();
new InThread().start();
System.out.println("successfully connected to stratum pool " + serverAddress + "/" + port);
}
public void sendMiningSubscribe() {
ObjectNode resultNode = mapper.createObjectNode();
// {"id": 1, "method": "mining.subscribe", "params": []}\n
resultNode.put("id", nextRequestId.incrementAndGet() );
resultNode.put("method", "mining.subscribe");
ArrayNode putArray = resultNode.putArray("params");
putArray.add("mcproxy4");
if (DEBUG)
System.out.println(resultNode.asText());
sendMessage(resultNode);
}
public boolean sendWorkerAuthorization(String workerName, String workerPassword) {
this.workerName = workerName;
this.workerPassword = workerPassword;
ObjectNode resultNode = mapper.createObjectNode();
// {"params": ["slush.miner1", "password"], "id": 2, "method": "mining.authorize"}\n
ArrayNode putArray = resultNode.putArray("params");
putArray.add(workerName);
putArray.add(workerPassword);
long requestId = nextRequestId.incrementAndGet();
resultNode.put("id", requestId );
resultNode.put("method", "mining.authorize");
if (DEBUG)
System.out.println(resultNode.asText());
sendMessage(resultNode);
StratumResult res = null;
long delta = 0;
while ( delta < 20000 && (res = findStratumResult(requestId)) == null) {
try {
Thread.sleep(10);
delta += 10;
} catch (InterruptedException ex) {
}
}
if (res == null) {
if (DEBUG)
System.out.println(prefix + "sendWorkerAuthorization error: no response from pool in 20s");
System.err.println("no response from stratum pool in 20s, while sending credentials; bailing out");
System.err.flush();
//throw new RuntimeException("no response from stratum pool");
//return false;
} else {
if (res.result == false) {
System.err.println("registration with stratum pool not successful, wrong credentials? bailing out");
System.err.flush();
//throw new RuntimeException("credentials registration with stratum pool failed");
} else {
System.out.println("registration with stratum pool is successful!");
System.out.flush();
}
}
return res.result;
}
/**
* the worker which submits this work, must update the nTime and nonce fields
* @param work
*/
public StratumResult sendWorkSubmission(ServerWork work) {
if (!okJobs.contains(work.jobId)) {
System.out.println(prefix + " sendWorkSubmission error: job " + work.jobId + " is no more valid!");
StratumResult result = new StratumResult();
result.result = false;
result.error = "job " + work.jobId + " is no more valid!";
result.id = 1;
return result;
}
// 1. Check if blockheader meets requested difficulty
// NOTE: this is done previously
// 2. Lookup for job and extranonce used for creating given block header
// (job, extranonce2) = self.get_job_from_header(header)
// job, extranonce2 are inside work
// 3. Format extranonce2 to hex string
//extranonce2_hex = binascii.hexlify(self.extranonce2_padding(extranonce2))
String extranonce2_hex = extranonce2_padding(work);
// 4. Parse ntime and nonce from header
//ntimepos = 17*8 # 17th integer in datastring
//noncepos = 19*8 # 19th integer in datastring
//ntime = header[ntimepos:ntimepos+8]
//nonce = header[noncepos:noncepos+8]
//work.nTime
//work.nonce
// 5. Submit share to the pool
//return self.f.rpc('mining.submit', [worker_name, job.job_id, extranonce2_hex, ntime, nonce])
// {"params": ["redacted", "1369818357 489", "12000000", "51a5c4f5", "41f20233"], "id": 2, "method": "mining.submit"}
ObjectNode resultNode = mapper.createObjectNode();
ArrayNode putArray = resultNode.putArray("params");
putArray.add(work.workerName);
putArray.add(work.jobId);
putArray.add(extranonce2_hex);
putArray.add(work.minerNtime);
putArray.add(work.nonce);
long requestId = nextRequestId.incrementAndGet();
resultNode.put("id", requestId );
resultNode.put("method", "mining.submit");
if (DEBUG)
System.out.println(prefix + " sendWorkSubmission: " + resultNode.asText());
sendMessage(resultNode);
StratumResult res = null;
long delta = 0;
while ( delta < 10000 && (res = findStratumResult(requestId)) == null) {
try {
Thread.sleep(10);
delta += 10;
} catch (InterruptedException ex) {
}
}
if (res == null) {
if (DEBUG)
System.out.println(prefix + " sendWorkSubmission error: no response from pool in 10s");
StratumResult result = new StratumResult();
result.result = false;
result.error = "no response from pool in 10s";
result.id = 1;
return result;
}
return res;
}
private StratumResult findStratumResult(long requestId) {
long now = System.currentTimeMillis();
for (Iterator<StratumResult> i = stratumResults.iterator(); i.hasNext();) {
StratumResult res = i.next();
if (res.id == requestId) {
if (DEBUG)
System.out.println("findStratumResult: " + res.toString());
stratumResults.remove(res);
return res;
}
long delta = (now - res.timestamp) / 1000;
if (delta > 120)
try {
stratumResults.remove(res);
} catch (Exception ex) {}
}
return null;
}
final private Object lock = new Object();
public ServerWork getStratumWork() {
ServerWork result = null;
synchronized(lock) {
while ((result = workQueue.pollFirst()) == null) {
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
}
}
}
return result;
}
public static String extranonce2_padding(ServerWork work) {
// Update coinbase. Always use an LE encoded nonce2 to fill in values from left to right and prevent overflow errors with small n2sizes
String res;
res = String.format("%016X", work.extranonce2.get());
//res = Long.toHexString(work.extranonce2.get());
if (work.extranonce2_size * 2 < res.length()) {
//res = res.substring((int)(res.length() - work.extranonce2_size * 2));
res = res.substring(0, (int)(res.length() - work.extranonce2_size * 2));
} else if (work.extranonce2_size * 2 > res.length()) {
while (work.extranonce2_size * 2 > res.length())
//res = "00" + res;
res = res + "00";
}
if (DEBUG)
System.out.println(prefix + " extranonce2_padding: " + res + ", len=" + res.length());
return res;
//ByteBuffer outputByteBuffer = ByteBuffer.allocate((int) work.extranonce2_size);
/*
>>> import struct
>>> struct.pack(">I",34) // big-endian
'\x00\x00\x00"'
>>> ord('"')
34
>>> hex(ord('"'))
'0x22'
*/
}
static public byte [] hash256(byte [] a) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
// hash1 size: 32 bytes
byte [] hash1 = digest.digest(a);
digest.reset();
// hash2 size: 32 bytes
byte [] hash2 = digest.digest(hash1);
return hash2;
//System.out.println("hash2 len: " + hash2.length);
}
public static String toHexString(byte [] barr) {
String result = "";
for (int i = 0; i < barr.length; i++) {
result += String.format("%02X", barr[i]);
}
return result;
}
public static byte [] toByteArray(String bin) {
if (bin.length() % 2 != 0)
throw new RuntimeException("bin.length() % 2 != 0");
byte [] result = new byte[bin.length() / 2];
for (int i = 0; i < result.length; i++) {
String b = bin.substring(i * 2, (i+1) * 2);
result[i] = (byte) (Integer.parseInt(b, 16) & 0xFF);
}
return result;
}
public static byte [] reverseHash(byte [] barr) {
if (barr.length % 4 != 0)
throw new RuntimeException("barr.length() % 4 != 0");
byte [] result = new byte[barr.length];
for (int i = 0; i < barr.length; i += 4) {
result[i] = barr[i+3];
result[i+1] = barr[i+2];
result[i+2] = barr[i+1];
result[i+3] = barr[i];
}
return result;
}
public static long reverse(long x) {
ByteBuffer bbuf = ByteBuffer.allocate(8);
bbuf.order(ByteOrder.BIG_ENDIAN);
bbuf.putLong(x);
bbuf.order(ByteOrder.LITTLE_ENDIAN);
return bbuf.getLong(0);
}
public ServerWork getWork() throws NoSuchAlgorithmException, CloneNotSupportedException {
if (DEBUG) {
System.out.println(prefix + "getWork, workQueue size: " + workQueue.size());
}
// Pick the latest job from pool
ServerWork originalWork = workQueue.peek();
if (originalWork == null) {
if (DEBUG) {
System.out.println(prefix + "getWork, returning null!");
}
return null;
}
ServerWork work = (ServerWork) originalWork.clone();
work.timestamp = System.currentTimeMillis();
// 1. Increase extranonce2
long extranonce2 = reverse(originalWork.extranonce2.incrementAndGet());
// we need to truncate extranonce2, respecting its size!
//extranonce2 = (extranonce2 >> 32) & 0xFFFFFFFF;
work.extranonce2 = new AtomicLong(extranonce2);
// 2. Build final extranonce
String extranonce = work.extraNonce1Str + extranonce2_padding(work);
if (DEBUG)
System.out.println(prefix + " extranonce:" + extranonce);
// 3. Put coinbase transaction together
String coinbase_bin = work.coinbasePart1 + extranonce + work.coinbasePart2;
// self.coinb1_bin + extranonce + self.coinb2_bin
// 4. Calculate coinbase hash
byte [] coinbase_hash = hash256( toByteArray(coinbase_bin) );
// 5. Calculate merkle root
// merkle_root = binascii.hexlify(utils.reverse_hash(job.build_merkle_root(coinbase_hash)))
byte [] merkle_root = reverseHash ( buildMerkleRoot(work, coinbase_hash) );
String merkleRootStr = toHexString( merkle_root );
/*
# 3. Put coinbase transaction together
coinbase_bin = job.build_coinbase(extranonce)
# 4. Calculate coinbase hash
coinbase_hash = utils.doublesha(coinbase_bin)
# 5. Calculate merkle root
merkle_root = binascii.hexlify(utils.reverse_hash(job.build_merkle_root(coinbase_hash)))
# 6. Generate current ntime
ntime = int(time.time()) + job.ntime_delta
# 7. Serialize header
block_header = job.serialize_header(merkle_root, ntime, 0)
*
*
def build_merkle_root(self, coinbase_hash):
merkle_root = coinbase_hash
for h in self.merkle_branch:
merkle_root = utils.doublesha(merkle_root + h)
return merkle_root
*/
// 6. Generate current ntime
//ntime = int(time.time()) + job.ntime_delta
// job.ntime_delta = int(ntime, 16) - int(time.time())
long unixTime = System.currentTimeMillis() / 1000L;
long ntime = unixTime + work.ntime_delta;
work.minerNtime = String.format("%04X", ntime);
// 7. Serialize header
//block_header = job.serialize_header(merkle_root, ntime, 0)
work.block_header =
work.version +
work.hashPrevBlock +
merkleRootStr +
work.minerNtime +
work.nBit +
"00000000000000" +
"800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000";
/*
def serialize_header(self, merkle_root, ntime, nonce):
r = self.version
r += self.prevhash
r += merkle_root
r += binascii.hexlify(struct.pack(">I", ntime))
r += self.nbits
r += binascii.hexlify(struct.pack(">I", nonce))
r += '000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000' # padding
return r
*/
// 8. Register job params
//self.register_merkle(job, merkle_root, extranonce2)
setDifficulty(work, difficulty);
if (DEBUG) {
System.out.println(prefix + "getWork, returning: " + work);
}
return work;
}
static byte [] concat(byte [] a, byte [] b) {
byte [] result = new byte[a.length + b.length];
System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b,0, result, a.length, b.length);
return result;
}
static public byte [] buildMerkleRoot(ServerWork work, byte [] coinbase_hash) throws NoSuchAlgorithmException {
byte [] merkle_root = coinbase_hash;
for (int i = 0; i < work.merkleBranches.length; i++) {
byte [] h = toByteArray( work.merkleBranches[i] );
merkle_root = hash256( concat(merkle_root, h) );
}
return merkle_root;
}
/*
def set_difficulty(self, new_difficulty):
if self.scrypt_target:
dif1 = 0x0000ffff00000000000000000000000000000000000000000000000000000000
else:
dif1 = 0x00000000ffff0000000000000000000000000000000000000000000000000000
self.target = int(dif1 / new_difficulty)
self.target_hex = binascii.hexlify(utils.uint256_to_str(self.target))
self.difficulty = new_difficulty
*/
void setDifficulty(ServerWork work, long new_difficulty) {
BigInteger dif1 = new BigInteger("00000000ffff0000000000000000000000000000000000000000000000000000", 16);
work.target = dif1.divide( BigInteger.valueOf(new_difficulty) );
byte [] tbe = work.target.toByteArray(); // big endian
work.target_hex = "";
for (int i = tbe.length - 1; i >= 0; i--)
work.target_hex += String.format("%02X", tbe[i]);
while (work.target_hex.length() < 64)
work.target_hex += "00";
}
/*
https://github.com/slush0/stratum-mining-proxy/blob/master/mining_libs/jobs.py
def getwork(self, no_midstate=True):
'''Miner requests for new getwork'''
job = self.last_job # Pick the latest job from pool
# 1. Increase extranonce2
extranonce2 = job.increase_extranonce2()
# 2. Build final extranonce
extranonce = self.build_full_extranonce(extranonce2)
# 3. Put coinbase transaction together
coinbase_bin = job.build_coinbase(extranonce)
# 4. Calculate coinbase hash
coinbase_hash = utils.doublesha(coinbase_bin)
# 5. Calculate merkle root
merkle_root = binascii.hexlify(utils.reverse_hash(job.build_merkle_root(coinbase_hash)))
# 6. Generate current ntime
ntime = int(time.time()) + job.ntime_delta
# 7. Serialize header
block_header = job.serialize_header(merkle_root, ntime, 0)
# 8. Register job params
self.register_merkle(job, merkle_root, extranonce2)
# 9. Prepare hash1, calculate midstate and fill the response object
header_bin = binascii.unhexlify(block_header)[:64]
hash1 = "00000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000010000"
result = {'data': block_header,
'hash1': hash1}
if self.use_old_target:
result['target'] = 'ffffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000'
elif self.real_target:
result['target'] = self.target_hex
else:
result['target'] = self.target1_hex
if calculateMidstate and not (no_midstate or self.no_midstate):
# Midstate module not found or disabled
result['midstate'] = binascii.hexlify(calculateMidstate(header_bin))
return result
*/
public void close()
{
open=false;
try
{
sock.close();
}
catch(Throwable t){}
}
public long getNextRequestId()
{
return nextRequestId.getAndIncrement();
}
public void sendMessage(ObjectNode msg)
{
try
{
out_queue.put(msg);
}
catch(java.lang.InterruptedException e)
{
throw new RuntimeException(e);
}
}
/*
public void sendRealJob(ObjectNode block_template, boolean clean)
throws Exception
{
if (user_session_data == null) return;
if (!mining_subscribe) return;
String job_id = user_session_data.getNextJobId();
JobInfo ji = new JobInfo(server, user, job_id, block_template, extranonce1);
user_session_data.saveJobInfo(job_id, ji);
JSONObject msg = ji.getMiningNotifyMessage(clean);
sendMessage(msg);
}
*/
public class OutThread extends Thread
{
public OutThread()
{
setName("OutThread");
setDaemon(true);
}
public void run()
{
try
{
PrintStream out = new PrintStream(sock.getOutputStream());
while(open)
{
//Using poll rather than take so this thread will
//exit if the connection is closed. Otherwise,
//it would wait forever on this queue
ObjectNode msg = out_queue.poll(30, TimeUnit.SECONDS);
if (msg != null)
{
String msg_str = msg.toString();
out.println(msg_str);
out.flush();
if (DEBUG)
System.out.println("Out: " + msg.toString());
lastOutputNetworkAction.set(System.currentTimeMillis());
//updateLastNetworkAction();
}
}
}
catch(Exception e)
{
System.out.println( e.toString() );
e.printStackTrace();
}
finally
{
close();
}
}
}
public class InThread extends Thread
{
public InThread()
{
setName("InThread");
setDaemon(true);
}
public void run()
{
try
{
Scanner scan = new Scanner(sock.getInputStream());
while(open)
{
String line = scan.nextLine();
//updateLastNetworkAction();
lastInputNetworkAction.set(System.currentTimeMillis());
line = line.trim();
if (line.length() > 0)
{
ObjectNode msg = (ObjectNode) mapper.readTree(line);
if (DEBUG)
System.out.println("In: " + msg.toString());
try {
processInMessage(msg);
} catch (Exception ex) {
System.err.println(prefix + " exception in InThread: " + ex.toString());
}
}
}
}
catch(Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
finally
{
close();
}
}
}
public static class ServerWork implements Cloneable {
String jobId;
String hashPrevBlock;
String coinbasePart1;
String extraNonce1Str;
long extranonce2_size;
String coinbasePart2;
String [] merkleBranches;
String version;
String nBit;
String nTime;
boolean cleanJobs;
long difficulty;
long timestamp = System.currentTimeMillis();
//
String nonce;
String workerName;
//String extraNonce2Str;
//long extranonce1;
AtomicLong extranonce2 = new AtomicLong(0L);
long ntime_delta;
// for getwork
BigInteger target;
String target_hex;
String block_header;
String minerNtime;
@Override
public String toString() {
String mb = "";
for (int i = 0; i < merkleBranches.length; i++)
mb += "merkleBranches[" + i + "]=" + merkleBranches[i] + ";";
return "ServerWork{" + "jobId=" + jobId + ", hashPrevBlock=" + hashPrevBlock + ", coinbasePart1=" + coinbasePart1 +
", extraNonce1Str=" + extraNonce1Str + ", extranonce2_size=" + extranonce2_size + ", coinbasePart2=" + coinbasePart2 + ", merkleBranches=" + mb +
", version=" + version + ", nBit=" + nBit + ", nTime=" + nTime + ", cleanJobs=" + cleanJobs + ", difficulty=" + difficulty + ", timestamp=" + timestamp +
", nonce=" + nonce + ", workerName=" + workerName + //", extranonce1=" + extranonce1 +
", extranonce2=" + extranonce2 + ", ntime_delta=" + ntime_delta + ", target=" + target + ", target_hex=" + target_hex + ", block_header=" + block_header + '}';
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
private void doTests() throws NoSuchAlgorithmException, CloneNotSupportedException {
// 'mining.notify', u'ae6812eb4cd7735a302a8a9dd95cf71f'], u'f800003e', 4
this.extraNonce1Str = "f800003e";
this.extranonce2_size = 4;
this.difficulty = 256;
ServerWork newServerWork = new ServerWork();
newServerWork.jobId = "281c";
newServerWork.hashPrevBlock = "de68011079eef077f92c231a08cc08c411ced9d385f8d4c9adc961fc22c6c533";
newServerWork.coinbasePart1 = "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff27030cf700062f503253482f044a92fb5208";
newServerWork.coinbasePart2 = "0d2f7374726174756d506f6f6c2f000000000100adf4ca010000001976a914cc31a98aba0c51cd8f355e35adaa86011c0a2a4a88ac00000000";
newServerWork.merkleBranches = new String[0];
newServerWork.extraNonce1Str = this.extraNonce1Str;
newServerWork.extranonce2_size = this.extranonce2_size;
newServerWork.version = "00000002";
newServerWork.nBit = "1b01b269";
newServerWork.nTime = "52fb9247";
newServerWork.cleanJobs = false;
newServerWork.difficulty = this.difficulty;
long unixTime = System.currentTimeMillis() / 1000L;
newServerWork.ntime_delta = Long.parseLong(newServerWork.nTime, 16) - unixTime;
if (newServerWork.cleanJobs) {
if (DEBUG)
System.out.println("cleanJobs == true! cleaning work queue");
workQueue.clear();
}
workQueue.add(newServerWork);
/*
[u'281c',
u'de68011079eef077f92c231a08cc08c411ced9d385f8d4c9adc961fc22c6c533',
u'01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff27030cf700062f503253482f044a92fb5208',
u'0d2f7374726174756d506f6f6c2f000000000100adf4ca010000001976a914cc31a98aba0c51cd8f355e35adaa86011c0a2a4a88ac00000000',
[],
u'00000002',
u'1b01b269',
u'52fb9247',
False]
*
*
"data": "00000002bcc8c807468a23955657c90f74ba988d72b0762190f3bb7cb58b611d30a43570708b3f03aa00d5dcdbb4a874adbe748e218e80b120535605c86aa4efcc87d84152fb8e3e1b01b26900000000000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000",
"target": "0000000000000000000000000000000000000000000000000000ffff00000000"}
*
*/
ServerWork work = getWork();
setDifficulty(work, 256);
if (DEBUG) {
System.out.println(work);
System.out.println(work.target);
System.out.println(work.target_hex);
}
}
private void processInMessage(ObjectNode msg) {
//System.out.println(prefix + "processInMessage " + msg.toString());
// https://www.btcguild.com/new_protocol.php
long idx = msg.get("id").asLong();
JsonNode errorNode = msg.get("error");
JsonNode resultNode = msg.get("result");
String msgStr = msg.toString();
boolean debugthis = true;
if (msgStr.contains("\"mining.notify\"") && msgStr.contains("result")) {
if (debugthis || DEBUG)
System.out.println(prefix + "MESSAGE mining.notify (work subscription confirmation) " + msgStr);
// {"error":null,"id":6268754711428788574,"result":[["mining.notify","ae6812eb4cd7735a302a8a9dd95cf71f"],"f8000008",4]}
if (resultNode != null && resultNode instanceof ArrayNode) {
ArrayNode arrayNode = (ArrayNode) resultNode;
//System.out.println("len: " + arrayNode.size());
for (int i = 0; i < arrayNode.size(); i++) {
JsonNode node = arrayNode.get(i);
//System.out.println(i + " - " + node.toString());
if (node instanceof ArrayNode && node.toString().contains("mining.notify")) {
notifySubscription = ((ArrayNode) node).get(1).asText();
} else if (i == 1) {
extraNonce1Str = node.asText();
} else if (i == 2) {
extranonce2_size = node.asLong();
}
}
}
miningSubscribed = true;
if (DEBUG) {
System.out.println(prefix + "notifySubscription = " + notifySubscription);
System.out.println(prefix + "extraNonce1Str = " + extraNonce1Str);
System.out.println(prefix + "extranonce2_size = " + extranonce2_size);
System.out.println();
}
return;
} else if (msgStr.contains("\"mining.set_difficulty\"")) {
if (debugthis || DEBUG)
System.out.println(prefix + "MESSAGE mining.set_difficulty " + msgStr);
// {"params":[256],"id":null,"method":"mining.set_difficulty"}
ArrayNode paramsNode = (ArrayNode) msg.get("params");
long newDifficulty = paramsNode.get(0).asLong();
difficulty = newDifficulty;
if (DEBUG) {
System.out.println(prefix + "new difficulty: " + newDifficulty);
System.out.println();
}
return;
} else if (msgStr.contains("\"mining.notify\"") && msgStr.contains("params")) {
if (debugthis || DEBUG)
System.out.println(prefix + "MESSAGE mining.notify (work push) " + msgStr);
ArrayNode params = (ArrayNode) msg.get("params");
//{"params":[
// "178a",
// "ce2e706306028f9e215c14944c9369b229492e4d70ee2fe6759dae2fbef68114",
// "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff270398f100062f503253482f04454dfa5208",
// "0d2f7374726174756d506f6f6c2f000000000100b4f135010000001976a914cc31a98aba0c51cd8f355e35adaa86011c0a2a4a88ac00000000",
// [],
// "00000002",
// "1b01a0e9",
// "52fa4d3e",
// true],
// "id":null,"method":"mining.notify"}
ServerWork newServerWork = new ServerWork();
newServerWork.workerName = this.workerName;
//newServerWork.workerPassword = this.workerPassword;
newServerWork.jobId = params.get(0).asText();
newServerWork.hashPrevBlock = params.get(1).asText();
newServerWork.coinbasePart1 = params.get(2).asText();
newServerWork.coinbasePart2 = params.get(3).asText();
ArrayNode branches = (ArrayNode) params.get(4);
newServerWork.merkleBranches = new String[branches.size()];
for (int i = 0; i < branches.size(); i++)
newServerWork.merkleBranches[i] = branches.get(i).asText();
newServerWork.extraNonce1Str = this.extraNonce1Str;
newServerWork.extranonce2_size = this.extranonce2_size;
newServerWork.version = params.get(5).asText();
newServerWork.nBit = params.get(6).asText();
newServerWork.nTime = params.get(7).asText();
newServerWork.cleanJobs = params.get(8).asBoolean();
newServerWork.difficulty = this.difficulty;
long unixTime = System.currentTimeMillis() / 1000L;
newServerWork.ntime_delta = Long.parseLong(newServerWork.nTime, 16) - unixTime;
if (newServerWork.cleanJobs) {
if (true || DEBUG)
System.out.println(prefix + " cleanJobs == true! cleaning work queue");
StratumThread.getQueue().clear();
StratumThread.reset();
// also clear the list of acceptable jobs
okJobs.clear();
workQueue.clear();
}
if (!okJobs.contains(newServerWork.jobId))
okJobs.add(newServerWork.jobId);
workQueue.add(newServerWork);
if (DEBUG)
System.out.println(prefix + " workQueue size: " + workQueue.size() );
/*
params[0] = Job ID. This is included when miners submit a results so work can be matched with proper transactions.
params[1] = Hash of previous block. Used to build the header.
params[2] = Coinbase (part 1). The miner inserts ExtraNonce1 and ExtraNonce2 after this section of the coinbase.
params[3] = Coinbase (part 2). The miner appends this after the first part of the coinbase and the two ExtraNonce values.
params[4][] = List of merkle branches. The coinbase transaction is hashed against the merkle branches to build the final merkle root.
params[5] = Bitcoin block version, used in the block header.
params[6] = nBit, the encoded network difficulty. Used in the block header.
params[7] = nTime, the current time. nTime rolling should be supported, but should not increase faster than actual time.
params[8] = Clean Jobs. If true, miners should abort their current work and immediately use the new job. If false, they can still use the current job, but should move to the new one after exhausting the current nonce range.
*/
if (DEBUG) {
System.out.println(newServerWork.toString());
System.out.println();
}
return;
} else if (msgStr.contains("\"error\"") && msgStr.contains("\"result\"")) {
if (debugthis || DEBUG)
System.out.println(prefix + "MESSAGE result: " + msgStr);
lastOperationResult = msg.get("result").asBoolean();
if (debugthis || DEBUG) {
System.out.println(prefix + "result = " + lastOperationResult);
}
StratumResult result = new StratumResult();
result.id = msg.get("id").asLong();
result.error = msg.get("error").toString();
result.result = msg.get("result").asBoolean();
stratumResults.add(result);
if (debugthis || DEBUG) {
System.out.println(prefix + "complete result = " + result);
System.out.println(prefix + "stratumResults size: " + stratumResults.size());
System.out.println();
}
}
/*
Out: {"id":6268754711428788574,"method":"mining.subscribe","params":[]}
In: {"error":null,"id":6268754711428788574,"result":[["mining.notify","ae6812eb4cd7735a302a8a9dd95cf71f"],"f8000008",4]}
processInMessage
In: {"params":[256],"id":null,"method":"mining.set_difficulty"}
processInMessage
In: {"params":["1726","ba80e0721a236fca3b1ea994aca86fb5498d81ece49dd1b32ca2fc3c7295d80c","01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff27036bf100062f503253482f046843fa5208","0d2f7374726174756d506f6f6c2f00000000010001b2c4000000001976a914cc31a98aba0c51cd8f355e35adaa86011c0a2a4a88ac00000000",[],"00000002","1b01a0e9","52fa4361",true],"id":null,"method":"mining.notify"}
processInMessage
In: {"params":["1727","ba80e0721a236fca3b1ea994aca86fb5498d81ece49dd1b32ca2fc3c7295d80c","01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff27036bf100062f503253482f048643fa5208","0d2f7374726174756d506f6f6c2f00000000010001b2c4000000001976a914cc31a98aba0c51cd8f355e35adaa86011c0a2a4a88ac00000000",[],"00000002","1b01a0e9","52fa437f",false],"id":null,"method":"mining.notify"}
processInMessage
*/
}
public LinkedBlockingDeque<StratumResult> getStratumResults() {
return stratumResults;
}
/*
private void processInMessage(ObjectNode msg)
throws Exception
{
long idx = msg.optLong("id",-1);
if (idx != -1 && idx == get_client_id && msg.has("result"))
{
client_version = msg.getString("result");
return;
}
Object id = msg.opt("id");
if (!msg.has("method"))
{
System.out.println("Unknown message: " + msg.toString());
return;
}
String method = msg.getString("method");
if (method.equals("mining.subscribe"))
{
JSONObject reply = new JSONObject();
reply.put("id", id);
reply.put("error", JSONObject.NULL);
JSONArray lst2 = new JSONArray();
lst2.put("mining.notify");
lst2.put("hhtt");
JSONArray lst = new JSONArray();
lst.put(lst2);
lst.put(Hex.encodeHexString(extranonce1));
lst.put(4);
lst.put(RUNTIME_SESSION);
reply.put("result", lst);
sendMessage(reply);
mining_subscribe=true;
}
else if (method.equals("mining.authorize"))
{
JSONArray params = msg.getJSONArray("params");
String username = (String)params.get(0);
String password = (String)params.get(1);
PoolUser pu = server.getAuthHandler().authenticate(username, password);
JSONObject reply = new JSONObject();
reply.put("id", id);
if (pu==null)
{
reply.put("error", "unknown user");
reply.put("result", false);
sendMessage(reply);
}
else
{
reply.put("result", true);
reply.put("error", JSONObject.NULL);
//reply.put("difficulty", pu.getDifficulty());
//reply.put("user", pu.getName());
user = pu;
sendMessage(reply);
sendDifficulty();
sendGetClient();
user_session_data = server.getUserSessionData(pu);
sendRealJob(server.getCurrentBlockTemplate(),false);
}
}
else if (method.equals("mining.resume"))
{
JSONArray params = msg.getJSONArray("params");
String session_id = params.getString(0);
JSONObject reply = new JSONObject();
reply.put("id", id);
// should be the same as mining.subscribe
if (!session_id.equals(RUNTIME_SESSION))
{
reply.put("error", "bad session id");
reply.put("result", false);
sendMessage(reply);
}
else
{
reply.put("result", true);
reply.put("error", JSONObject.NULL);
sendMessage(reply);
mining_subscribe=true;
}
}
else if (method.equals("mining.submit"))
{
JSONArray params = msg.getJSONArray("params");
String job_id = params.getString(1);
JobInfo ji = user_session_data.getJobInfo(job_id);
if (ji == null)
{
JSONObject reply = new JSONObject();
reply.put("id", id);
reply.put("result", false);
reply.put("error", "unknown-work");
sendMessage(reply);
}
else
{
SubmitResult res = new SubmitResult();
res.client_version = client_version;
ji.validateSubmit(params,res);
JSONObject reply = new JSONObject();
reply.put("id", id);
if (res.our_result.equals("Y"))
{
reply.put("result", true);
}
else
{
reply.put("result", false);
}
if (res.reason==null)
{
reply.put("error", JSONObject.NULL);
}
else
{
reply.put("error", res.reason);
}
sendMessage(reply);
if ((res !=null) && (res.reason != null) && (res.reason.equals("H-not-zero")))
{
//User is not respecting difficulty, remind them
sendDifficulty();
}
}
}
}
private void sendDifficulty()
throws Exception
{
JSONObject msg = new JSONObject();
msg.put("id", JSONObject.NULL);
msg.put("method","mining.set_difficulty");
JSONArray lst = new JSONArray();
lst.put(user.getDifficulty());
msg.put("params", lst);
sendMessage(msg);
}
private void sendGetClient()
throws Exception
{
long id = getNextRequestId();
get_client_id = id;
JSONObject msg = new JSONObject();
msg.put("id", id);
msg.put("method","client.get_version");
sendMessage(msg);
}
*/
public boolean isOpen() {
return open;
}
public void setOpen(boolean open) {
this.open = open;
}
public String getExtraNonce1Str() {
return extraNonce1Str;
}
public void setExtraNonce1Str(String extraNonce1Str) {
this.extraNonce1Str = extraNonce1Str;
}
public long getExtranonce2_size() {
return extranonce2_size;
}
public void setExtranonce2_size(long extranonce2_size) {
this.extranonce2_size = extranonce2_size;
}
public long getDifficulty() {
return difficulty;
}
public void setDifficulty(long difficulty) {
this.difficulty = difficulty;
}
public long getLastOutputNetworkAction() {
return lastOutputNetworkAction.get();
}
public long getLastInputNetworkAction() {
return lastInputNetworkAction.get();
}
}
| |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @author max
*/
package com.intellij.psi.impl.source.tree;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.LogUtil;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.impl.DebugUtil;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.ILazyParseableElementType;
import com.intellij.util.text.CharArrayUtil;
import com.intellij.util.text.ImmutableCharSequence;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
public class LazyParseableElement extends CompositeElement {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.LazyParseableElement");
private static class ChameleonLock {
private ChameleonLock() {}
@NonNls
@Override
public String toString() {
return "chameleon parsing lock";
}
}
// Lock which protects expanding chameleon for this node.
// Under no circumstances should you grab the PSI_LOCK while holding this lock.
private final ChameleonLock lock = new ChameleonLock();
/** guarded by {@link #lock} */
private CharSequence myText;
private static final ThreadLocal<Boolean> ourSuppressEagerPsiCreation = new ThreadLocal<Boolean>();
public LazyParseableElement(@NotNull IElementType type, @Nullable CharSequence text) {
super(type);
if (text != null) {
synchronized (lock) {
myText = ImmutableCharSequence.asImmutable(text);
}
setCachedLength(text.length());
}
}
@Override
public void clearCaches() {
super.clearCaches();
synchronized (lock) {
if (myText != null) {
setCachedLength(myText.length());
}
}
}
public void chameleonBack() {
ApplicationManager.getApplication().assertReadAccessAllowed();
DebugUtil.startPsiModification("chameleon-back");
try {
synchronized (lock) {
if (myText == null) {
String text = super.getText();
TreeElement node = rawFirstChild();
if (node != null) {
node.rawRemoveUpToWithoutNotifications(null, true);
}
myText = text;
setCachedLength(myText.length());
}
}
}
finally {
DebugUtil.finishPsiModification();
}
}
@NotNull
@Override
public String getText() {
CharSequence text = myText();
if (text != null) {
return text.toString();
}
return super.getText();
}
@Override
@NotNull
public CharSequence getChars() {
CharSequence text = myText();
if (text != null) {
return text;
}
return super.getText();
}
@Override
public int getTextLength() {
CharSequence text = myText();
if (text != null) {
return text.length();
}
return super.getTextLength();
}
@Override
public int getNotCachedLength() {
CharSequence text = myText();
if (text != null) {
return text.length();
}
return super.getNotCachedLength();
}
@Override
public int hc() {
CharSequence text = myText();
return text == null ? super.hc() : LeafElement.leafHC(text);
}
@Override
protected int textMatches(@NotNull CharSequence buffer, int start) {
CharSequence text = myText();
if (text != null) {
return LeafElement.leafTextMatches(text, buffer, start);
}
return super.textMatches(buffer, start);
}
public boolean isParsed() {
return myText() == null;
}
private CharSequence myText() {
synchronized (lock) {
return myText;
}
}
@Override
final void setFirstChildNode(TreeElement child) {
if (myText() != null) {
LOG.error("Mutating collapsed chameleon");
}
super.setFirstChildNode(child);
}
@Override
final void setLastChildNode(TreeElement child) {
if (myText() != null) {
LOG.error("Mutating collapsed chameleon");
}
super.setLastChildNode(child);
}
private void ensureParsed() {
if (!ourParsingAllowed) {
LOG.error("Parsing not allowed!!!");
}
CharSequence text = myText();
if (text == null) return;
if (TreeUtil.getFileElement(this) == null) {
LOG.error("Chameleons must not be parsed till they're in file tree: " + this);
}
ApplicationManager.getApplication().assertReadAccessAllowed();
DebugUtil.startPsiModification("lazy-parsing");
try {
ILazyParseableElementType type = (ILazyParseableElementType)getElementType();
ASTNode parsedNode = type.parseContents(this);
if (parsedNode == null && text.length() > 0) {
CharSequence diagText = ApplicationManager.getApplication().isInternal() ? text : "";
LOG.error("No parse for a non-empty string: " + diagText + "; type=" + LogUtil.objectAndClass(type));
}
synchronized (lock) {
if (myText == null) return;
if (rawFirstChild() != null) {
LOG.error("Reentrant parsing?");
}
myText = null;
if (parsedNode == null) return;
super.rawAddChildrenWithoutNotifications((TreeElement)parsedNode);
}
}
finally {
DebugUtil.finishPsiModification();
}
if (!Boolean.TRUE.equals(ourSuppressEagerPsiCreation.get())) {
// create PSI all at once, to reduce contention of PsiLock in CompositeElement.getPsi()
// create PSI outside the 'lock' since this method grabs PSI_LOCK and deadlock is possible when someone else locks in the other order.
createAllChildrenPsiIfNecessary();
}
}
@Override
public void rawAddChildrenWithoutNotifications(@NotNull TreeElement first) {
if (myText() != null) {
LOG.error("Mutating collapsed chameleon");
}
super.rawAddChildrenWithoutNotifications(first);
}
@Override
public TreeElement getFirstChildNode() {
ensureParsed();
return super.getFirstChildNode();
}
@Override
public TreeElement getLastChildNode() {
ensureParsed();
return super.getLastChildNode();
}
public int copyTo(@Nullable char[] buffer, int start) {
CharSequence text = myText();
if (text == null) return -1;
if (buffer != null) {
CharArrayUtil.getChars(text, buffer, start);
}
return start + text.length();
}
private static boolean ourParsingAllowed = true;
@TestOnly
public static void setParsingAllowed(boolean allowed) {
ourParsingAllowed = allowed;
}
public static void setSuppressEagerPsiCreation(boolean suppress) {
ourSuppressEagerPsiCreation.set(suppress);
}
}
| |
/*******************************************************************************
* 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.ofbiz.content.output;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttribute;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.HashPrintServiceAttributeSet;
import javax.print.attribute.PrintRequestAttribute;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.PrintServiceAttributeSet;
import javax.print.attribute.standard.PrinterName;
import javax.xml.transform.stream.StreamSource;
import javolution.util.FastMap;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.MimeConstants;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.collections.MapStack;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.webapp.view.ApacheFopWorker;
import org.ofbiz.widget.fo.FoFormRenderer;
import org.ofbiz.widget.fo.FoScreenRenderer;
import org.ofbiz.widget.screen.ScreenRenderer;
/**
* Output Services
*/
public class OutputServices {
public final static String module = OutputServices.class.getName();
protected static final FoScreenRenderer foScreenRenderer = new FoScreenRenderer();
protected static final FoFormRenderer foFormRenderer = new FoFormRenderer();
public static final String resource = "ContentUiLabels";
public static Map<String, Object> sendPrintFromScreen(DispatchContext dctx, Map<String, ? extends Object> serviceContext) {
Locale locale = (Locale) serviceContext.get("locale");
String screenLocation = (String) serviceContext.remove("screenLocation");
Map<String, Object> screenContext = UtilGenerics.checkMap(serviceContext.remove("screenContext"));
String contentType = (String) serviceContext.remove("contentType");
String printerContentType = (String) serviceContext.remove("printerContentType");
if (UtilValidate.isEmpty(screenContext)) {
screenContext = FastMap.newInstance();
}
screenContext.put("locale", locale);
if (UtilValidate.isEmpty(contentType)) {
contentType = "application/postscript";
}
if (UtilValidate.isEmpty(printerContentType)) {
printerContentType = contentType;
}
try {
MapStack<String> screenContextTmp = MapStack.create();
screenContextTmp.put("locale", locale);
Writer writer = new StringWriter();
// substitute the freemarker variables...
ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContextTmp, foScreenRenderer);
screensAtt.populateContextForService(dctx, screenContext);
screenContextTmp.putAll(screenContext);
screensAtt.getContext().put("formStringRenderer", foFormRenderer);
screensAtt.render(screenLocation);
// create the input stream for the generation
StreamSource src = new StreamSource(new StringReader(writer.toString()));
// create the output stream for the generation
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
ApacheFopWorker.transform(src, null, fop);
baos.flush();
baos.close();
// Print is sent
DocFlavor psInFormat = new DocFlavor.INPUT_STREAM(printerContentType);
InputStream bais = new ByteArrayInputStream(baos.toByteArray());
DocAttributeSet docAttributeSet = new HashDocAttributeSet();
List<Object> docAttributes = UtilGenerics.checkList(serviceContext.remove("docAttributes"));
if (UtilValidate.isNotEmpty(docAttributes)) {
for (Object da : docAttributes) {
Debug.logInfo("Adding DocAttribute: " + da, module);
docAttributeSet.add((DocAttribute) da);
}
}
Doc myDoc = new SimpleDoc(bais, psInFormat, docAttributeSet);
PrintService printer = null;
// lookup the print service for the supplied printer name
String printerName = (String) serviceContext.remove("printerName");
if (UtilValidate.isNotEmpty(printerName)) {
PrintServiceAttributeSet printServiceAttributes = new HashPrintServiceAttributeSet();
printServiceAttributes.add(new PrinterName(printerName, locale));
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, printServiceAttributes);
if (printServices.length > 0) {
printer = printServices[0];
Debug.logInfo("Using printer: " + printer.getName(), module);
if (!printer.isDocFlavorSupported(psInFormat)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotSupportDocFlavorFormat", UtilMisc.toMap("psInFormat", psInFormat, "printerName", printer.getName()), locale));
}
}
if (printer == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotFound", UtilMisc.toMap("printerName", printerName), locale));
}
} else {
// if no printer name was supplied, try to get the default printer
printer = PrintServiceLookup.lookupDefaultPrintService();
if (printer != null) {
Debug.logInfo("No printer name supplied, using default printer: " + printer.getName(), module);
}
}
if (printer == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotAvailable", locale));
}
PrintRequestAttributeSet praset = new HashPrintRequestAttributeSet();
List<Object> printRequestAttributes = UtilGenerics.checkList(serviceContext.remove("printRequestAttributes"));
if (UtilValidate.isNotEmpty(printRequestAttributes)) {
for (Object pra : printRequestAttributes) {
Debug.logInfo("Adding PrintRequestAttribute: " + pra, module);
praset.add((PrintRequestAttribute) pra);
}
}
DocPrintJob job = printer.createPrintJob();
job.print(myDoc, praset);
} catch (Exception e) {
Debug.logError(e, "Error rendering [" + contentType + "]: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentRenderingError", UtilMisc.toMap("contentType", contentType, "errorString", e.toString()), locale));
}
return ServiceUtil.returnSuccess();
}
public static Map<String, Object> createFileFromScreen(DispatchContext dctx, Map<String, ? extends Object> serviceContext) {
Locale locale = (Locale) serviceContext.get("locale");
String screenLocation = (String) serviceContext.remove("screenLocation");
Map<String, Object> screenContext = UtilGenerics.checkMap(serviceContext.remove("screenContext"));
String contentType = (String) serviceContext.remove("contentType");
String filePath = (String) serviceContext.remove("filePath");
String fileName = (String) serviceContext.remove("fileName");
if (UtilValidate.isEmpty(screenContext)) {
screenContext = FastMap.newInstance();
}
screenContext.put("locale", locale);
if (UtilValidate.isEmpty(contentType)) {
contentType = "application/pdf";
}
try {
MapStack<String> screenContextTmp = MapStack.create();
screenContextTmp.put("locale", locale);
Writer writer = new StringWriter();
// substitute the freemarker variables...
ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContextTmp, foScreenRenderer);
screensAtt.populateContextForService(dctx, screenContext);
screenContextTmp.putAll(screenContext);
screensAtt.getContext().put("formStringRenderer", foFormRenderer);
screensAtt.render(screenLocation);
// create the input stream for the generation
StreamSource src = new StreamSource(new StringReader(writer.toString()));
// create the output stream for the generation
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
ApacheFopWorker.transform(src, null, fop);
baos.flush();
baos.close();
fileName += UtilDateTime.nowAsString();
if ("application/pdf".equals(contentType)) {
fileName += ".pdf";
} else if ("application/postscript".equals(contentType)) {
fileName += ".ps";
} else if ("text/plain".equals(contentType)) {
fileName += ".txt";
}
if (UtilValidate.isEmpty(filePath)) {
filePath = UtilProperties.getPropertyValue("content.properties", "content.output.path", "/output");
}
File file = new File(filePath, fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.close();
} catch (Exception e) {
Debug.logError(e, "Error rendering [" + contentType + "]: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentRenderingError", UtilMisc.toMap("contentType", contentType, "errorString", e.toString()), locale));
}
return ServiceUtil.returnSuccess();
}
}
| |
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Java API Library
*
* Copyright (c) 2020 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
package com.adyen.model.marketpay;
import com.fasterxml.jackson.annotation.JsonValue;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import static com.adyen.util.Util.toIndentedString;
/**
* UpdateAccountHolderRequest
*/
public class UpdateAccountHolderRequest {
@SerializedName("accountHolderCode")
private String accountHolderCode = null;
@SerializedName("accountHolderDetails")
private AccountHolderDetails accountHolderDetails = null;
@SerializedName("description")
private String description = null;
/**
* The entity type. Permitted values: `Business`, `Individual` If an account holder is 'Business', then `accountHolderDetails.businessDetails` must be provided, as well as at least one entry in the `accountHolderDetails.businessDetails.shareholders` list. If an account holder is 'Individual', then `accountHolderDetails.individualDetails` must be provided.
*/
@JsonAdapter(LegalEntityEnum.Adapter.class)
public enum LegalEntityEnum {
BUSINESS("Business"),
INDIVIDUAL("Individual"),
NONPROFIT("NonProfit"),
PUBLICCOMPANY("PublicCompany");
@JsonValue
private String value;
LegalEntityEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static LegalEntityEnum fromValue(String text) {
return Arrays.stream(values()).
filter(s -> s.value.equals(text)).
findFirst().orElse(null);
}
public static class Adapter extends TypeAdapter<LegalEntityEnum> {
@Override
public void write(final JsonWriter jsonWriter, final LegalEntityEnum enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public LegalEntityEnum read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return LegalEntityEnum.fromValue(String.valueOf(value));
}
}
}
@SerializedName("legalEntity")
private LegalEntityEnum legalEntity = null;
@SerializedName("primaryCurrency")
private String primaryCurrency = null;
@SerializedName("processingTier")
private Integer processingTier = null;
@SerializedName("verificationProfile")
private String verificationProfile = null;
public UpdateAccountHolderRequest accountHolderCode(String accountHolderCode) {
this.accountHolderCode = accountHolderCode;
return this;
}
/**
* The code of the Account Holder to be updated.
*
* @return accountHolderCode
**/
public String getAccountHolderCode() {
return accountHolderCode;
}
public void setAccountHolderCode(String accountHolderCode) {
this.accountHolderCode = accountHolderCode;
}
public UpdateAccountHolderRequest accountHolderDetails(AccountHolderDetails accountHolderDetails) {
this.accountHolderDetails = accountHolderDetails;
return this;
}
/**
* Get accountHolderDetails
*
* @return accountHolderDetails
**/
public AccountHolderDetails getAccountHolderDetails() {
return accountHolderDetails;
}
public void setAccountHolderDetails(AccountHolderDetails accountHolderDetails) {
this.accountHolderDetails = accountHolderDetails;
}
public UpdateAccountHolderRequest description(String description) {
this.description = description;
return this;
}
/**
* The description to which the Account Holder should be updated.
*
* @return description
**/
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public UpdateAccountHolderRequest legalEntity(LegalEntityEnum legalEntity) {
this.legalEntity = legalEntity;
return this;
}
/**
* The entity type. Permitted values: `Business`, `Individual` If an account holder is 'Business', then `accountHolderDetails.businessDetails` must be provided, as well as at least one entry in the `accountHolderDetails.businessDetails.shareholders` list. If an account holder is 'Individual', then `accountHolderDetails.individualDetails` must be provided.
*
* @return legalEntity
**/
public LegalEntityEnum getLegalEntity() {
return legalEntity;
}
public void setLegalEntity(LegalEntityEnum legalEntity) {
this.legalEntity = legalEntity;
}
public UpdateAccountHolderRequest primaryCurrency(String primaryCurrency) {
this.primaryCurrency = primaryCurrency;
return this;
}
/**
* The primary three-character [ISO currency code](https://docs.adyen.com/development-resources/currency-codes), to which the account holder should be updated.
*
* @return primaryCurrency
**/
public String getPrimaryCurrency() {
return primaryCurrency;
}
public void setPrimaryCurrency(String primaryCurrency) {
this.primaryCurrency = primaryCurrency;
}
public UpdateAccountHolderRequest processingTier(Integer processingTier) {
this.processingTier = processingTier;
return this;
}
/**
* The processing tier to which the Account Holder should be updated. >The processing tier can not be lowered through this request. >Required if accountHolderDetails are not provided.
*
* @return processingTier
**/
public Integer getProcessingTier() {
return processingTier;
}
public void setProcessingTier(Integer processingTier) {
this.processingTier = processingTier;
}
public UpdateAccountHolderRequest verificationProfile(String verificationProfile) {
this.verificationProfile = verificationProfile;
return this;
}
/**
* The identifier of the profile that applies to this entity
*
* @return verificationProfile
*/
public String getVerificationProfile() {
return verificationProfile;
}
public void setVerificationProfile(String verificationProfile) {
this.verificationProfile = verificationProfile;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UpdateAccountHolderRequest updateAccountHolderRequest = (UpdateAccountHolderRequest) o;
return Objects.equals(this.accountHolderCode, updateAccountHolderRequest.accountHolderCode) &&
Objects.equals(this.accountHolderDetails, updateAccountHolderRequest.accountHolderDetails) &&
Objects.equals(this.description, updateAccountHolderRequest.description) &&
Objects.equals(this.legalEntity, updateAccountHolderRequest.legalEntity) &&
Objects.equals(this.primaryCurrency, updateAccountHolderRequest.primaryCurrency) &&
Objects.equals(this.processingTier, updateAccountHolderRequest.processingTier) &&
Objects.equals(this.verificationProfile, updateAccountHolderRequest.verificationProfile);
}
@Override
public int hashCode() {
return Objects.hash(accountHolderCode, accountHolderDetails, description, legalEntity, primaryCurrency, processingTier, verificationProfile);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class UpdateAccountHolderRequest {\n");
sb.append(" accountHolderCode: ").append(toIndentedString(accountHolderCode)).append("\n");
sb.append(" accountHolderDetails: ").append(toIndentedString(accountHolderDetails)).append("\n");
sb.append(" description: ").append(toIndentedString(description)).append("\n");
sb.append(" legalEntity: ").append(toIndentedString(legalEntity)).append("\n");
sb.append(" primaryCurrency: ").append(toIndentedString(primaryCurrency)).append("\n");
sb.append(" processingTier: ").append(toIndentedString(processingTier)).append("\n");
sb.append(" verificationProfile: ").append(toIndentedString(verificationProfile)).append("\n");
sb.append("}");
return sb.toString();
}
}
| |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package otelo.Hexagonal;
import java.util.ArrayList;
/**
*
* @author cliente
*/
public class OthelloHexagonal{
private int tamTab;
private int[][] MatTab; //Si MatTab ij {-1,0,1}; -1:negro; 0:vacio; 1:blanco
private int[][] MatPesos; //Matriz de pesos de ubicacion
private int turno; //fichas (b/n) (-1/1)
private int nivel1; //define tipo nivel de jug 1
private int nivel2; //define tipo nivel de jug 2
private Jugador jug1;
private Jugador jug2;
// <editor-fold defaultstate="collapsed" desc="VARIABLES ESTATICAS">
// <editor-fold defaultstate="collapsed" desc="Estados de casilleros /turnos">
public static int FICHA_BLANCA = 1;
public static int VACIO = 0;
public static int FICHA_NEGRA = -1;
public static int FICHA_POSIBLE = -2;
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Tipos de juego">
public static int HUMANO = 0;
public static int FACIL = 1;
public static int MEDIO = 2;
public static int EXPERTO = 3;
public static int NO_MAQUINAS = 100;
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Pesos de Criterios">
private static float CRIT_PESO_POSICION = 0.65f;
private static float CRIT_FICHAS_INVERTIDAS = 0.35f;
// </editor-fold>
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Representacion de tablero (tam=6)">
/*
* Grafico de la matriz de hexagonos
* XXXX000000 |
* XXX0000000 |
* XX00000000 |
* X000000000 |
* 0000000000 |> 2n-2
* 0000000000 |>
* 000000000X |
* 00000000XX |
* 0000000XXX |
* 000000XXXX |
* donde: X es posicion no valida
* 0 es posicion valida
*/
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Constructor de OTHELLOHEXAGONAL">
public OthelloHexagonal(int tamTab, int jugador1, int jugador2) {
this.tamTab = tamTab;
this.nivel1 = jugador2;
if (jugador1 == Jugador.HUMANO)
jug1 = new Jugador(Jugador.FIC_BLA, Jugador.HUMANO);
else{
nivel1 = jugador1;
jug1 = new Jugador(Jugador.FIC_BLA, Jugador.MAQUINA);
}
if (jugador2 == Jugador.HUMANO)
jug2 = new Jugador(Jugador.FIC_NEG, Jugador.HUMANO);
else{
nivel2 = jugador2;
jug2 = new Jugador(Jugador.FIC_NEG, Jugador.MAQUINA);
}
turno = 1;
iniciarTablero();
iniciarPesos();
}
// </editor-fold>
public void mt(){
for(int i=0;i<MatTab.length;i++){
for(int j=0;j<MatTab[0].length;j++)
System.out.print(MatTab[i][j]+"\t");
System.out.println("");
}
}
public void mp(){
for(int i=0;i<MatPesos.length;i++){
for(int j=0;j<MatPesos[0].length;j++)
System.out.print(MatPesos[i][j]+"\t");
System.out.println("");
}
}
// <editor-fold defaultstate="collapsed" desc="Estado Inicial">
private void iniciarTablero(){
MatTab = new int[2*(tamTab-1)][2*(tamTab-1)];
for(int i=0;i<MatTab.length;i++)
for(int j=0;j<MatTab[0].length;j++)
MatTab[i][j] = 0;
MatTab[tamTab-2][tamTab-2] = MatTab[tamTab-1][tamTab-1]= 1;
MatTab[tamTab-1][tamTab-2] = MatTab[tamTab-2][tamTab-1]= -1;
}
private void iniciarPesos(){
MatPesos = new int[2*(tamTab-1)][2*(tamTab-1)];
for(int i=0;i<MatPesos.length;i++){
for(int j=0;j<MatPesos[0].length;j++){
if(tamTab-2<=i+j && i+j<=3*tamTab-4){
double difX = Math.abs(i-tamTab+1.5);
double difY = Math.abs(j-tamTab+1.5);
MatPesos[i][j] = 2*(int)Math.sqrt(Math.pow(difX,2) + Math.pow(difY,2));
if(((int)Math.abs(j-i))==(2*tamTab-4))
MatPesos[i][j] = -tamTab/2;
if((i==tamTab-1 && j==0) || (j==tamTab-1 && i==0))
MatPesos[i][j] = -tamTab/2;
if((i==tamTab-3 && j==1) || (j==tamTab-3 && i==1))
MatPesos[i][j] = -tamTab/2;
if((i==tamTab-2 && j==MatPesos[0].length-1) || (j==tamTab-2 && i==MatPesos[0].length-1))
MatPesos[i][j] = -tamTab/2;
if((i==tamTab && j==MatPesos[0].length-2) || (j==tamTab && i==MatPesos[0].length-2))
MatPesos[i][j] = -tamTab/2;
if((i==tamTab-2 && j==1) || (j==tamTab-2 && i==1))
MatPesos[i][j] = -tamTab/2;
if((i==MatPesos[0].length-2 && j==tamTab-1) || (j==MatPesos[0].length-2 && i==tamTab-1))
MatPesos[i][j] = -tamTab/2;
if((i==MatPesos[0].length-2 && j==1) || (j==MatPesos[0].length-2 && i==1))
MatPesos[i][j] = -tamTab/2;
}else
MatPesos[i][j] = 0;
}
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Contadores de fichas">
public int cantB(){
int cant = 0;
for(int i=0;i<MatTab.length;i++)
for(int j=0;j<MatTab[0].length;j++)
if(tamTab-2<=i+j && i+j<=3*tamTab-4)
if(MatTab[i][j]==FICHA_BLANCA)
cant++;
return cant;
}
public int cantN(){
int cant = 0;
for(int i=0;i<MatTab.length;i++)
for(int j=0;j<MatTab[0].length;j++)
if(tamTab-2<=i+j && i+j<=3*tamTab-4)
if(MatTab[i][j]==FICHA_NEGRA)
cant++;
return cant;
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Verificadores de jugadas validas">
private boolean verificarDiagonalInferior(int x, int y,int turno, int [][] MatJug){
int limiteInferior;
if (y<tamTab-2)
limiteInferior = 2*tamTab-3;
else
limiteInferior = 3*tamTab-4-y;
boolean cont = true;
int i = x+1;
int ultimaficha = MatJug[x][y];
if(ultimaficha != VACIO)
return false;
while(cont && i<limiteInferior){
if(MatJug[i][y]==VACIO || MatJug[i][y]==turno)
cont = false;
else if (MatJug[i][y]==(-turno)){
ultimaficha = MatJug[i][y]; i++;
}
}
try{
if (ultimaficha == (-turno) && MatJug[i][y] == turno)
return true;
else
return false;
}catch(ArrayIndexOutOfBoundsException ae){
return false;
}
}
private boolean verificarDiagonalSuperior(int x, int y, int turno, int [][] MatJug){
int limiteSuperior;
if (y<tamTab-2)
limiteSuperior = tamTab-3-y;
else
limiteSuperior = 0;
boolean cont = true;
int i = x-1;
int ultimaficha = MatJug[x][y];
if(ultimaficha != VACIO)
return false;
while(cont && i >=limiteSuperior){
if(MatJug[i][y]==VACIO || MatJug[i][y]==turno)
cont = false;
else if (MatJug[i][y]==(-turno)){
ultimaficha = MatJug[i][y]; i--;
}
}
try{
if (ultimaficha == (-turno) && MatJug[i][y] == turno)
return true;
else
return false;
}catch(ArrayIndexOutOfBoundsException ae){
return false;
}
}
private boolean verificarContraDiagonalInferior(int x, int y, int turno, int [][] MatJug){
int limiteSuperior;
if (x<tamTab-2)
limiteSuperior = tamTab-3-x;
else
limiteSuperior = 0;
boolean cont = true;
int j = y-1;
int ultimaficha = MatJug[x][y];
if(ultimaficha != VACIO)
return false;
while(cont && j >=limiteSuperior){
if(MatJug[x][j]==VACIO || MatJug[x][j]==turno)
cont = false;
else if (MatJug[x][j]==(-turno)){
ultimaficha = MatJug[x][j]; j--;
}
}
try{
if (ultimaficha == (-turno) && MatJug[x][j] == turno)
return true;
else
return false;
}catch(ArrayIndexOutOfBoundsException ae){
return false;
}
}
private boolean verificarContraDiagonalSuperior(int x, int y,int turno, int [][] MatJug){
int limiteInferior;
if (x<tamTab-2)
limiteInferior = 2*tamTab-3;
else
limiteInferior = 3*tamTab-4-x;
boolean cont = true;
int j = y+1;
int ultimaficha = MatJug[x][y];
if(ultimaficha != VACIO)
return false;
while(cont && j <limiteInferior){
if(MatJug[x][j]==VACIO || MatJug[x][j]==turno)
cont = false;
else if (MatJug[x][j]==(-turno)){
ultimaficha = MatJug[x][j]; j++;
}
}
try{
if (ultimaficha == (-turno) && MatJug[x][j] == turno)
return true;
else
return false;
}catch(ArrayIndexOutOfBoundsException ae){
return false;
}
}
private boolean verificarVerticalInferior(int x, int y,int turno, int [][] MatJug){
boolean cont = true;
int i = x - 1;
int j = y + 1;
int ultimaficha = MatJug[x][y];
if(ultimaficha != VACIO)
return false;
while(cont && i>=0 && j<2*tamTab-2){
if(MatJug[i][j] == VACIO || MatJug[i][j] == turno)
cont = false;
else if (MatJug[i][j]==(-turno)){
ultimaficha = MatJug[i][j]; i--; j++;
}
}
try{
if (ultimaficha == (-turno) && MatJug[i][j] == turno)
return true;
else
return false;
}catch(ArrayIndexOutOfBoundsException ae){
return false;
}
}
private boolean verificarVerticalSuperior(int x, int y, int turno, int [][] MatJug){
boolean cont = true;
int i = x + 1;
int j = y - 1;
int ultimaficha = MatJug[x][y];
if(ultimaficha != VACIO)
return false;
while(cont && 2*tamTab-2>i && j>=0){
if(MatJug[i][j] == VACIO || MatJug[i][j] == turno)
cont = false;
else if (MatJug[i][j]==(-turno)){
ultimaficha = MatJug[i][j]; i++; j--;
}
}
try{
if (ultimaficha == (-turno) && MatJug[i][j] == turno)
return true;
else
return false;
}catch(ArrayIndexOutOfBoundsException ae){
return false;
}
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Realizadores de nuevo estado">
public int cambiarFichasDiagonalInferior(int x, int y, int turno, int[][] MatJug){
int i = x+1;
int cont = 0;
while(MatJug[i][y]!=turno){
MatJug[i][y] = turno;
i++;
cont++;
}
return cont;
}
public int cambiarFichasDiagonalSuperior(int x, int y, int turno, int[][] MatJug){
int i = x-1;
int cont = 0;
while(MatJug[i][y]!=turno){
MatJug[i][y] = turno;
cont++;
i--;
}
return cont;
}
public int cambiarFichasContraDiagonalInferior(int x, int y, int turno, int[][] MatJug){
int j = y-1;
int cont = 0;
while(MatJug[x][j]!=turno){
MatJug[x][j] = turno;
j--;
cont++;
}
return cont;
}
public int cambiarFichasContraDiagonalSuperior(int x, int y, int turno, int[][] MatJug){
int j = y+1;
int cont = 0;
while(MatJug[x][j]!=turno){
MatJug[x][j] = turno;
j++;
cont++;
}
return cont;
}
public int cambiarFichasVerticalInferior(int x, int y, int turno, int[][] MatJug){
int inc = 1;
int cont = 0;
while(MatJug[x-inc][y+inc]!=turno){
MatJug[x-inc][y+inc] = turno;
inc++;
cont++;
}
return cont;
}
public int cambiarFichasVerticalSuperior(int x, int y, int turno, int[][] MatJug){
int inc = 1;
int cont = 0;
while(MatJug[x+inc][y-inc]!=turno){
MatJug[x+inc][y-inc] = turno;
inc++;
cont++;
}
return cont;
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Movimientos del juego">
public void colocarFichaBlanca(int x, int y){
if(tamTab-2<=x+y && x+y<=3*tamTab-4){//si esta dentro del tablero
if(MatTab[x][y] == 0){//si la posicion esta vacia
boolean res = false;
int cont = 0;
if(verificarDiagonalInferior(x, y, FICHA_BLANCA,MatTab)){
cont+=cambiarFichasDiagonalInferior(x, y, FICHA_BLANCA, MatTab);
res = true;
}
if(verificarDiagonalSuperior(x, y, FICHA_BLANCA,MatTab)){
cont+=cambiarFichasDiagonalSuperior(x, y, FICHA_BLANCA, MatTab);
res = true;
}
if(verificarContraDiagonalInferior(x, y, FICHA_BLANCA,MatTab)){
cont+=cambiarFichasContraDiagonalInferior(x, y, FICHA_BLANCA, MatTab);
res = true;
}
if(verificarContraDiagonalSuperior(x, y, FICHA_BLANCA,MatTab)){
cont+=cambiarFichasContraDiagonalSuperior(x, y, FICHA_BLANCA, MatTab);
res = true;
}
if(verificarVerticalInferior(x, y, FICHA_BLANCA,MatTab)){
cont+=cambiarFichasVerticalInferior(x, y, FICHA_BLANCA, MatTab);
res = true;
}
if(verificarVerticalSuperior(x, y, FICHA_BLANCA,MatTab)){
cont+=cambiarFichasVerticalSuperior(x, y, FICHA_BLANCA, MatTab);
res = true;
}
if(res){
MatTab[x][y] = FICHA_BLANCA;
turno = FICHA_NEGRA;
System.out.println("Se cambiaron :"+cont+" fichas");
}else
System.out.println("no se ingreso ficha");
}else
System.out.println("movimiento invalido");
}else
System.out.println("valor de x,y "+MatTab[x][y]);
}
public void colocarFichaNegra(int x, int y){
if(tamTab-2<=x+y && x+y<=3*tamTab-4){//si esta dentro del tablero
if(MatTab[x][y]==0){//si la posicion esta vacia
boolean res = false;
int cont = 0;
if(verificarDiagonalInferior(x, y, FICHA_NEGRA,MatTab)){
cont+=cambiarFichasDiagonalInferior(x, y, FICHA_NEGRA, MatTab);
res = true;
}
if(verificarDiagonalSuperior(x, y, FICHA_NEGRA,MatTab)){
cont+=cambiarFichasDiagonalSuperior(x, y, FICHA_NEGRA, MatTab);
res = true;
}
if(verificarContraDiagonalInferior(x, y, FICHA_NEGRA,MatTab)){
cont+=cambiarFichasContraDiagonalInferior(x, y, FICHA_NEGRA, MatTab);
res = true;
}
if(verificarContraDiagonalSuperior(x, y, FICHA_NEGRA,MatTab)){
cont+=cambiarFichasContraDiagonalSuperior(x, y, FICHA_NEGRA, MatTab);
res = true;
}
if(verificarVerticalInferior(x, y, FICHA_NEGRA,MatTab)){
cont+=cambiarFichasVerticalInferior(x, y, FICHA_NEGRA, MatTab);
res = true;
}
if(verificarVerticalSuperior(x, y, FICHA_NEGRA,MatTab)){
cont+=cambiarFichasVerticalSuperior(x, y, FICHA_NEGRA, MatTab);
res = true;
}
System.out.println("valor de x,y "+MatTab[x][y]);
if(res){
MatTab[x][y] = FICHA_NEGRA;
turno = FICHA_BLANCA;
System.out.println("Se cambiaron "+cont+" fichas");
}else
System.out.println("no se inngreso ficha");
}else
System.out.println("movimiento invalido");
}else
System.out.println("valor de x,y "+MatTab[x][y]);
}// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Condiciones de estado meta">
public boolean isFin(){
int cantFich = cantB() + cantN();
ArrayList<Integer> jugs = buscarJugadasPosibles(turno,MatTab).get(0);
if(cantFich == (tamTab-1)*(3*tamTab-2) || jugs.size() == 0){//cant == (otheHex.getTamTab()-1)*(3*otheHex.getTamTab()-2)
return true;
}
return false;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Busqueda de jugadas Posibles">
public ArrayList <ArrayList <Integer>> buscarJugPos(int turnoFich, int[][] MatTab){
return buscarJugadasPosibles(turnoFich, MatTab);
}
private ArrayList <ArrayList <Integer>> buscarJugadasPosibles(int turnoFich,int[][] MatEstAct){
ArrayList <ArrayList <Integer>> listJug = new ArrayList<ArrayList<Integer>>();
ArrayList <Integer> xs = new ArrayList<Integer>();
ArrayList <Integer> ys = new ArrayList<Integer>();
for(int i=0;i<MatEstAct.length;i++){
for(int j=0;j<MatEstAct[0].length;j++){
if(tamTab-2<=i+j && i+j<=3*tamTab-4){
boolean res = verificarContraDiagonalInferior(i, j, turnoFich,MatEstAct) || verificarContraDiagonalSuperior(i, j, turnoFich,MatEstAct)
|| verificarDiagonalInferior(i, j, turnoFich,MatEstAct) || verificarDiagonalSuperior(i, j, turnoFich,MatEstAct)
|| verificarVerticalInferior(i, j, turnoFich,MatEstAct) || verificarVerticalSuperior(i, j, turnoFich,MatEstAct);
if (res){
xs.add(i);
ys.add(j);
}
}
}
}
listJug.add(xs);
listJug.add(ys);
return listJug;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Busquedas por niveles de maquina">
private int[] buscarJugadaFacil(int ficha){
ArrayList <ArrayList <Integer>> jugadas = buscarJugadasPosibles(ficha,MatTab);
ArrayList <Integer> xs = jugadas.get(0);
ArrayList <Integer> ys = jugadas.get(1);
int ind = (int)(Math.random()*xs.size());
System.out.println("Las pos jugdas son:");
for (int i = 0; i < xs.size(); i++)
System.out.println("i: "+i+" => "+xs.get(i)+" "+ys.get(i));
System.out.println("La jugada es "+ind+" de "+xs.size());
int jugada[] = {xs.get(ind), ys.get(ind)};
return jugada;
}
private int[] buscarJugadaMedio(int ficha){
ArrayList <ArrayList <Integer>> jugadas = buscarJugadasPosibles(ficha,MatTab);
ArrayList <Integer> xs = jugadas.get(0);
ArrayList <Integer> ys = jugadas.get(1);
ArrayList <Float> pesos = new ArrayList<Float>();
for(int i = 0; i < xs.size(); i++)
pesos.add(funcionEvaluadora(xs.get(i), ys.get(i), ficha, MatTab));
int ind = 0;
/*float may = pesos.get(ind);
for(int i = 0; i < pesos.size(); i++)
if(pesos.get(i)>may){
ind = i;
may = pesos.get(i);
}
System.out.println("Elegi jugada "+ ind +" peso: "+may);*/
ind = indiceMejorJugada(pesos);
int jugada[] = {xs.get(ind), ys.get(ind)};
return jugada;
}
private int[] buscarJugadaExperto(int ficha){
ArrayList <ArrayList <Integer>> jugadas = buscarJugadasPosibles(ficha,MatTab);
ArrayList <Integer> xs = jugadas.get(0);
ArrayList <Integer> ys = jugadas.get(1);
ArrayList <Float> difGanancias = new ArrayList<Float>();
System.out.println("exiten "+(xs.size())+" jugs mias");
int[][] estTemp = new int[MatTab.length][MatTab.length];
for(int index=0;index<xs.size();index++){
for(int i=0;i<MatTab.length;i++)
for(int j=0;j<MatTab.length;j++)
estTemp[i][j] = MatTab[i][j];
difGanancias.add(funcionEvaluadora(xs.get(index), ys.get(index), ficha, estTemp)
- mejorJugadaContrincante(xs.get(index), ys.get(index), ficha, estTemp));
}
int ind = 0;
/*float may = difGanancias.get(ind);
for(int i = 0; i < difGanancias.size(); i++)
if(difGanancias.get(i) > may){
ind = i;
may = difGanancias.get(i);
}
System.out.println("Elegi jugada "+ ind +" peso: "+may);*/
ind = indiceMejorJugada(difGanancias);
int jugada[] = {xs.get(ind), ys.get(ind)};
return jugada;
}
private float mejorJugadaContrincante(int x, int y, int ficha, int[][] estAnt){
ArrayList <ArrayList <Integer>> jugadas = buscarJugadasPosibles(-ficha,estAnt);
ArrayList <Integer> xs = jugadas.get(0);
ArrayList <Integer> ys = jugadas.get(1);
ArrayList <Float> pesos = new ArrayList<Float>();
System.out.println("exiten "+(xs.size())+" jugs contr");
for(int i = 0; i < xs.size(); i++)
pesos.add(funcionEvaluadora(xs.get(i), ys.get(i), -ficha, estAnt));
int ind = 0;
if(xs.isEmpty())
return 0.0f;
float may = pesos.get(ind);
for(int i = 0; i < pesos.size(); i++){
System.out.println("jugada "+i+" de contrincante "+ pesos.get(i));
if(pesos.get(i)>may){
ind = i;
may = pesos.get(i);
}
}
System.out.println("Elegi jugada Cont "+ ind +" peso: "+may);
return may;
}
private int indiceMejorJugada(ArrayList<Float> array){
float mayor = array.get(0);
ArrayList<Float> Mayores = new ArrayList<Float>();
for (Float elemArr : array) {
if(mayor<elemArr){
Mayores = new ArrayList<Float>();
Mayores.add(elemArr);
mayor = elemArr;
}else{
if(mayor == elemArr)
Mayores.add(elemArr);
}
}
System.out.println("son "+Mayores.size()+ " jugadas posibles");
return (int)(Mayores.size()*Math.random());
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Selector de estrategia">
public void movimientoMaquina(){
if(turno == FICHA_BLANCA){
if(jug1.getTipo()==Jugador.HUMANO){
//esperar click
}else{
if(nivel1 == FACIL){
System.out.println("Entre a nivel facil");
int jug[] = buscarJugadaFacil(FICHA_BLANCA);
colocarFichaBlanca(jug[0], jug[1]);
}
if(nivel1 == MEDIO){
System.out.println("Entre a nivel medio");
int jug[] = buscarJugadaMedio(FICHA_BLANCA);
colocarFichaBlanca(jug[0], jug[1]);
// <editor-fold defaultstate="collapsed" desc="Estrategia MEDIO">
// </editor-fold>
}
if(nivel1 == EXPERTO){
System.out.println("Entre a nivel medio");
int jug[] = buscarJugadaExperto(FICHA_BLANCA);
colocarFichaBlanca(jug[0], jug[1]);
// <editor-fold defaultstate="collapsed" desc="Estrategia EXPERTO">
// </editor-fold>
}
}
}else{
if(jug2.getTipo()==Jugador.HUMANO){
//esperar click
}else{
if(nivel2 == FACIL){
int jug[] = buscarJugadaFacil(FICHA_NEGRA);
colocarFichaNegra(jug[0], jug[1]);
}
if(nivel2 == MEDIO){
int jug[] = buscarJugadaMedio(FICHA_NEGRA);
colocarFichaNegra(jug[0], jug[1]);
// <editor-fold defaultstate="collapsed" desc="Estrategia MEDIO">
// </editor-fold>
}
if(nivel2 == EXPERTO){
int jug[] = buscarJugadaExperto(FICHA_NEGRA);
colocarFichaNegra(jug[0], jug[1]);
// <editor-fold defaultstate="collapsed" desc="Estrategia EXPERTO">
// </editor-fold>
}
}
}
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="Funcion evaluadora/criterios">
private float funcionEvaluadora(int x, int y, int ficha, int[][] estAct){
System.out.println("Peso en "+x+" "+y+" = "+(fichasInvert(x,y,ficha,estAct)*CRIT_FICHAS_INVERTIDAS+pesoPosicion(x,y)*CRIT_PESO_POSICION));
return fichasInvert(x,y,ficha,estAct)*CRIT_FICHAS_INVERTIDAS+pesoPosicion(x,y)*CRIT_PESO_POSICION;
}
//crea una matriz temporal a partir del parametro que solicita
private int fichasInvert(int x, int y,int ficha, int[][] estAct){
int[][] estTemp = new int[estAct.length][estAct.length];
for(int i=0;i<estAct.length;i++)
for(int j=0;j<estAct.length;j++)
estTemp[i][j] = estAct[i][j];
int cont = 0;
if(verificarDiagonalInferior(x, y, ficha, estTemp))
cont+=cambiarFichasDiagonalInferior(x, y, ficha, estTemp);
if(verificarDiagonalSuperior(x, y, ficha, estTemp))
cont+=cambiarFichasDiagonalSuperior(x, y, ficha, estTemp);
if(verificarContraDiagonalInferior(x, y, ficha, estTemp))
cont+=cambiarFichasContraDiagonalInferior(x, y, ficha, estTemp);
if(verificarContraDiagonalSuperior(x, y, ficha, estTemp))
cont+=cambiarFichasContraDiagonalSuperior(x, y, ficha, estTemp);
if(verificarVerticalInferior(x, y, ficha, estTemp))
cont+=cambiarFichasVerticalInferior(x, y, ficha, estTemp);
if(verificarVerticalSuperior(x, y, ficha, estTemp))
cont+=cambiarFichasVerticalSuperior(x, y, ficha, estTemp);
return cont;
}
private int pesoPosicion(int x, int y){
return MatPesos[x][y];
}
// </editor-fold>
public int getTamTab() {
return tamTab;
}
public void setTamTab(int tamTab) {
this.tamTab = tamTab;
}
public int[][] getMatTab() {
return MatTab;
}
public void setMatTab(int[][] MatTab) {
this.MatTab = MatTab;
}
public int getTurno() {
return turno;
}
public void setTurno(int turno) {
this.turno = turno;
}
public int getTipoJug1(){
return jug1.getTipo();
}
public int getTipoJug2(){
return jug2.getTipo();
}
}
| |
package ru.shutoff.caralarm;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.support.v4.app.NotificationCompat;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;
@SuppressWarnings("ConstantConditions")
public class Alarm extends Activity {
TextView tvAlarm;
ImageView imgPhoto;
MediaPlayer player;
VolumeTask volumeTask;
Timer timer;
String car_id;
SharedPreferences preferences;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm);
tvAlarm = (TextView) findViewById(R.id.text_alarm);
imgPhoto = (ImageView) findViewById(R.id.photo);
Button btn = (Button) findViewById(R.id.alarm);
btn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
v.setBackgroundResource(R.drawable.pressed);
break;
case MotionEvent.ACTION_UP:
showMain();
break;
case MotionEvent.ACTION_CANCEL:
v.setBackgroundResource(R.drawable.button);
break;
}
return true;
}
});
preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
car_id = Preferences.getCar(preferences, getIntent().getStringExtra(Names.ID));
process(getIntent());
}
void showMain() {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(Names.ID, car_id);
startActivity(intent);
finish();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
process(intent);
}
@Override
public void onAttachedToWindow() {
//make the activity show even the screen is locked.
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
+ WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
+ WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
+ WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
}
@Override
protected void onDestroy() {
super.onDestroy();
stop();
}
void stop() {
if (player != null) {
player.release();
player = null;
}
if (volumeTask != null) {
volumeTask.stop();
volumeTask = null;
}
if (timer != null) {
timer.cancel();
timer = null;
}
}
void cancelAlarm() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(getBaseContext())
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Car Aarm") //$NON-NLS-1$
.setContentText(tvAlarm.getText()); //$NON-NLS-1$
Intent notificationIntent = new Intent(getBaseContext(), MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
int id = preferences.getInt(Names.IDS, 0);
id++;
SharedPreferences.Editor ed = preferences.edit();
ed.putInt(Names.IDS, id);
ed.commit();
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(id, builder.build());
finish();
}
void process(Intent intent) {
car_id = Preferences.getCar(preferences, intent.getStringExtra(Names.ID));
String number = preferences.getString(Names.CAR_PHONE + car_id, "");
if (number.length() > 0) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
Cursor contactLookup = null;
try {
ContentResolver contentResolver = getContentResolver();
contactLookup = contentResolver.query(uri, new String[]{BaseColumns._ID,
ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
if (contactLookup != null) {
if (contactLookup.getCount() > 0) {
contactLookup.moveToNext();
String contactId = contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactId));
Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
AssetFileDescriptor fd =
getContentResolver().openAssetFileDescriptor(displayPhotoUri, "r");
InputStream inputStream = fd.createInputStream();
if (inputStream != null) {
Bitmap photo = BitmapFactory.decodeStream(inputStream);
imgPhoto.setImageBitmap(photo);
inputStream.close();
}
}
}
} catch (Exception ex) {
// ignore
} finally {
if (contactLookup != null) {
contactLookup.close();
}
}
}
String alarm = intent.getStringExtra(Names.ALARM);
if (alarm != null) {
String[] cars = preferences.getString(Names.CARS, "").split(",");
if (cars.length > 1) {
String name = preferences.getString(Names.CAR_NAME, "");
if (name.length() == 0) {
name = getString(R.string.car);
if (car_id.length() > 0)
name += " " + car_id;
}
alarm = name + "\n" + alarm;
}
tvAlarm.setText(alarm);
String sound = preferences.getString(Names.ALARM, "");
Uri uri = Uri.parse(sound);
Ringtone ringtone = RingtoneManager.getRingtone(getBaseContext(), uri);
if (ringtone == null)
uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
if (timer != null)
timer.cancel();
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
cancelAlarm();
}
});
}
};
timer = new Timer();
timer.schedule(timerTask, 3 * 60 * 1000);
try {
if (player == null) {
volumeTask = new VolumeTask(this);
player = new MediaPlayer();
player.setDataSource(this, uri);
player.setAudioStreamType(AudioManager.STREAM_RING);
player.setLooping(true);
player.prepare();
player.start();
}
} catch (Exception err) {
// ignore
}
}
}
}
| |
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.eperson;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Locale;
import javax.mail.MessagingException;
import org.apache.log4j.Logger;
import org.dspace.authorize.AuthorizeException;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.core.Email;
import org.dspace.core.I18nUtil;
import org.dspace.core.Utils;
import org.dspace.storage.rdbms.DatabaseManager;
import org.dspace.storage.rdbms.TableRow;
/**
* Methods for handling registration by email and forgotten passwords. When
* someone registers as a user, or forgets their password, the
* sendRegistrationInfo or sendForgotPasswordInfo methods can be used to send an
* email to the user. The email contains a special token, a long string which is
* randomly generated and thus hard to guess. When the user presents the token
* back to the system, the AccountManager can use the token to determine the
* identity of the eperson.
*
* *NEW* now ignores expiration dates so that tokens never expire
*
* @author Peter Breton
* @version $Revision$
*/
public class AccountManager
{
/** log4j log */
private static Logger log = Logger.getLogger(AccountManager.class);
/** Protected Constructor */
protected AccountManager()
{
}
/**
* Email registration info to the given email address.
*
* Potential error conditions: Cannot create registration data in database
* (throws SQLException) Error sending email (throws MessagingException)
* Error reading email template (throws IOException) Authorization error
* (throws AuthorizeException)
*
* @param context
* DSpace context
* @param email
* Email address to send the registration email to
*/
public static void sendRegistrationInfo(Context context, String email)
throws SQLException, IOException, MessagingException,
AuthorizeException
{
sendInfo(context, email, true, true);
}
/**
* Email forgot password info to the given email address.
*
* Potential error conditions: No EPerson with that email (returns null)
* Cannot create registration data in database (throws SQLException) Error
* sending email (throws MessagingException) Error reading email template
* (throws IOException) Authorization error (throws AuthorizeException)
*
* @param context
* DSpace context
* @param email
* Email address to send the forgot-password email to
*/
public static void sendForgotPasswordInfo(Context context, String email)
throws SQLException, IOException, MessagingException,
AuthorizeException
{
sendInfo(context, email, false, true);
}
/**
* <p>
* Return the EPerson corresponding to token, where token was emailed to the
* person by either the sendRegistrationInfo or sendForgotPasswordInfo
* methods.
* </p>
*
* <p>
* If the token is not found return null.
* </p>
*
* @param context
* DSpace context
* @param token
* Account token
* @return The EPerson corresponding to token, or null.
* @exception SQLException
* If the token or eperson cannot be retrieved from the
* database.
*/
public static EPerson getEPerson(Context context, String token)
throws SQLException, AuthorizeException
{
String email = getEmail(context, token);
if (email == null)
{
return null;
}
EPerson ep = EPerson.findByEmail(context, email);
return ep;
}
/**
* Return the e-mail address referred to by a token, or null if email
* address can't be found ignores expiration of token
*
* @param context
* DSpace context
* @param token
* Account token
* @return The email address corresponding to token, or null.
*/
public static String getEmail(Context context, String token)
throws SQLException
{
TableRow rd = DatabaseManager.findByUnique(context, "RegistrationData",
"token", token);
if (rd == null)
{
return null;
}
/*
* ignore the expiration date on tokens Date expires =
* rd.getDateColumn("expires"); if (expires != null) { if ((new
* java.util.Date()).after(expires)) return null; }
*/
return rd.getStringColumn("email");
}
/**
* Delete token.
*
* @param context
* DSpace context
* @param token
* The token to delete
* @exception SQLException
* If a database error occurs
*/
public static void deleteToken(Context context, String token)
throws SQLException
{
DatabaseManager.deleteByValue(context, "RegistrationData", "token",
token);
}
/*
* THIS IS AN INTERNAL METHOD. THE SEND PARAMETER ALLOWS IT TO BE USED FOR
* TESTING PURPOSES.
*
* Send an info to the EPerson with the given email address. If isRegister
* is TRUE, this is registration email; otherwise, it is forgot-password
* email. If send is TRUE, the email is sent; otherwise it is skipped.
*
* Potential error conditions: No EPerson with that email (returns null)
* Cannot create registration data in database (throws SQLException) Error
* sending email (throws MessagingException) Error reading email template
* (throws IOException) Authorization error (throws AuthorizeException)
*
* @param context DSpace context @param email Email address to send the
* forgot-password email to @param isRegister If true, this is for
* registration; otherwise, it is for forgot-password @param send If true,
* send email; otherwise do not send any email
*/
protected static TableRow sendInfo(Context context, String email,
boolean isRegister, boolean send) throws SQLException, IOException,
MessagingException, AuthorizeException
{
// See if a registration token already exists for this user
TableRow rd = DatabaseManager.findByUnique(context, "registrationdata",
"email", email);
// If it already exists, just re-issue it
if (rd == null)
{
rd = DatabaseManager.row("RegistrationData");
rd.setColumn("token", Utils.generateHexKey());
// don't set expiration date any more
// rd.setColumn("expires", getDefaultExpirationDate());
rd.setColumn("email", email);
DatabaseManager.insert(context, rd);
// This is a potential problem -- if we create the callback
// and then crash, registration will get SNAFU-ed.
// So FIRST leave some breadcrumbs
if (log.isDebugEnabled())
{
log.debug("Created callback "
+ rd.getIntColumn("registrationdata_id")
+ " with token " + rd.getStringColumn("token")
+ " with email \"" + email + "\"");
}
}
if (send)
{
sendEmail(context, email, isRegister, rd);
}
return rd;
}
/**
* Send a DSpace message to the given email address.
*
* If isRegister is <code>true</code>, this is registration email;
* otherwise, it is a forgot-password email.
*
* @param email
* The email address to mail to
* @param isRegister
* If true, this is registration email; otherwise it is
* forgot-password email.
* @param rd
* The RDBMS row representing the registration data.
* @exception MessagingException
* If an error occurs while sending email
* @exception IOException
* If an error occurs while reading the email template.
*/
private static void sendEmail(Context context, String email, boolean isRegister, TableRow rd)
throws MessagingException, IOException, SQLException
{
String base = ConfigurationManager.getProperty("dspace.url");
// Note change from "key=" to "token="
String specialLink = new StringBuffer().append(base).append(
base.endsWith("/") ? "" : "/").append(
isRegister ? "register" : "forgot").append("?")
.append("token=").append(rd.getStringColumn("token"))
.toString();
Locale locale = context.getCurrentLocale();
Email bean = ConfigurationManager.getEmail(I18nUtil.getEmailFilename(locale, isRegister ? "register"
: "change_password"));
bean.addRecipient(email);
bean.addArgument(specialLink);
bean.send();
// Breadcrumbs
if (log.isInfoEnabled())
{
log.info("Sent " + (isRegister ? "registration" : "account")
+ " information to " + email);
}
}
}
| |
/* $Id: MultipartWrapper.java 988245 2010-08-23 18:39:35Z kwright $ */
/**
* 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.manifoldcf.ui.multipart;
import org.apache.manifoldcf.core.interfaces.*;
import org.apache.manifoldcf.ui.beans.AdminProfile;
import org.apache.commons.fileupload.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
/** This class provides abstract parameter service, including support for uploaded files and
* multipart forms. It is styled much like HttpServletRequest, but wraps this interface so
* that code can access either standard post data or multipart data transparently.
*/
public class MultipartWrapper implements IPostParameters
{
public static final String _rcsid = "@(#)$Id: MultipartWrapper.java 988245 2010-08-23 18:39:35Z kwright $";
/** The Admin Profile bean, for password mapping. */
protected final AdminProfile adminProfile;
/** This is the HttpServletRequest object, which will be used for parameters only if
* the form is not multipart. */
protected HttpServletRequest request = null;
protected Map variableMap = new HashMap();
protected String characterEncoding = null;
/** Constructor.
*/
public MultipartWrapper(HttpServletRequest request, AdminProfile adminProfile)
throws ManifoldCFException
{
this.adminProfile = adminProfile;
// Check that we have a file upload request
boolean isMultipart = FileUpload.isMultipartContent(request);
if (!isMultipart)
{
this.request = request;
return;
}
// It is multipart!
// Create a factory for disk-based file items
DefaultFileItemFactory factory = new DefaultFileItemFactory();
// Create a new file upload handler
DiskFileUpload upload = new DiskFileUpload(factory);
// Parse the request
try
{
characterEncoding = request.getCharacterEncoding();
// Handle broken tomcat; characterEncoding always comes back null for tomcat4
if (characterEncoding == null)
characterEncoding = "utf8";
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext())
{
FileItem item = (FileItem) iter.next();
String name = item.getFieldName();
ArrayList list = (ArrayList)variableMap.get(name);
if (list == null)
{
list = new ArrayList();
variableMap.put(name,list);
}
else
{
if (((FileItem)list.get(0)).isFormField() != item.isFormField())
throw new ManifoldCFException("Illegal form data; posted form has the same name for different data types ('"+name+"')!");
}
list.add(item);
}
}
catch (FileUploadException e)
{
throw new ManifoldCFException("Problem uploading file: "+e.getMessage(),e);
}
}
/** Get multiple parameter values.
*/
@Override
public String[] getParameterValues(String name)
{
// Expect multiple items, all strings
ArrayList list = (ArrayList)variableMap.get(name);
if (list == null)
{
if (request != null)
return request.getParameterValues(name);
return null;
}
Object x = list.get(0);
if ((x instanceof FileItem) && !((FileItem)x).isFormField())
return null;
String[] rval = new String[list.size()];
int i = 0;
while (i < rval.length)
{
x = list.get(i);
if (x instanceof String)
rval[i] = (String)x;
else
{
try
{
rval[i] = ((FileItem)x).getString(characterEncoding);
}
catch (UnsupportedEncodingException e)
{
rval[i] = ((FileItem)x).getString();
}
}
i++;
}
return rval;
}
/** Get single parameter value.
*/
@Override
public String getParameter(String name)
{
// Get it as a parameter.
ArrayList list = (ArrayList)variableMap.get(name);
if (list == null)
{
if (request != null)
return request.getParameter(name);
return null;
}
Object x = list.get(0);
if (x instanceof String)
return (String)x;
FileItem item = (FileItem)x;
if (!item.isFormField())
return null;
try
{
return item.getString(characterEncoding);
}
catch (UnsupportedEncodingException e)
{
return item.getString();
}
}
/** Get a file parameter, as a binary input.
*/
@Override
public BinaryInput getBinaryStream(String name)
throws ManifoldCFException
{
if (request != null)
return null;
ArrayList list = (ArrayList)variableMap.get(name);
if (list == null)
return null;
Object x = list.get(0);
if (x instanceof String)
return null;
FileItem item = (FileItem)x;
if (item.isFormField())
return null;
try
{
InputStream uploadedStream = item.getInputStream();
try
{
return new TempFileInput(uploadedStream);
}
finally
{
uploadedStream.close();
}
}
catch (IOException e)
{
throw new ManifoldCFException("Error creating file binary stream",e);
}
}
/** Get file parameter, as a byte array.
*/
@Override
public byte[] getBinaryBytes(String name)
{
if (request != null)
return null;
ArrayList list = (ArrayList)variableMap.get(name);
if (list == null)
return null;
Object x = list.get(0);
if (x instanceof String)
return null;
FileItem item = (FileItem)x;
if (item.isFormField())
return null;
return item.get();
}
/** Set a parameter value
*/
@Override
public void setParameter(String name, String value)
{
ArrayList values = new ArrayList();
if (value != null)
values.add(value);
variableMap.put(name,values);
}
/** Set an array of parameter values
*/
@Override
public void setParameterValues(String name, String[] values)
{
ArrayList valueArray = new ArrayList();
int i = 0;
while (i < values.length)
{
valueArray.add(values[i++]);
}
variableMap.put(name,valueArray);
}
// Password mapping
/** Map a password to a unique key.
* This method works within a specific given browser session to replace an existing password with
* a key which can be used to look up the password at a later time.
*@param password is the password.
*@return the key.
*/
@Override
public String mapPasswordToKey(String password)
{
return adminProfile.getPasswordMapper().mapPasswordToKey(password);
}
/** Convert a key, created by mapPasswordToKey, back to the original password, within
* the lifetime of the browser session. If the provided key is not an actual key, instead
* the key value is assumed to be a new password value.
*@param key is the key.
*@return the password.
*/
@Override
public String mapKeyToPassword(String key)
{
return adminProfile.getPasswordMapper().mapKeyToPassword(key);
}
}
| |
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.graphic;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import net.sourceforge.plantuml.Dimension2DDouble;
import net.sourceforge.plantuml.style.SName;
import net.sourceforge.plantuml.ugraphic.UGraphic;
import net.sourceforge.plantuml.ugraphic.UGraphicStencil;
import net.sourceforge.plantuml.ugraphic.UPath;
import net.sourceforge.plantuml.ugraphic.UTranslate;
// https://stackoverflow.com/questions/39552127/algorithm-for-drawing-random-comic-style-clouds
// http://martin-oehm.de/data/cloud.html
// https://stackoverflow.com/questions/34623855/what-is-the-algorithm-behind-the-pdf-cloud-annotation
// https://stackoverflow.com/questions/3177121/how-do-i-paint-clouds
class USymbolCloud extends USymbol {
private final static boolean NEW = true;
private final static boolean DEBUG = false;
@Override
public SkinParameter getSkinParameter() {
return SkinParameter.CLOUD;
}
@Override
public SName getSName() {
return SName.cloud;
}
private void drawCloud(UGraphic ug, double width, double height, double shadowing) {
final UPath shape = getSpecificFrontierForCloud(width, height);
shape.setDeltaShadow(shadowing);
ug.apply(UTranslate.dy(0)).draw(shape);
}
private UPath getSpecificFrontierForCloudNew(double width, double height) {
final Random rnd = new Random((long) width + 7919L * (long) height);
final List<Point2D> points = new ArrayList<>();
double bubbleSize = 11;
if (Math.max(width, height) / bubbleSize > 16) {
bubbleSize = Math.max(width, height) / 16;
}
final double margin1 = 8;
final Point2D.Double pointA = new Point2D.Double(margin1, margin1);
final Point2D.Double pointB = new Point2D.Double(width - margin1, margin1);
final Point2D.Double pointC = new Point2D.Double(width - margin1, height - margin1);
final Point2D.Double pointD = new Point2D.Double(margin1, height - margin1);
if (width > 100 && height > 100) {
complex(rnd, points, bubbleSize, pointA, pointB, pointC, pointD);
} else {
simple(rnd, points, bubbleSize, pointA, pointB, pointC, pointD);
}
points.add(points.get(0));
final UPath result = new UPath();
result.moveTo(points.get(0));
for (int i = 0; i < points.size() - 1; i++) {
if (DEBUG) {
result.lineTo(points.get(i + 1));
} else {
addCurve(rnd, result, points.get(i), points.get(i + 1));
}
}
return result;
}
private void complex(final Random rnd, final List<Point2D> points, double bubbleSize, final Point2D.Double pointA,
final Point2D.Double pointB, final Point2D.Double pointC, final Point2D.Double pointD) {
final double margin2 = 7;
specialLine(bubbleSize, rnd, points, mvX(pointA, margin2), mvX(pointB, -margin2));
points.add(mvY(pointB, margin2));
specialLine(bubbleSize, rnd, points, mvY(pointB, margin2), mvY(pointC, -margin2));
points.add(mvX(pointC, -margin2));
specialLine(bubbleSize, rnd, points, mvX(pointC, -margin2), mvX(pointD, margin2));
points.add(mvY(pointD, -margin2));
specialLine(bubbleSize, rnd, points, mvY(pointD, -margin2), mvY(pointA, margin2));
points.add(mvX(pointA, margin2));
}
private void simple(final Random rnd, final List<Point2D> points, double bubbleSize, final Point2D.Double pointA,
final Point2D.Double pointB, final Point2D.Double pointC, final Point2D.Double pointD) {
specialLine(bubbleSize, rnd, points, pointA, pointB);
specialLine(bubbleSize, rnd, points, pointB, pointC);
specialLine(bubbleSize, rnd, points, pointC, pointD);
specialLine(bubbleSize, rnd, points, pointD, pointA);
}
private static Point2D mvX(Point2D pt, double dx) {
return new Point2D.Double(pt.getX() + dx, pt.getY());
}
private static Point2D mvY(Point2D pt, double dy) {
return new Point2D.Double(pt.getX(), pt.getY() + dy);
}
private void specialLine(double bubbleSize, Random rnd, List<Point2D> points, Point2D p1, Point2D p2) {
final CoordinateChange change = new CoordinateChange(p1, p2);
final double length = change.getLength();
final Point2D middle = change.getTrueCoordinate(length / 2, -rnd(rnd, 1, 1 + Math.min(12, bubbleSize * 0.8)));
// final Point2D middle = change.getTrueCoordinate(length / 2, -13);
if (DEBUG) {
points.add(middle);
points.add(p2);
} else {
bubbleLine(rnd, points, p1, middle, bubbleSize);
bubbleLine(rnd, points, middle, p2, bubbleSize);
}
}
private void bubbleLine(Random rnd, List<Point2D> points, Point2D p1, Point2D p2, double bubbleSize) {
final CoordinateChange change = new CoordinateChange(p1, p2);
final double length = change.getLength();
int nb = (int) (length / bubbleSize);
if (nb == 0) {
bubbleSize = length / 2;
nb = (int) (length / bubbleSize);
}
for (int i = 0; i < nb; i++) {
points.add(rnd(rnd, change.getTrueCoordinate(i * length / nb, 0), bubbleSize * .2));
}
}
private void addCurve(Random rnd, UPath path, Point2D p1, Point2D p2) {
final CoordinateChange change = new CoordinateChange(p1, p2);
final double length = change.getLength();
final double coef = rnd(rnd, .25, .35);
final Point2D middle = change.getTrueCoordinate(length * coef, -length * rnd(rnd, .4, .55));
final Point2D middle2 = change.getTrueCoordinate(length * (1 - coef), -length * rnd(rnd, .4, .55));
path.cubicTo(middle, middle2, p2);
}
static private double rnd(Random rnd, double a, double b) {
return rnd.nextDouble() * (b - a) + a;
}
static private Point2D rnd(Random rnd, Point2D pt, double v) {
final double x = pt.getX() + v * rnd.nextDouble();
final double y = pt.getY() + v * rnd.nextDouble();
return new Point2D.Double(x, y);
}
private UPath getSpecificFrontierForCloud(double width, double height) {
if (NEW) {
return getSpecificFrontierForCloudNew(width, height);
}
final UPath path = new UPath();
path.moveTo(0, 10);
double x = 0;
for (int i = 0; i < width - 9; i += 10) {
path.cubicTo(i, -3 + 10, 2 + i, -5 + 10, 5 + i, -5 + 10);
path.cubicTo(8 + i, -5 + 10, 10 + i, -3 + 10, 10 + i, 10);
x = i + 10;
}
double y = 0;
for (int j = 10; j < height - 9; j += 10) {
path.cubicTo(x + 3, j, x + 5, 2 + j, x + 5, 5 + j);
path.cubicTo(x + 5, 8 + j, x + 3, 10 + j, x, 10 + j);
y = j + 10;
}
for (int i = 0; i < width - 9; i += 10) {
path.cubicTo(x - i, y + 3, x - 3 - i, y + 5, x - 5 - i, y + 5);
path.cubicTo(x - 8 - i, y + 5, x - 10 - i, y + 3, x - 10 - i, y);
}
for (int j = 0; j < height - 9 - 10; j += 10) {
path.cubicTo(-3, y - j, -5, y - 2 - j, -5, y - 5 - j);
path.cubicTo(-5, y - 8 - j, -3, y - 10 - j, 0, y - 10 - j);
}
return path;
}
private Margin getMargin() {
if (NEW)
return new Margin(15, 15, 15, 15);
return new Margin(10, 10, 10, 10);
}
@Override
public TextBlock asSmall(TextBlock name, final TextBlock label, final TextBlock stereotype,
final SymbolContext symbolContext, final HorizontalAlignment stereoAlignment) {
return new AbstractTextBlock() {
public void drawU(UGraphic ug) {
final Dimension2D dim = calculateDimension(ug.getStringBounder());
ug = UGraphicStencil.create(ug, dim);
ug = symbolContext.apply(ug);
drawCloud(ug, dim.getWidth(), dim.getHeight(), symbolContext.getDeltaShadow());
final Margin margin = getMargin();
final TextBlock tb = TextBlockUtils.mergeTB(stereotype, label, HorizontalAlignment.CENTER);
tb.drawU(ug.apply(new UTranslate(margin.getX1(), margin.getY1())));
}
public Dimension2D calculateDimension(StringBounder stringBounder) {
final Dimension2D dimLabel = label.calculateDimension(stringBounder);
final Dimension2D dimStereo = stereotype.calculateDimension(stringBounder);
return getMargin().addDimension(Dimension2DDouble.mergeTB(dimStereo, dimLabel));
}
};
}
@Override
public TextBlock asBig(final TextBlock title, HorizontalAlignment labelAlignment, final TextBlock stereotype,
final double width, final double height, final SymbolContext symbolContext,
final HorizontalAlignment stereoAlignment) {
return new AbstractTextBlock() {
public void drawU(UGraphic ug) {
final Dimension2D dim = calculateDimension(ug.getStringBounder());
ug = symbolContext.apply(ug);
drawCloud(ug, dim.getWidth(), dim.getHeight(), symbolContext.getDeltaShadow());
final Dimension2D dimStereo = stereotype.calculateDimension(ug.getStringBounder());
final double posStereo = (width - dimStereo.getWidth()) / 2;
stereotype.drawU(ug.apply(new UTranslate(posStereo, 13)));
final Dimension2D dimTitle = title.calculateDimension(ug.getStringBounder());
final double posTitle = (width - dimTitle.getWidth()) / 2;
title.drawU(ug.apply(new UTranslate(posTitle, 13 + dimStereo.getHeight())));
}
public Dimension2D calculateDimension(StringBounder stringBounder) {
return new Dimension2DDouble(width, height);
}
};
}
}
| |
package org.broadinstitute.hellbender.metrics;
import htsjdk.samtools.SAMReadGroupRecord;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.metrics.MetricsFile;
import htsjdk.samtools.reference.ReferenceSequence;
import htsjdk.samtools.util.CloserUtil;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.File;
import java.io.Serializable;
import java.util.*;
import static htsjdk.samtools.util.CollectionUtil.makeSet;
/**
* Test all of the functionality of MultiLevelReducibleCollector. This includes duplicates of
* all of the basic functionality of multi-level distribution based on the MultiLevelCollector
* tests, with additional test code to verify the combine functionality used for combing/reducing
* multiple collectors into a single collector.
*/
public final class MultiLevelReducibleCollectorUnitTest {
public static File TESTFILE = new File("src/test/resources/org/broadinstitute/hellbender/metrics/test.sam");
public String noneOrStr(final String str) {
return str == null ? "" : str;
}
static final class TestArg {
public final SAMRecord samRecord;
public final ReferenceSequence refSeq;
public TestArg(final SAMRecord samRecord, final ReferenceSequence refSeq) {
this.samRecord = samRecord;
this.refSeq = refSeq;
}
}
/** We will just Tally up the number of times records were added to this metric and change FINISHED
* to true when FINISHED is called
*/
static final class TotalNumberMetric extends MultiLevelMetrics implements Serializable {
private static final long serialVersionUID = 1L;
/** The number of these encountered **/
public Integer TALLY = 0;
public boolean FINISHED = false;
}
private class RecordCountPerUnitCollector implements PerUnitMetricCollector<TotalNumberMetric, Integer, TestArg>{
private static final long serialVersionUID = 1L;
private final TotalNumberMetric metric;
RecordCountMultiLevelCollector outerCollector;
public RecordCountPerUnitCollector(
final RecordCountMultiLevelCollector outerCollector, final String sample, final String library, final String readGroup) {
this.outerCollector = outerCollector;
metric = new TotalNumberMetric();
metric.SAMPLE = sample;
metric.LIBRARY = library;
metric.READ_GROUP = readGroup;
outerCollector.unitsToMetrics.put(noneOrStr(sample) + "_" + noneOrStr(library) + "_" + noneOrStr(readGroup), metric);
}
@Override
public void acceptRecord(final TestArg args) {
outerCollector.numProcessed += 1;
metric.TALLY += 1;
if(metric.SAMPLE != null) {
Assert.assertEquals(metric.SAMPLE, args.samRecord.getReadGroup().getSample());
}
if(metric.LIBRARY != null) {
Assert.assertEquals(metric.LIBRARY, args.samRecord.getReadGroup().getLibrary());
}
if(metric.READ_GROUP != null) {
Assert.assertEquals(metric.READ_GROUP, args.samRecord.getReadGroup().getPlatformUnit());
}
}
@Override
public void finish() {
metric.FINISHED = true;
}
@Override
public void addMetricsToFile(final MetricsFile<TotalNumberMetric, Integer> totalNumberMetricIntegerMetricsFile) {
totalNumberMetricIntegerMetricsFile.addMetric(metric);
}
public RecordCountPerUnitCollector combine(RecordCountPerUnitCollector source) {
Assert.assertEquals(this.metric.FINISHED, true);
Assert.assertEquals(source.metric.FINISHED, true);
Assert.assertEquals(this.metric.SAMPLE, source.metric.SAMPLE);
Assert.assertEquals(this.metric.LIBRARY, source.metric.LIBRARY);
Assert.assertEquals(this.metric.READ_GROUP, source.metric.READ_GROUP);
metric.TALLY += source.metric.TALLY;
return this;
}
}
class RecordCountMultiLevelCollector extends MultiLevelReducibleCollector<TotalNumberMetric, Integer, TestArg, RecordCountPerUnitCollector> {
private static final long serialVersionUID = 1L;
public RecordCountMultiLevelCollector(
final Set<MetricAccumulationLevel> accumulationLevels,
final List<SAMReadGroupRecord> samRgRecords) {
setup(accumulationLevels, samRgRecords);
}
//The number of times records were accepted by a RecordCountPerUnitCollectors (note since the same
//samRecord might be aggregated by multiple PerUnit collectors, this may be greater than the number of
//records in the file
private int numProcessed = 0;
public int getNumProcessed() {
return numProcessed;
}
private Map<String, TotalNumberMetric> unitsToMetrics = new LinkedHashMap<>();
public Map<String, TotalNumberMetric> getUnitsToMetrics() {
return unitsToMetrics;
}
public void setUnitsToMetrics(Map<String, TotalNumberMetric> inMap) {
unitsToMetrics = inMap;
}
@Override
protected TestArg makeArg(final SAMRecord samRec, final ReferenceSequence refSeq) {
return new TestArg(samRec, refSeq);
}
@Override
protected RecordCountPerUnitCollector makeChildCollector(
final String sample, final String library, final String readGroup) {
return new RecordCountPerUnitCollector(this, sample, library, readGroup);
}
/*
* Normally this would not be overridden by subclasses since the interesting metrics are at
* the per-unit collector level, but this test collects aggregate values for test purposes
* so we need to combine those manually.
*/
public void combine(RecordCountMultiLevelCollector source) {
// first, combine the per-unit metrics by delegating to the default combine method
super.combine(source);
// combine the test-specific stuff
this.numProcessed = this.getNumProcessed() + source.getNumProcessed();
Map<String, TotalNumberMetric> combinedUnitsToMetrics = new LinkedHashMap<>(this.getUnitsToMetrics());
combinedUnitsToMetrics.putAll(source.getUnitsToMetrics());
combinedUnitsToMetrics.putAll(this.getUnitsToMetrics());
this.setUnitsToMetrics(combinedUnitsToMetrics);
}
@Override
public RecordCountPerUnitCollector combineUnit(RecordCountPerUnitCollector c1, RecordCountPerUnitCollector c2) {
return c1.combine(c2);
}
}
public static final Map<MetricAccumulationLevel, Map<String, Integer>> accumulationLevelToPerUnitReads =
new LinkedHashMap<>();
static {
HashMap<String, Integer> curMap = new LinkedHashMap<>();
curMap.put("__", 19);
accumulationLevelToPerUnitReads.put(MetricAccumulationLevel.ALL_READS, curMap);
curMap = new LinkedHashMap<>();
curMap.put("Ma__", 10);
curMap.put("Pa__", 9);
accumulationLevelToPerUnitReads.put(MetricAccumulationLevel.SAMPLE, curMap);
curMap = new LinkedHashMap<>();
curMap.put("Ma_whatever_", 10);
curMap.put("Pa_lib1_", 4);
curMap.put("Pa_lib2_", 5);
accumulationLevelToPerUnitReads.put(MetricAccumulationLevel.LIBRARY, curMap);
curMap = new LinkedHashMap<>();
curMap.put("Ma_whatever_me", 10);
curMap.put("Pa_lib1_myself", 4);
curMap.put("Pa_lib2_i", 3);
curMap.put("Pa_lib2_i2", 2);
accumulationLevelToPerUnitReads.put(MetricAccumulationLevel.READ_GROUP, curMap);
}
@DataProvider(name = "variedAccumulationLevels")
public Object[][] variedAccumulationLevels() {
return new Object[][] {
{makeSet(MetricAccumulationLevel.ALL_READS)},
{makeSet(MetricAccumulationLevel.ALL_READS, MetricAccumulationLevel.SAMPLE)},
{makeSet(MetricAccumulationLevel.SAMPLE, MetricAccumulationLevel.LIBRARY)},
{makeSet(MetricAccumulationLevel.READ_GROUP, MetricAccumulationLevel.LIBRARY)},
{makeSet(MetricAccumulationLevel.SAMPLE, MetricAccumulationLevel.LIBRARY, MetricAccumulationLevel.READ_GROUP)},
{makeSet(MetricAccumulationLevel.SAMPLE, MetricAccumulationLevel.LIBRARY, MetricAccumulationLevel.READ_GROUP, MetricAccumulationLevel.ALL_READS)},
};
}
@Test(dataProvider = "variedAccumulationLevels")
public void multilevelCollectorTest(final Set<MetricAccumulationLevel> accumulationLevels) {
final SamReader in = SamReaderFactory.makeDefault().open(TESTFILE);
final RecordCountMultiLevelCollector collector1 = new RecordCountMultiLevelCollector(
accumulationLevels, in.getFileHeader().getReadGroups());
final RecordCountMultiLevelCollector collector2 = new RecordCountMultiLevelCollector(
accumulationLevels, in.getFileHeader().getReadGroups());
//distribute the reads across the two collectors
int count = 1;
for (final SAMRecord rec : in) {
if (count % 2 == 0) {
collector1.acceptRecord(rec, null);
}
else {
collector2.acceptRecord(rec, null);
}
count++;
}
collector1.finish();
collector2.finish();
// combine the results into collector1
collector1.combine(collector2);
int totalProcessed = 0;
int totalMetrics = 0;
for(final MetricAccumulationLevel level : accumulationLevels) {
final Map<String, Integer> keyToMetrics = accumulationLevelToPerUnitReads.get(level);
for(final Map.Entry<String, Integer> entry : keyToMetrics.entrySet()) {
final TotalNumberMetric metric = collector1.getUnitsToMetrics().get(entry.getKey());
Assert.assertEquals(entry.getValue(), metric.TALLY);
Assert.assertTrue(metric.FINISHED);
totalProcessed += metric.TALLY;
totalMetrics += 1;
}
}
Assert.assertEquals(collector1.getUnitsToMetrics().size(), totalMetrics);
Assert.assertEquals(totalProcessed, collector1.getNumProcessed());
CloserUtil.close(in);
}
}
| |
package correos.tiendaonline.software.Datos;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Mauricio
*/
public class Categoria {
int id;
String nombre,descripcion;
Conexion m_Conexion;
public Categoria() {
this.m_Conexion = Conexion.getInstancia();
}
public void setId(int id) {
this.id = id;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public void setCategoria(int id,String nombre,String descripcion){
this.id = id;
this.nombre = nombre;
this.descripcion = descripcion;
}
public void setCategoria(String nombre,String descripcion){
this.nombre = nombre;
this.descripcion = descripcion;
}
public DefaultTableModel getCategoria(int id) {
// Tabla para mostrar lo obtenido de la consulta
DefaultTableModel categoria = new DefaultTableModel();
categoria.setColumnIdentifiers(new Object[]{
"id", "nombre", "descripcion"
});
// Abro y obtengo la conexion
this.m_Conexion.abrirConexion();
Connection con = this.m_Conexion.getConexion();
// Preparo la consulta
String sql = "SELECT\n"
+ "categoria.id,\n"
+ "categoria.nombre,\n"
+ "categoria.descripcion\n"
+ "FROM categoria\n"
+ "WHERE categoria.id=?";
// Los simbolos de interrogacion son para mandar parametros
// a la consulta al momento de ejecutalas
try {
// La ejecuto
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
// Cierro la conexion
this.m_Conexion.cerrarConexion();
// Recorro el resultado
while (rs.next()) {
// Agrego las tuplas a mi tabla
categoria.addRow(new Object[]{
rs.getInt("id"),
rs.getString("nombre"),
rs.getString("descripcion"),
});
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return categoria;
}
public DefaultTableModel getCategorias() {
// Tabla para mostrar lo obtenido de la consulta
DefaultTableModel categorias = new DefaultTableModel();
categorias.setColumnIdentifiers(new Object[]{
"id", "nombre", "descrpcion"
});
// Abro y obtengo la conexion
this.m_Conexion.abrirConexion();
Connection con = this.m_Conexion.getConexion();
// Preparo la consulta
String sql = "SELECT\n"
+ "categoria.id,\n"
+ "categoria.nombre,\n"
+ "categoria.descripcion\n"
+ "FROM categoria\n"
+ "WHERE categoria.estado='true'";
try {
// La ejecuto
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
// Cierro la conexion
this.m_Conexion.cerrarConexion();
// Recorro el resultado
while (rs.next()) {
// Agrego las tuplas a mi tabla
categorias.addRow(new Object[]{
rs.getInt("id"),
rs.getString("nombre"),
rs.getString("descripcion")
});
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return categorias;
}
public int registrarCategoria() {
// Abro y obtengo la conexion
this.m_Conexion.abrirConexion();
Connection con = this.m_Conexion.getConexion();
// Preparo la consulta
String sql = "INSERT INTO categoria(\n"
+ "nombre,descripcion)\n"
+ "VALUES(?,?)";
try {
// La ejecuto
PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
// El segundo parametro de usa cuando se tienen tablas que generan llaves primarias
// es bueno cuando nuestra bd tiene las primarias autoincrementables
ps.setString(1, this.nombre);
ps.setString(2, this.descripcion);
int rows = ps.executeUpdate();
// Cierro Conexion
this.m_Conexion.cerrarConexion();
// Obtengo el id generado pra devolverlo
if (rows != 0) {
ResultSet generateKeys = ps.getGeneratedKeys();
if (generateKeys.next()) {
return generateKeys.getInt(1);
}
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return 0;
}
public void modificarCategoria() {
// Abro y obtengo la conexion
this.m_Conexion.abrirConexion();
Connection con = this.m_Conexion.getConexion();
// Preparo la consulta
String sql = "UPDATE categoria SET \n"
+ "nombre = ?,\n"
+ "descripcion = ?\n"
+ "WHERE categoria.id = ?";
System.out.println(sql);
System.out.println(toString());
try {
// La ejecuto
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, this.nombre);
ps.setString(2, this.descripcion);
ps.setInt(3, this.id);
int rows = ps.executeUpdate();
// Cierro la conexion
this.m_Conexion.cerrarConexion();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
public void eliminarCategoria() {
// Abro y obtengo la conexion
this.m_Conexion.abrirConexion();
Connection con = this.m_Conexion.getConexion();
// Preparo la consulta
String sql = "UPDATE categoria SET\n"
+ "estado = ?\n"
+ "WHERE categoria.id = ?";
try {
// La ejecuto
PreparedStatement ps = con.prepareStatement(sql);
ps.setBoolean(1,false);
ps.setInt(2, this.id);
int rows = ps.executeUpdate();
// Cierro la conexion
this.m_Conexion.cerrarConexion();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
| |
package org.ripple.bouncycastle.pqc.math.ntru.polynomial;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.SecureRandom;
import org.ripple.bouncycastle.pqc.math.ntru.util.ArrayEncoder;
import org.ripple.bouncycastle.pqc.math.ntru.util.Util;
import org.ripple.bouncycastle.util.Arrays;
/**
* A <code>TernaryPolynomial</code> with a "low" number of nonzero coefficients.
*/
public class SparseTernaryPolynomial
implements TernaryPolynomial
{
/**
* Number of bits to use for each coefficient. Determines the upper bound for <code>N</code>.
*/
private static final int BITS_PER_INDEX = 11;
private int N;
private int[] ones;
private int[] negOnes;
/**
* Constructs a new polynomial.
*
* @param N total number of coefficients including zeros
* @param ones indices of coefficients equal to 1
* @param negOnes indices of coefficients equal to -1
*/
SparseTernaryPolynomial(int N, int[] ones, int[] negOnes)
{
this.N = N;
this.ones = ones;
this.negOnes = negOnes;
}
/**
* Constructs a <code>DenseTernaryPolynomial</code> from a <code>IntegerPolynomial</code>. The two polynomials are
* independent of each other.
*
* @param intPoly the original polynomial
*/
public SparseTernaryPolynomial(IntegerPolynomial intPoly)
{
this(intPoly.coeffs);
}
/**
* Constructs a new <code>SparseTernaryPolynomial</code> with a given set of coefficients.
*
* @param coeffs the coefficients
*/
public SparseTernaryPolynomial(int[] coeffs)
{
N = coeffs.length;
ones = new int[N];
negOnes = new int[N];
int onesIdx = 0;
int negOnesIdx = 0;
for (int i = 0; i < N; i++)
{
int c = coeffs[i];
switch (c)
{
case 1:
ones[onesIdx++] = i;
break;
case -1:
negOnes[negOnesIdx++] = i;
break;
case 0:
break;
default:
throw new IllegalArgumentException("Illegal value: " + c + ", must be one of {-1, 0, 1}");
}
}
ones = Arrays.copyOf(ones, onesIdx);
negOnes = Arrays.copyOf(negOnes, negOnesIdx);
}
/**
* Decodes a byte array encoded with {@link #toBinary()} to a ploynomial.
*
* @param is an input stream containing an encoded polynomial
* @param N number of coefficients including zeros
* @param numOnes number of coefficients equal to 1
* @param numNegOnes number of coefficients equal to -1
* @return the decoded polynomial
* @throws IOException
*/
public static SparseTernaryPolynomial fromBinary(InputStream is, int N, int numOnes, int numNegOnes)
throws IOException
{
int maxIndex = 1 << BITS_PER_INDEX;
int bitsPerIndex = 32 - Integer.numberOfLeadingZeros(maxIndex - 1);
int data1Len = (numOnes * bitsPerIndex + 7) / 8;
byte[] data1 = Util.readFullLength(is, data1Len);
int[] ones = ArrayEncoder.decodeModQ(data1, numOnes, maxIndex);
int data2Len = (numNegOnes * bitsPerIndex + 7) / 8;
byte[] data2 = Util.readFullLength(is, data2Len);
int[] negOnes = ArrayEncoder.decodeModQ(data2, numNegOnes, maxIndex);
return new SparseTernaryPolynomial(N, ones, negOnes);
}
/**
* Generates a random polynomial with <code>numOnes</code> coefficients equal to 1,
* <code>numNegOnes</code> coefficients equal to -1, and the rest equal to 0.
*
* @param N number of coefficients
* @param numOnes number of 1's
* @param numNegOnes number of -1's
*/
public static SparseTernaryPolynomial generateRandom(int N, int numOnes, int numNegOnes, SecureRandom random)
{
int[] coeffs = Util.generateRandomTernary(N, numOnes, numNegOnes, random);
return new SparseTernaryPolynomial(coeffs);
}
public IntegerPolynomial mult(IntegerPolynomial poly2)
{
int[] b = poly2.coeffs;
if (b.length != N)
{
throw new IllegalArgumentException("Number of coefficients must be the same");
}
int[] c = new int[N];
for (int idx = 0; idx != ones.length; idx++)
{
int i = ones[idx];
int j = N - 1 - i;
for (int k = N - 1; k >= 0; k--)
{
c[k] += b[j];
j--;
if (j < 0)
{
j = N - 1;
}
}
}
for (int idx = 0; idx != negOnes.length; idx++)
{
int i = negOnes[idx];
int j = N - 1 - i;
for (int k = N - 1; k >= 0; k--)
{
c[k] -= b[j];
j--;
if (j < 0)
{
j = N - 1;
}
}
}
return new IntegerPolynomial(c);
}
public IntegerPolynomial mult(IntegerPolynomial poly2, int modulus)
{
IntegerPolynomial c = mult(poly2);
c.mod(modulus);
return c;
}
public BigIntPolynomial mult(BigIntPolynomial poly2)
{
BigInteger[] b = poly2.coeffs;
if (b.length != N)
{
throw new IllegalArgumentException("Number of coefficients must be the same");
}
BigInteger[] c = new BigInteger[N];
for (int i = 0; i < N; i++)
{
c[i] = BigInteger.ZERO;
}
for (int idx = 0; idx != ones.length; idx++)
{
int i = ones[idx];
int j = N - 1 - i;
for (int k = N - 1; k >= 0; k--)
{
c[k] = c[k].add(b[j]);
j--;
if (j < 0)
{
j = N - 1;
}
}
}
for (int idx = 0; idx != negOnes.length; idx++)
{
int i = negOnes[idx];
int j = N - 1 - i;
for (int k = N - 1; k >= 0; k--)
{
c[k] = c[k].subtract(b[j]);
j--;
if (j < 0)
{
j = N - 1;
}
}
}
return new BigIntPolynomial(c);
}
public int[] getOnes()
{
return ones;
}
public int[] getNegOnes()
{
return negOnes;
}
/**
* Encodes the polynomial to a byte array writing <code>BITS_PER_INDEX</code> bits for each coefficient.
*
* @return the encoded polynomial
*/
public byte[] toBinary()
{
int maxIndex = 1 << BITS_PER_INDEX;
byte[] bin1 = ArrayEncoder.encodeModQ(ones, maxIndex);
byte[] bin2 = ArrayEncoder.encodeModQ(negOnes, maxIndex);
byte[] bin = Arrays.copyOf(bin1, bin1.length + bin2.length);
System.arraycopy(bin2, 0, bin, bin1.length, bin2.length);
return bin;
}
public IntegerPolynomial toIntegerPolynomial()
{
int[] coeffs = new int[N];
for (int idx = 0; idx != ones.length; idx++)
{
int i = ones[idx];
coeffs[i] = 1;
}
for (int idx = 0; idx != negOnes.length; idx++)
{
int i = negOnes[idx];
coeffs[i] = -1;
}
return new IntegerPolynomial(coeffs);
}
public int size()
{
return N;
}
public void clear()
{
for (int i = 0; i < ones.length; i++)
{
ones[i] = 0;
}
for (int i = 0; i < negOnes.length; i++)
{
negOnes[i] = 0;
}
}
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + N;
result = prime * result + Arrays.hashCode(negOnes);
result = prime * result + Arrays.hashCode(ones);
return result;
}
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
SparseTernaryPolynomial other = (SparseTernaryPolynomial)obj;
if (N != other.N)
{
return false;
}
if (!Arrays.areEqual(negOnes, other.negOnes))
{
return false;
}
if (!Arrays.areEqual(ones, other.ones))
{
return false;
}
return true;
}
}
| |
/*
* Copyright 2001-2008 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.juddi.api.impl;
import java.rmi.RemoteException;
import java.util.List;
import java.util.UUID;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.juddi.api.util.InquiryQuery;
import org.apache.juddi.api.util.PublicationQuery;
import org.apache.juddi.api.util.QueryStatus;
import org.apache.juddi.config.AppConfig;
import org.apache.juddi.config.PersistenceManager;
import org.apache.juddi.config.Property;
import org.apache.juddi.mapping.MappingModelToApi;
import org.apache.juddi.model.TempKey;
import org.apache.juddi.query.util.FindQualifiers;
import org.apache.juddi.v3.error.ErrorMessage;
import org.apache.juddi.v3.error.InvalidKeyPassedException;
import org.apache.juddi.validation.ValidateInquiry;
import org.uddi.api_v3.BindingDetail;
import org.uddi.api_v3.BusinessDetail;
import org.uddi.api_v3.BusinessList;
import org.uddi.api_v3.FindBinding;
import org.uddi.api_v3.FindBusiness;
import org.uddi.api_v3.FindRelatedBusinesses;
import org.uddi.api_v3.FindService;
import org.uddi.api_v3.FindTModel;
import org.uddi.api_v3.GetBindingDetail;
import org.uddi.api_v3.GetBusinessDetail;
import org.uddi.api_v3.GetOperationalInfo;
import org.uddi.api_v3.GetServiceDetail;
import org.uddi.api_v3.GetTModelDetail;
import org.uddi.api_v3.OperationalInfos;
import org.uddi.api_v3.RelatedBusinessesList;
import org.uddi.api_v3.ServiceDetail;
import org.uddi.api_v3.ServiceList;
import org.uddi.api_v3.TModelDetail;
import org.uddi.api_v3.TModelList;
import org.uddi.v3_service.DispositionReportFaultMessage;
import org.uddi.v3_service.UDDIInquiryPortType;
/**
* This implements the UDDI v3 Inquiry API web service
* @author <a href="mailto:jfaath@apache.org">Jeff Faath</a>
*/
@WebService(serviceName="UDDIInquiryService",
endpointInterface="org.uddi.v3_service.UDDIInquiryPortType",
targetNamespace = "urn:uddi-org:v3_service")
public class UDDIInquiryImpl extends AuthenticatedService implements UDDIInquiryPortType {
private static Log log = LogFactory.getLog(UDDIInquiryImpl.class);
private UDDIServiceCounter serviceCounter;
public UDDIInquiryImpl() {
super();
serviceCounter = ServiceCounterLifecycleResource.getServiceCounter(UDDIInquiryImpl.class);
}
public BindingDetail findBinding(FindBinding body)
throws DispositionReportFaultMessage {
long startTime = System.currentTimeMillis();
try {
new ValidateInquiry(null).validateFindBinding(body);
} catch (DispositionReportFaultMessage drfm) {
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.FIND_BINDING, QueryStatus.FAILED, procTime);
throw drfm;
}
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (isAuthenticated())
this.getEntityPublisher(em, body.getAuthInfo());
org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers();
findQualifiers.mapApiFindQualifiers(body.getFindQualifiers());
List<?> keysFound = InquiryHelper.findBinding(body, findQualifiers, em);
if (keysFound!=null && keysFound.size() == 0) {
if (body.getServiceKey() != null) {
// Check that we were passed a valid serviceKey per
// 5.1.12.4 of the UDDI v3 spec
String serviceKey = body.getServiceKey();
org.apache.juddi.model.BusinessService modelBusinessService = null;
try {
modelBusinessService=em.find(org.apache.juddi.model.BusinessService.class, serviceKey);
} catch (ClassCastException e) {
logger.info("uh oh!", e);
}
if (modelBusinessService == null)
throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ServiceNotFound", serviceKey));
}
}
BindingDetail result = InquiryHelper.getBindingDetailFromKeys(body, findQualifiers, em, keysFound);
tx.rollback();
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.FIND_BINDING, QueryStatus.SUCCESS, procTime);
return result;
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}
public BusinessList findBusiness(FindBusiness body)
throws DispositionReportFaultMessage {
long startTime = System.currentTimeMillis();
try {
new ValidateInquiry(null).validateFindBusiness(body);
} catch (DispositionReportFaultMessage drfm) {
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.FIND_BUSINESS, QueryStatus.FAILED, procTime);
throw drfm;
}
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (isAuthenticated())
this.getEntityPublisher(em, body.getAuthInfo());
org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers();
findQualifiers.mapApiFindQualifiers(body.getFindQualifiers());
List<?> keysFound = InquiryHelper.findBusiness(body, findQualifiers, em);
BusinessList result = InquiryHelper.getBusinessListFromKeys(body, findQualifiers, em, keysFound);
tx.rollback();
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.FIND_BUSINESS, QueryStatus.SUCCESS, procTime);
return result;
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}
public RelatedBusinessesList findRelatedBusinesses(FindRelatedBusinesses body)
throws DispositionReportFaultMessage {
long startTime = System.currentTimeMillis();
try {
new ValidateInquiry(null).validateFindRelatedBusinesses(body, false);
} catch (DispositionReportFaultMessage drfm) {
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.FIND_RELATEDBUSINESSES, QueryStatus.FAILED, procTime);
throw drfm;
}
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (isAuthenticated())
this.getEntityPublisher(em, body.getAuthInfo());
// TODO: findQualifiers aren't really used for this call, except maybe for sorting. Sorting must be done in Java due to the retrieval method used. Right now
// no sorting is performed.
org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers();
findQualifiers.mapApiFindQualifiers(body.getFindQualifiers());
RelatedBusinessesList result = InquiryHelper.getRelatedBusinessesList(body, em);
tx.rollback();
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.FIND_RELATEDBUSINESSES, QueryStatus.SUCCESS, procTime);
return result;
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}
public ServiceList findService(FindService body)
throws DispositionReportFaultMessage {
long startTime = System.currentTimeMillis();
try {
new ValidateInquiry(null).validateFindService(body);
} catch (DispositionReportFaultMessage drfm) {
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.FIND_SERVICE, QueryStatus.FAILED, procTime);
throw drfm;
}
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (isAuthenticated())
this.getEntityPublisher(em, body.getAuthInfo());
org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers();
findQualifiers.mapApiFindQualifiers(body.getFindQualifiers());
List<?> keysFound = InquiryHelper.findService(body, findQualifiers, em);
if (keysFound.size() == 0) {
if (body.getBusinessKey() != null) {
// Check that we were passed a valid businessKey per
// 5.1.12.4 of the UDDI v3 spec
String businessKey = body.getBusinessKey();
org.apache.juddi.model.BusinessEntity modelBusinessEntity = null;
try {
modelBusinessEntity = em.find(org.apache.juddi.model.BusinessEntity.class, businessKey);
} catch (ClassCastException e) {}
if (modelBusinessEntity == null) {
throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", businessKey));
}
}
}
ServiceList result = InquiryHelper.getServiceListFromKeys(body, findQualifiers, em, keysFound);
tx.rollback();
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.FIND_SERVICE, QueryStatus.SUCCESS, procTime);
return result;
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}
public TModelList findTModel(FindTModel body)
throws DispositionReportFaultMessage {
long startTime = System.currentTimeMillis();
try {
new ValidateInquiry(null).validateFindTModel(body, false);
} catch (DispositionReportFaultMessage drfm) {
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.FIND_TMODEL, QueryStatus.FAILED, procTime);
throw drfm;
}
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (isAuthenticated())
this.getEntityPublisher(em, body.getAuthInfo());
org.apache.juddi.query.util.FindQualifiers findQualifiers = new org.apache.juddi.query.util.FindQualifiers();
findQualifiers.mapApiFindQualifiers(body.getFindQualifiers());
List<?> keysFound = InquiryHelper.findTModel(body, findQualifiers, em);
TModelList result = InquiryHelper.getTModelListFromKeys(body, findQualifiers, em, keysFound);
tx.rollback();
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.FIND_TMODEL, QueryStatus.SUCCESS, procTime);
return result;
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}
public BindingDetail getBindingDetail(GetBindingDetail body)
throws DispositionReportFaultMessage {
long startTime = System.currentTimeMillis();
try {
new ValidateInquiry(null).validateGetBindingDetail(body);
} catch (DispositionReportFaultMessage drfm) {
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.FIND_TMODEL, QueryStatus.FAILED, procTime);
throw drfm;
}
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (isAuthenticated())
this.getEntityPublisher(em, body.getAuthInfo());
BindingDetail result = new BindingDetail();
List<String> bindingKeyList = body.getBindingKey();
for (String bindingKey : bindingKeyList) {
org.apache.juddi.model.BindingTemplate modelBindingTemplate = null;
try {
modelBindingTemplate = em.find(org.apache.juddi.model.BindingTemplate.class, bindingKey);
} catch (ClassCastException e) {}
if (modelBindingTemplate == null)
throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BindingTemplateNotFound", bindingKey));
org.uddi.api_v3.BindingTemplate apiBindingTemplate = new org.uddi.api_v3.BindingTemplate();
MappingModelToApi.mapBindingTemplate(modelBindingTemplate, apiBindingTemplate);
result.getBindingTemplate().add(apiBindingTemplate);
}
tx.commit();
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.GET_BINDINGDETAIL, QueryStatus.SUCCESS, procTime);
return result;
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}
public BusinessDetail getBusinessDetail(GetBusinessDetail body)
throws DispositionReportFaultMessage {
long startTime = System.currentTimeMillis();
try {
new ValidateInquiry(null).validateGetBusinessDetail(body);
} catch (DispositionReportFaultMessage drfm) {
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.GET_BUSINESSDETAIL, QueryStatus.FAILED, procTime);
throw drfm;
}
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (isAuthenticated())
this.getEntityPublisher(em, body.getAuthInfo());
BusinessDetail result = new BusinessDetail();
List<String> businessKeyList = body.getBusinessKey();
for (String businessKey : businessKeyList) {
org.apache.juddi.model.BusinessEntity modelBusinessEntity = null;
try {
modelBusinessEntity = em.find(org.apache.juddi.model.BusinessEntity.class, businessKey);
} catch (ClassCastException e) {}
if (modelBusinessEntity == null)
throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.BusinessNotFound", businessKey));
org.uddi.api_v3.BusinessEntity apiBusinessEntity = new org.uddi.api_v3.BusinessEntity();
MappingModelToApi.mapBusinessEntity(modelBusinessEntity, apiBusinessEntity);
result.getBusinessEntity().add(apiBusinessEntity);
}
tx.commit();
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.GET_BUSINESSDETAIL, QueryStatus.SUCCESS, procTime);
return result;
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}
public OperationalInfos getOperationalInfo(GetOperationalInfo body)
throws DispositionReportFaultMessage {
long startTime = System.currentTimeMillis();
try {
new ValidateInquiry(null).validateGetOperationalInfo(body);
} catch (DispositionReportFaultMessage drfm) {
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.GET_OPERATIONALINFO, QueryStatus.FAILED, procTime);
throw drfm;
}
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (isAuthenticated())
this.getEntityPublisher(em, body.getAuthInfo());
OperationalInfos result = new OperationalInfos();
List<String> entityKeyList = body.getEntityKey();
for (String entityKey : entityKeyList) {
org.apache.juddi.model.UddiEntity modelUddiEntity = null;
try {
modelUddiEntity = em.find(org.apache.juddi.model.UddiEntity.class, entityKey);
} catch (ClassCastException e) {}
if (modelUddiEntity == null)
throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.EntityNotFound", entityKey));
org.uddi.api_v3.OperationalInfo apiOperationalInfo = new org.uddi.api_v3.OperationalInfo();
MappingModelToApi.mapOperationalInfo(modelUddiEntity, apiOperationalInfo);
result.getOperationalInfo().add(apiOperationalInfo);
}
tx.commit();
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.GET_OPERATIONALINFO, QueryStatus.SUCCESS, procTime);
return result;
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}
public ServiceDetail getServiceDetail(GetServiceDetail body)
throws DispositionReportFaultMessage {
long startTime = System.currentTimeMillis();
try {
new ValidateInquiry(null).validateGetServiceDetail(body);
} catch (DispositionReportFaultMessage drfm) {
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.GET_SERVICEDETAIL, QueryStatus.FAILED, procTime);
throw drfm;
}
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (isAuthenticated())
this.getEntityPublisher(em, body.getAuthInfo());
ServiceDetail result = new ServiceDetail();
List<String> serviceKeyList = body.getServiceKey();
for (String serviceKey : serviceKeyList) {
org.apache.juddi.model.BusinessService modelBusinessService = null;
try {
modelBusinessService = em.find(org.apache.juddi.model.BusinessService.class, serviceKey);
} catch (ClassCastException e){}
if (modelBusinessService == null)
throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.ServiceNotFound", serviceKey));
org.uddi.api_v3.BusinessService apiBusinessService = new org.uddi.api_v3.BusinessService();
MappingModelToApi.mapBusinessService(modelBusinessService, apiBusinessService);
result.getBusinessService().add(apiBusinessService);
}
tx.commit();
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.GET_SERVICEDETAIL, QueryStatus.SUCCESS, procTime);
return result;
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}
public TModelDetail getTModelDetail(GetTModelDetail body)
throws DispositionReportFaultMessage {
long startTime = System.currentTimeMillis();
try {
new ValidateInquiry(null).validateGetTModelDetail(body);
} catch (DispositionReportFaultMessage drfm) {
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.GET_TMODELDETAIL, QueryStatus.FAILED, procTime);
throw drfm;
}
EntityManager em = PersistenceManager.getEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
if (isAuthenticated())
this.getEntityPublisher(em, body.getAuthInfo());
TModelDetail result = new TModelDetail();
List<String> tmodelKeyList = body.getTModelKey();
for (String tmodelKey : tmodelKeyList) {
org.apache.juddi.model.Tmodel modelTModel = null;
try {
modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey);
} catch (ClassCastException e) {}
if (modelTModel == null)
throw new InvalidKeyPassedException(new ErrorMessage("errors.invalidkey.TModelNotFound", tmodelKey));
org.uddi.api_v3.TModel apiTModel = new org.uddi.api_v3.TModel();
MappingModelToApi.mapTModel(modelTModel, apiTModel);
result.getTModel().add(apiTModel);
}
tx.commit();
long procTime = System.currentTimeMillis() - startTime;
serviceCounter.update(InquiryQuery.GET_TMODELDETAIL, QueryStatus.SUCCESS, procTime);
return result;
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}
private boolean isAuthenticated() {
boolean result = false;
try {
result = AppConfig.getConfiguration().getBoolean(Property.JUDDI_AUTHENTICATE_INQUIRY);
} catch (ConfigurationException e) {
log.error("Configuration exception occurred retrieving: " + Property.JUDDI_AUTHENTICATE_INQUIRY, e);
}
return result;
}
}
| |
/*
* 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.search.sort;
import org.apache.lucene.search.SortField;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.cache.bitset.BitsetFilterCache;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.fielddata.IndexFieldDataCache;
import org.elasticsearch.index.mapper.ContentPath;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.Mapper.BuilderContext;
import org.elasticsearch.index.mapper.NumberFieldMapper;
import org.elasticsearch.index.mapper.ObjectMapper;
import org.elasticsearch.index.mapper.ObjectMapper.Nested;
import org.elasticsearch.index.query.IdsQueryBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.SearchModule;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.IndexSettingsModule;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.mockito.Mockito;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;
import static java.util.Collections.emptyList;
import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode;
public abstract class AbstractSortTestCase<T extends SortBuilder<T>> extends ESTestCase {
private static final int NUMBER_OF_TESTBUILDERS = 20;
protected static NamedWriteableRegistry namedWriteableRegistry;
private static NamedXContentRegistry xContentRegistry;
private static ScriptService scriptService;
@BeforeClass
public static void init() {
Settings baseSettings = Settings.builder()
.put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
.build();
Map<String, Function<Map<String, Object>, Object>> scripts = Collections.singletonMap("dummy", p -> null);
ScriptEngine engine = new MockScriptEngine(MockScriptEngine.NAME, scripts);
scriptService = new ScriptService(baseSettings, Collections.singletonMap(engine.getType(), engine), ScriptModule.CORE_CONTEXTS);
SearchModule searchModule = new SearchModule(Settings.EMPTY, false, emptyList());
namedWriteableRegistry = new NamedWriteableRegistry(searchModule.getNamedWriteables());
xContentRegistry = new NamedXContentRegistry(searchModule.getNamedXContents());
}
@AfterClass
public static void afterClass() throws Exception {
namedWriteableRegistry = null;
xContentRegistry = null;
scriptService = null;
}
/** Returns random sort that is put under test */
protected abstract T createTestItem();
/** Returns mutated version of original so the returned sort is different in terms of equals/hashcode */
protected abstract T mutate(T original) throws IOException;
/** Parse the sort from xContent. Just delegate to the SortBuilder's static fromXContent method. */
protected abstract T fromXContent(XContentParser parser, String fieldName) throws IOException;
/**
* Test that creates new sort from a random test sort and checks both for equality
*/
public void testFromXContent() throws IOException {
for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) {
T testItem = createTestItem();
XContentBuilder builder = XContentFactory.contentBuilder(randomFrom(XContentType.values()));
if (randomBoolean()) {
builder.prettyPrint();
}
testItem.toXContent(builder, ToXContent.EMPTY_PARAMS);
XContentBuilder shuffled = shuffleXContent(builder);
XContentParser itemParser = createParser(shuffled);
itemParser.nextToken();
/*
* filter out name of sort, or field name to sort on for element fieldSort
*/
itemParser.nextToken();
String elementName = itemParser.currentName();
itemParser.nextToken();
T parsedItem = fromXContent(itemParser, elementName);
assertNotSame(testItem, parsedItem);
assertEquals(testItem, parsedItem);
assertEquals(testItem.hashCode(), parsedItem.hashCode());
assertWarnings(testItem);
}
}
protected void assertWarnings(T testItem) {
// assert potential warnings based on the test sort configuration. Do nothing by default, subtests can overwrite
}
/**
* test that build() outputs a {@link SortField} that is similar to the one
* we would get when parsing the xContent the sort builder is rendering out
*/
public void testBuildSortField() throws IOException {
QueryShardContext mockShardContext = createMockShardContext();
for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) {
T sortBuilder = createTestItem();
SortFieldAndFormat sortField = sortBuilder.build(mockShardContext);
sortFieldAssertions(sortBuilder, sortField.field, sortField.format);
}
}
protected abstract void sortFieldAssertions(T builder, SortField sortField, DocValueFormat format) throws IOException;
/**
* Test serialization and deserialization of the test sort.
*/
public void testSerialization() throws IOException {
for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) {
T testsort = createTestItem();
T deserializedsort = copy(testsort);
assertEquals(testsort, deserializedsort);
assertEquals(testsort.hashCode(), deserializedsort.hashCode());
assertNotSame(testsort, deserializedsort);
}
}
/**
* Test equality and hashCode properties
*/
public void testEqualsAndHashcode() {
for (int runs = 0; runs < NUMBER_OF_TESTBUILDERS; runs++) {
checkEqualsAndHashCode(createTestItem(), this::copy, this::mutate);
}
}
protected QueryShardContext createMockShardContext() {
Index index = new Index(randomAlphaOfLengthBetween(1, 10), "_na_");
IndexSettings idxSettings = IndexSettingsModule.newIndexSettings(index,
Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build());
BitsetFilterCache bitsetFilterCache = new BitsetFilterCache(idxSettings, Mockito.mock(BitsetFilterCache.Listener.class));
BiFunction<MappedFieldType, String, IndexFieldData<?>> indexFieldDataLookup = (fieldType, fieldIndexName) -> {
IndexFieldData.Builder builder = fieldType.fielddataBuilder(fieldIndexName);
return builder.build(idxSettings, fieldType, new IndexFieldDataCache.None(), null, null);
};
return new QueryShardContext(0, idxSettings, bitsetFilterCache, indexFieldDataLookup, null, null, scriptService,
xContentRegistry(), namedWriteableRegistry, null, null, () -> randomNonNegativeLong(), null) {
@Override
public MappedFieldType fieldMapper(String name) {
return provideMappedFieldType(name);
}
@Override
public ObjectMapper getObjectMapper(String name) {
BuilderContext context = new BuilderContext(this.getIndexSettings().getSettings(), new ContentPath());
return new ObjectMapper.Builder<>(name).nested(Nested.newNested(false, false)).build(context);
}
};
}
/**
* Return a field type. We use {@link NumberFieldMapper.NumberFieldType} by default since it is compatible with all sort modes
* Tests that require other field types can override this.
*/
protected MappedFieldType provideMappedFieldType(String name) {
NumberFieldMapper.NumberFieldType doubleFieldType = new NumberFieldMapper.NumberFieldType(NumberFieldMapper.NumberType.DOUBLE);
doubleFieldType.setName(name);
doubleFieldType.setHasDocValues(true);
return doubleFieldType;
}
@Override
protected NamedXContentRegistry xContentRegistry() {
return xContentRegistry;
}
protected static QueryBuilder randomNestedFilter() {
int id = randomIntBetween(0, 2);
switch(id) {
case 0: return (new MatchAllQueryBuilder()).boost(randomFloat());
case 1: return (new IdsQueryBuilder()).boost(randomFloat());
case 2: return (new TermQueryBuilder(
randomAlphaOfLengthBetween(1, 10),
randomDouble()).boost(randomFloat()));
default: throw new IllegalStateException("Only three query builders supported for testing sort");
}
}
@SuppressWarnings("unchecked")
private T copy(T original) throws IOException {
/* The cast below is required to make Java 9 happy. Java 8 infers the T in copyWriterable to be the same as AbstractSortTestCase's
* T but Java 9 infers it to be SortBuilder. */
return (T) copyWriteable(original, namedWriteableRegistry,
namedWriteableRegistry.getReader(SortBuilder.class, original.getWriteableName()));
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.management.internal.cli.shell;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import jline.Terminal;
import jline.console.ConsoleReader;
import org.springframework.shell.core.AbstractShell;
import org.springframework.shell.core.ExecutionStrategy;
import org.springframework.shell.core.ExitShellRequest;
import org.springframework.shell.core.JLineLogHandler;
import org.springframework.shell.core.JLineShell;
import org.springframework.shell.core.Parser;
import org.springframework.shell.event.ShellStatus.Status;
import org.apache.geode.internal.Banner;
import org.apache.geode.internal.GemFireVersion;
import org.apache.geode.internal.lang.ClassUtils;
import org.apache.geode.internal.process.signal.AbstractSignalNotificationHandler;
import org.apache.geode.internal.util.ArgumentRedactor;
import org.apache.geode.internal.util.HostName;
import org.apache.geode.internal.util.SunAPINotFoundException;
import org.apache.geode.management.cli.CommandProcessingException;
import org.apache.geode.management.cli.Result;
import org.apache.geode.management.internal.cli.CliUtil;
import org.apache.geode.management.internal.cli.CommandManager;
import org.apache.geode.management.internal.cli.GfshParser;
import org.apache.geode.management.internal.cli.LogWrapper;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
import org.apache.geode.management.internal.cli.result.CommandResult;
import org.apache.geode.management.internal.cli.result.ResultBuilder;
import org.apache.geode.management.internal.cli.shell.jline.ANSIHandler;
import org.apache.geode.management.internal.cli.shell.jline.ANSIHandler.ANSIStyle;
import org.apache.geode.management.internal.cli.shell.jline.GfshHistory;
import org.apache.geode.management.internal.cli.shell.jline.GfshUnsupportedTerminal;
import org.apache.geode.management.internal.cli.shell.unsafe.GfshSignalHandler;
import org.apache.geode.management.internal.cli.util.CommentSkipHelper;
/**
* Extends an interactive shell provided by
* <a href="https://github.com/SpringSource/spring-shell">Spring Shell</a> library.
*
* <p>
* This class is used to plug-in implementations of the following Spring (Roo) Shell components
* customized to suite GemFire Command Line Interface (CLI) requirements:
* <ul>
* <li><code>org.springframework.roo.shell.ExecutionStrategy</code>
* <li><code>org.springframework.roo.shell.Parser</code>
* </ul>
* <p />
* Additionally, this class is used to maintain GemFire SHell (gfsh) specific information like:
* environment
*
* <p>
* Additionally, this class is used to maintain GemFire SHell (gfsh) specific information
*
* @since GemFire 7.0
*/
public class Gfsh extends JLineShell {
public static final int DEFAULT_APP_FETCH_SIZE = 100;
public static final int DEFAULT_APP_LAST_EXIT_STATUS = 0;
public static final int DEFAULT_APP_COLLECTION_LIMIT = 20;
public static final boolean DEFAULT_APP_QUIET_EXECUTION = false;
public static final String DEFAULT_APP_QUERY_RESULTS_DISPLAY_MODE = "table";
public static final String DEFAULT_APP_RESULT_VIEWER = "basic";
public static final String EXTERNAL_RESULT_VIEWER = "external";
public static final String GFSH_APP_NAME = "gfsh";
public static final String LINE_INDENT = " ";
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
// Default Window dimensions
public static final int DEFAULT_WIDTH = 100;
public static final String ENV_APP_NAME = "APP_NAME";
public static final String ENV_APP_CONTEXT_PATH = "APP_CONTEXT_PATH";
public static final String ENV_APP_FETCH_SIZE = "APP_FETCH_SIZE";
public static final String ENV_APP_LAST_EXIT_STATUS = "APP_LAST_EXIT_STATUS";
public static final String ENV_APP_COLLECTION_LIMIT = "APP_COLLECTION_LIMIT";
public static final String ENV_APP_QUERY_RESULTS_DISPLAY_MODE = "APP_QUERY_RESULTS_DISPLAY_MODE";
public static final String ENV_APP_QUIET_EXECUTION = "APP_QUIET_EXECUTION";
public static final String ENV_APP_LOGGING_ENABLED = "APP_LOGGING_ENABLED";
public static final String ENV_APP_LOG_FILE = "APP_LOG_FILE";
public static final String ENV_APP_PWD = "APP_PWD";
public static final String ENV_APP_RESULT_VIEWER = "APP_RESULT_VIEWER";
// Environment Properties taken from the OS
public static final String ENV_SYS_USER = "SYS_USER";
public static final String ENV_SYS_USER_HOME = "SYS_USER_HOME";
public static final String ENV_SYS_HOST_NAME = "SYS_HOST_NAME";
public static final String ENV_SYS_CLASSPATH = "SYS_CLASSPATH";
public static final String ENV_SYS_JAVA_VERSION = "SYS_JAVA_VERSION";
public static final String ENV_SYS_OS = "SYS_OS";
public static final String ENV_SYS_OS_LINE_SEPARATOR = "SYS_OS_LINE_SEPARATOR";
public static final String ENV_SYS_GEODE_HOME_DIR = "SYS_GEODE_HOME_DIR";
private static final String DEFAULT_SECONDARY_PROMPT = ">";
private static final int DEFAULT_HEIGHT = 100;
private static final Object INSTANCE_LOCK = new Object();
protected static PrintStream gfshout = System.out;
protected static PrintStream gfsherr = System.err;
protected static ThreadLocal<Gfsh> gfshThreadLocal = new ThreadLocal<>();
private static Gfsh instance;
// This flag is used to restrict column trimming to table only types
private static ThreadLocal<Boolean> resultTypeTL = new ThreadLocal<>();
private static String OS = System.getProperty("os.name").toLowerCase();
private final Map<String, String> env = new TreeMap<>();
private final List<String> readonlyAppEnv = new ArrayList<>();
// Map to keep reference to actual user specified Command String
// Should always have one value at the max
private final Map<String, String> expandedPropCommandsMap = new HashMap<>();
private final ExecutionStrategy executionStrategy;
private final GfshParser parser;
private final LogWrapper gfshFileLogger;
private final GfshConfig gfshConfig;
private final GfshHistory gfshHistory;
private final ANSIHandler ansiHandler;
private final boolean isHeadlessMode;
private OperationInvoker operationInvoker;
private int lastExecutionStatus;
private Thread runner;
private boolean debugON;
private Terminal terminal;
private boolean suppressScriptCmdOutput;
private boolean isScriptRunning;
private AbstractSignalNotificationHandler signalHandler;
public Gfsh() {
this(null);
}
/**
* Create a GemFire shell with console using the specified arguments.
*
* @param args arguments to be used to create a GemFire shell instance
* @throws IOException
* @throws ClassNotFoundException
*/
protected Gfsh(String[] args) {
this(true, args, new GfshConfig());
}
/**
* Create a GemFire shell using the specified arguments. Console for user inputs is made available
* if <code>launchShell</code> is set to <code>true</code>.
*
* @param launchShell whether to make Console available
* @param args arguments to be used to create a GemFire shell instance or execute command
* @throws IOException
* @throws ClassNotFoundException
*/
protected Gfsh(boolean launchShell, String[] args, GfshConfig gfshConfig) {
// 1. Disable suppressing of duplicate messages
JLineLogHandler.setSuppressDuplicateMessages(false);
// 2. set & use gfshConfig
this.gfshConfig = gfshConfig;
this.gfshFileLogger = LogWrapper.getInstance();
this.gfshFileLogger.configure(this.gfshConfig);
this.ansiHandler = ANSIHandler.getInstance(this.gfshConfig.isANSISupported());
/* 3. log system properties & gfsh environment */
this.gfshFileLogger.info(Banner.getString(args));
// 4. Customized History implementation
this.gfshHistory = new GfshHistory();
// 6. Set System Environment here
initializeEnvironment();
// 7. Create Roo/SpringShell framework objects
this.executionStrategy = new GfshExecutionStrategy(this);
this.parser = new GfshParser(new CommandManager());
// 8. Set max History file size
setHistorySize(gfshConfig.getHistorySize());
String envProps = env.toString();
envProps = envProps.substring(1, envProps.length() - 1);
envProps = envProps.replaceAll(",", LINE_SEPARATOR);
this.gfshFileLogger.config("***** gfsh Environment ******" + LINE_SEPARATOR + envProps);
if (this.gfshFileLogger.fineEnabled()) {
String gfshConfigStr = this.gfshConfig.toString();
gfshConfigStr = gfshConfigStr.substring(0, gfshConfigStr.length() - 1);
gfshConfigStr = gfshConfigStr.replaceAll(",", LINE_SEPARATOR);
this.gfshFileLogger.fine("***** gfsh Configuration ******" + LINE_SEPARATOR + gfshConfigStr);
}
// Setup signal handler for various signals (such as CTRL-C)...
try {
ClassUtils.forName("sun.misc.Signal", new SunAPINotFoundException(
"WARNING!!! Not running a Sun JVM. Could not find the sun.misc.Signal class; Signal handling disabled."));
signalHandler = new GfshSignalHandler();
} catch (SunAPINotFoundException e) {
signalHandler = new AbstractSignalNotificationHandler() {};
this.gfshFileLogger.warning(e.getMessage());
}
// For test code only
if (this.gfshConfig.isTestConfig()) {
instance = this;
}
this.isHeadlessMode = !launchShell;
if (this.isHeadlessMode) {
this.gfshFileLogger.config("Running in headless mode");
// disable jline terminal
System.setProperty("jline.terminal", GfshUnsupportedTerminal.class.getName());
env.put(ENV_APP_QUIET_EXECUTION, String.valueOf(true));
// Only in headless mode, we do not want Gfsh's logger logs on screen
LogWrapper.getInstance().setParentFor(logger);
}
// we want to direct internal JDK logging to file in either mode
redirectInternalJavaLoggers();
}
public static Gfsh getInstance(boolean launchShell, String[] args, GfshConfig gfshConfig) {
if (instance == null) {
synchronized (INSTANCE_LOCK) {
if (instance == null) {
instance = new Gfsh(launchShell, args, gfshConfig);
instance.executeInitFileIfPresent();
}
}
}
return instance;
}
public static boolean isInfoResult() {
if (resultTypeTL.get() == null) {
return false;
}
return resultTypeTL.get();
}
public static void println() {
gfshout.println();
}
public static <T> void println(T toPrint) {
gfshout.println(toPrint);
}
public static <T> void print(T toPrint) {
gfshout.print(toPrint);
}
public static <T> void printlnErr(T toPrint) {
gfsherr.println(toPrint);
}
// See 46369
private static String readLine(ConsoleReader reader, String prompt) throws IOException {
String earlierLine = reader.getCursorBuffer().toString();
String readLine;
try {
readLine = reader.readLine(prompt);
} catch (IndexOutOfBoundsException e) {
if (earlierLine.length() == 0) {
reader.println();
readLine = LINE_SEPARATOR;
reader.getCursorBuffer().cursor = 0;
} else {
readLine = readLine(reader, prompt);
}
}
return readLine;
}
private static String removeBackslash(String result) {
if (result.endsWith(GfshParser.CONTINUATION_CHARACTER)) {
result = result.substring(0, result.length() - 1);
}
return result;
}
/**
* This method sets the parent of all loggers whose name starts with "java" or "javax" to
* LogWrapper.
*
* logWrapper disables any parents's log handler, and only logs to the file if specified. This
* would prevent JDK's logging show up in the console
*/
public static void redirectInternalJavaLoggers() {
// Do we need to this on re-connect?
LogManager logManager = LogManager.getLogManager();
try {
Enumeration<String> loggerNames = logManager.getLoggerNames();
while (loggerNames.hasMoreElements()) {
String loggerName = loggerNames.nextElement();
if (loggerName.startsWith("java.") || loggerName.startsWith("javax.")) {
Logger javaLogger = logManager.getLogger(loggerName);
/*
* From Java Docs: It is also important to note that the Logger associated with the String
* name may be garbage collected at any time if there is no strong reference to the
* Logger. The caller of this method must check the return value for null in order to
* properly handle the case where the Logger has been garbage collected.
*/
if (javaLogger != null) {
LogWrapper.getInstance().setParentFor(javaLogger);
}
}
}
} catch (SecurityException e) {
LogWrapper.getInstance().warning(e.getMessage(), e);
}
}
public static Gfsh getCurrentInstance() {
return instance;
}
private static String extractKey(String input) {
return input.substring("${".length(), input.length() - "}".length());
}
public static ConsoleReader getConsoleReader() {
Gfsh gfsh = Gfsh.getCurrentInstance();
return (gfsh == null ? null : gfsh.reader);
}
/**
* Take a string and wrap it into multiple lines separated by CliConstants.LINE_SEPARATOR. Lines
* are separated based upon the terminal width, separated on word boundaries and may have extra
* spaces added to provide indentation.
*
* For example: if the terminal width were 5 and the string "123 456789 01234" were passed in with
* an indentation level of 2, then the returned string would be:
*
* <pre>
* 123
* 45678
* 9
* 01234
* </pre>
*
* @param string String to wrap (add breakpoints and indent)
* @param indentationLevel The number of indentation levels to use.
* @return The wrapped string.
*/
public static String wrapText(final String string, final int indentationLevel,
final int terminalWidth) {
if (terminalWidth <= 1) {
return string;
}
final int maxLineLength = terminalWidth - 1;
final StringBuffer stringBuf = new StringBuffer();
int index = 0;
int startOfCurrentLine = 0;
while (index < string.length()) {
// Add the indentation
for (int i = 0; i < indentationLevel; i++) {
stringBuf.append(LINE_INDENT);
}
int currentLineLength = LINE_INDENT.length() * indentationLevel;
// Find the end of a line:
// 1. If the end of string is reached
// 2. If the width of the terminal has been reached
// 3. If a newline character was found in the string
while (index < string.length() && currentLineLength < maxLineLength
&& string.charAt(index) != '\n') {
index++;
currentLineLength++;
}
// If the line was terminated with a newline character
if (index != string.length() && string.charAt(index) == '\n') {
stringBuf.append(string.substring(startOfCurrentLine, index));
stringBuf.append(LINE_SEPARATOR);
index++;
startOfCurrentLine = index;
// If the end of the string was reached or the last character just happened to be a space
// character
} else if (index == string.length() || string.charAt(index) == ' ') {
stringBuf.append(string.substring(startOfCurrentLine, index));
if (index != string.length()) {
stringBuf.append(LINE_SEPARATOR);
index++;
}
} else {
final int spaceCharIndex = string.lastIndexOf(" ", index);
// If no spaces were found then there's no logical way to split the string
if (spaceCharIndex == -1) {
stringBuf.append(string.substring(startOfCurrentLine, index)).append(LINE_SEPARATOR);
// Else split the string cleanly between words
} else {
stringBuf.append(string.substring(startOfCurrentLine, spaceCharIndex))
.append(LINE_SEPARATOR);
index = spaceCharIndex + 1;
}
}
startOfCurrentLine = index;
}
return stringBuf.toString();
}
/**
* Initializes default environment variables to default values
*/
private void initializeEnvironment() {
env.put(ENV_SYS_USER, System.getProperty("user.name"));
env.put(ENV_SYS_USER_HOME, System.getProperty("user.home"));
env.put(ENV_SYS_HOST_NAME, new HostName().determineHostName());
env.put(ENV_SYS_CLASSPATH, System.getProperty("java.class.path"));
env.put(ENV_SYS_JAVA_VERSION, System.getProperty("java.version"));
env.put(ENV_SYS_OS, System.getProperty("os.name"));
env.put(ENV_SYS_OS_LINE_SEPARATOR, System.getProperty("line.separator"));
env.put(ENV_SYS_GEODE_HOME_DIR, System.getenv("GEODE_HOME"));
env.put(ENV_APP_NAME, Gfsh.GFSH_APP_NAME);
readonlyAppEnv.add(ENV_APP_NAME);
env.put(ENV_APP_LOGGING_ENABLED,
String.valueOf(!Level.OFF.equals(this.gfshConfig.getLogLevel())));
readonlyAppEnv.add(ENV_APP_LOGGING_ENABLED);
env.put(ENV_APP_LOG_FILE, this.gfshConfig.getLogFilePath());
readonlyAppEnv.add(ENV_APP_LOG_FILE);
env.put(ENV_APP_PWD, System.getProperty("user.dir"));
readonlyAppEnv.add(ENV_APP_PWD);
env.put(ENV_APP_FETCH_SIZE, String.valueOf(DEFAULT_APP_FETCH_SIZE));
env.put(ENV_APP_LAST_EXIT_STATUS, String.valueOf(DEFAULT_APP_LAST_EXIT_STATUS));
readonlyAppEnv.add(ENV_APP_LAST_EXIT_STATUS);
env.put(ENV_APP_COLLECTION_LIMIT, String.valueOf(DEFAULT_APP_COLLECTION_LIMIT));
env.put(ENV_APP_QUERY_RESULTS_DISPLAY_MODE, DEFAULT_APP_QUERY_RESULTS_DISPLAY_MODE);
env.put(ENV_APP_QUIET_EXECUTION, String.valueOf(DEFAULT_APP_QUIET_EXECUTION));
env.put(ENV_APP_RESULT_VIEWER, String.valueOf(DEFAULT_APP_RESULT_VIEWER));
}
public AbstractSignalNotificationHandler getSignalHandler() {
return signalHandler;
}
public String readPassword(String textToPrompt) {
if (isHeadlessMode && isQuietMode())
return null;
return readWithMask(textToPrompt, '*');
}
public String readText(String textToPrompt) {
if (isHeadlessMode && isQuietMode())
return null;
return interact(textToPrompt);
}
/**
* Starts this GemFire Shell with console.
*/
public void start() {
runner = new Thread(this, getShellName());
runner.start();
}
protected String getShellName() {
return "Gfsh Launcher";
}
/**
* Stops this GemFire Shell.
*/
public void stop() {
closeShell();
LogWrapper.close();
if (operationInvoker != null && operationInvoker.isConnected()) {
operationInvoker.stop();
}
instance = null;
}
public void waitForComplete() throws InterruptedException {
runner.join();
}
/*
* If an init file is provided, as a system property or in the default location, run it as a
* command script.
*/
private void executeInitFileIfPresent() {
String initFileName = this.gfshConfig.getInitFileName();
if (initFileName != null) {
this.gfshFileLogger.info("Using " + initFileName);
try {
File gfshInitFile = new File(initFileName);
boolean continueOnError = false;
this.executeScript(gfshInitFile, isQuietMode(), continueOnError);
} catch (Exception exception) {
this.gfshFileLogger.severe(initFileName, exception);
setLastExecutionStatus(-1);
}
}
}
/**
* See findResources in {@link AbstractShell}
*/
protected Collection<URL> findResources(String resourceName) {
return null;
}
/**
* Returns the {@link ExecutionStrategy} implementation used by this implementation of
* {@link AbstractShell}. {@link Gfsh} uses {@link GfshExecutionStrategy}.
*
* @return ExecutionStrategy used by Gfsh
*/
@Override
protected ExecutionStrategy getExecutionStrategy() {
return executionStrategy;
}
/**
* Returns the {@link Parser} implementation used by this implementation of
* {@link AbstractShell}.{@link Gfsh} uses {@link GfshParser}.
*
* @return Parser used by Gfsh
*/
@Override
public Parser getParser() {
return parser;
}
public GfshParser getGfshParser() {
return parser;
}
/**
* Executes the given command string. We have over-ridden the behavior to extend the original
* implementation to store the 'last command execution status'.
*
* @param line command string to be executed
* @return true if execution is successful; false otherwise
*/
@Override
public boolean executeScriptLine(final String line) {
boolean success = false;
String withPropsExpanded = line;
try {
// expand env property if the string contains $
if (line.contains("$")) {
withPropsExpanded = expandProperties(line);
}
String logMessage = "Command String to execute .. ";
if (!line.equals(withPropsExpanded)) {
if (!isQuietMode()) {
Gfsh.println("Post substitution: " + withPropsExpanded);
}
logMessage = "Command String after substitution : ";
expandedPropCommandsMap.put(withPropsExpanded, line);
}
if (gfshFileLogger.fineEnabled()) {
gfshFileLogger.fine(logMessage + ArgumentRedactor.redact(withPropsExpanded));
}
success = super.executeScriptLine(withPropsExpanded);
} catch (Exception e) {
setLastExecutionStatus(-1);
} finally { // Add all commands to in-memory GfshHistory
gfshHistory.setAutoFlush(true);
gfshHistory.addToHistory(line);
gfshHistory.setAutoFlush(false);
// clear the map
expandedPropCommandsMap.clear();
}
return success;
}
public String interact(String textToPrompt) {
try {
return reader.readLine(textToPrompt);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String readWithMask(String textToPrompt, Character mask) {
try {
return reader.readLine(textToPrompt, mask);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void printBannerAndWelcome() {
printAsInfo(getBanner());
printAsInfo(getWelcomeMessage());
}
public String getBanner() {
StringBuilder sb = new StringBuilder();
sb.append(" _________________________ __").append(LINE_SEPARATOR);
sb.append(" / _____/ ______/ ______/ /____/ /").append(LINE_SEPARATOR);
sb.append(" / / __/ /___ /_____ / _____ / ").append(LINE_SEPARATOR);
sb.append(" / /__/ / ____/ _____/ / / / / ").append(LINE_SEPARATOR);
sb.append("/______/_/ /______/_/ /_/ ").append(" ").append(this.getVersion())
.append(LINE_SEPARATOR);
return ansiHandler.decorateString(sb.toString(), ANSIStyle.BLUE);
}
@Override
protected String getProductName() {
return "gfsh";
}
@Override
public String getVersion() {
return getVersion(false);
}
public String getVersion(boolean full) {
if (full) {
return GemFireVersion.asString();
} else {
return GemFireVersion.getGemFireVersion();
}
}
public String getWelcomeMessage() {
return ansiHandler.decorateString("Monitor and Manage " + GemFireVersion.getProductName(),
ANSIStyle.CYAN);
}
// Over-ridden to avoid default behavior which is:
// For Iterable: go through all elements & call toString
// For others: call toString
@Override
protected void handleExecutionResult(Object result) {
try {
if (result instanceof Result) {
Result commandResult = (Result) result;
boolean isError = Result.Status.ERROR.equals(commandResult.getStatus());
if (isError) {
setLastExecutionStatus(-2);
} else {
setLastExecutionStatus(0);
}
if (useExternalViewer(commandResult)) {
// - Save file and pass to less so that viewer can scroll through
// results
CliUtil.runLessCommandAsExternalViewer(commandResult, isError);
} else {
if (!isScriptRunning) {
// Normal Command
while (commandResult.hasNextLine()) {
write(commandResult.nextLine(), isError);
}
} else if (!suppressScriptCmdOutput) {
// Command is part of script. Show output only when quite=false
while (commandResult.hasNextLine()) {
write(commandResult.nextLine(), isError);
}
}
}
resultTypeTL.set(null);
if (result instanceof CommandResult) {
CommandResult cmdResult = (CommandResult) result;
if (cmdResult.hasIncomingFiles()) {
boolean isAlreadySaved = cmdResult.getNumTimesSaved() > 0;
if (!isAlreadySaved) {
cmdResult.saveIncomingFiles(null);
}
Gfsh.println();// Empty line
}
}
}
if (result != null && !(result instanceof Result)) {
printAsInfo(result.toString());
}
} catch (Exception e) {
printAsWarning(e.getMessage());
logToFile(e.getMessage(), e);
}
}
private boolean useExternalViewer(Result result) {
boolean flag =
EXTERNAL_RESULT_VIEWER.equals(getEnvProperty(Gfsh.ENV_APP_RESULT_VIEWER)) && isUnix();
if (result instanceof CommandResult) {
CommandResult commandResult = (CommandResult) result;
resultTypeTL.set(commandResult.getType().equals("info"));
return flag && !commandResult.getType().equals("info");
} else
return false;
}
private boolean isUnix() {
return !(OS.contains("win"));
}
private void write(String message, boolean isError) {
if (isError) {
printAsWarning(message);
} else {
Gfsh.println(message);
}
}
@Override
protected ConsoleReader createConsoleReader() {
ConsoleReader consoleReader = super.createConsoleReader();
consoleReader.setHistory(gfshHistory);
terminal = consoleReader.getTerminal();
return consoleReader;
}
@Override
protected void logCommandToOutput(String processedLine) {
String originalString = expandedPropCommandsMap.get(processedLine);
if (originalString != null) {
// In history log the original command string & expanded line as a comment
super.logCommandToOutput(GfshHistory.redact(originalString));
super.logCommandToOutput(GfshHistory.redact("// Post substitution"));
super.logCommandToOutput(GfshHistory.redact("//" + processedLine));
} else {
super.logCommandToOutput(GfshHistory.redact(processedLine));
}
}
@Override
public String versionInfo() {
return getVersion();
}
public int getTerminalHeight() {
return terminal != null ? terminal.getHeight() : DEFAULT_HEIGHT;
}
public int getTerminalWidth() {
if (terminal != null) {
return terminal.getWidth();
}
Map<String, String> env = System.getenv();
String columnsFromEnv = env.get("COLUMNS");
if (columnsFromEnv != null) {
return Integer.parseInt(columnsFromEnv);
}
return DEFAULT_WIDTH;
}
/**
* @return the lastExecutionStatus
*/
public int getLastExecutionStatus() {
// APP_LAST_EXIT_STATUS
return lastExecutionStatus;
}
/**
* Set the last command execution status
*
* @param lastExecutionStatus last command execution status
*/
public void setLastExecutionStatus(int lastExecutionStatus) {
this.lastExecutionStatus = lastExecutionStatus;
env.put(ENV_APP_LAST_EXIT_STATUS, String.valueOf(lastExecutionStatus));
}
public void printAsInfo(String message) {
if (isHeadlessMode) {
println(message);
} else {
logger.info(message);
}
}
public void printAsWarning(String message) {
if (isHeadlessMode) {
printlnErr(message);
} else {
logger.warning(message);
}
}
public void printAsSevere(String message) {
if (isHeadlessMode) {
printlnErr(message);
} else {
logger.severe(message);
}
}
public void logInfo(String message, Throwable t) {
// No level enabled check for logger - it prints on console in colors as per level
if (debugON) {
logger.log(Level.INFO, message, t);
} else {
logger.info(message);
}
if (gfshFileLogger.infoEnabled()) {
gfshFileLogger.info(message, t);
}
}
public void logWarning(String message, Throwable t) {
// No level enabled check for logger - it prints on console in colors as per level
if (debugON) {
logger.log(Level.WARNING, message, t);
} else {
logger.warning(message);
}
if (gfshFileLogger.warningEnabled()) {
gfshFileLogger.warning(message, t);
}
}
public void logSevere(String message, Throwable t) {
// No level enabled check for logger - it prints on console in colors as per level
if (debugON) {
logger.log(Level.SEVERE, message, t);
} else {
logger.severe(message);
}
if (gfshFileLogger.severeEnabled()) {
gfshFileLogger.severe(message, t);
}
}
public boolean logToFile(String message, Throwable t) {
boolean loggedMessage = false;
if (gfshFileLogger != null) {
gfshFileLogger.info(message, t);
loggedMessage = true;
}
return loggedMessage;
}
public Result executeScript(File scriptFile, boolean quiet, boolean continueOnError) {
Result result;
String initialIsQuiet = getEnvProperty(ENV_APP_QUIET_EXECUTION);
try {
this.isScriptRunning = true;
if (scriptFile == null) {
throw new IllegalArgumentException("Given script file is null.");
} else if (!scriptFile.exists()) {
throw new IllegalArgumentException("Given script file does not exist.");
} else if (scriptFile.exists() && scriptFile.isDirectory()) {
throw new IllegalArgumentException(scriptFile.getPath() + " is a directory.");
}
ScriptExecutionDetails scriptInfo = new ScriptExecutionDetails(scriptFile.getPath());
if (scriptFile.exists()) {
setEnvProperty(ENV_APP_QUIET_EXECUTION, String.valueOf(quiet));
this.suppressScriptCmdOutput = quiet;
BufferedReader reader = new BufferedReader(new FileReader(scriptFile));
String lineRead = "";
StringBuilder linesBuffer = new StringBuilder();
String linesBufferString = "";
int commandSrNum = 0;
CommentSkipHelper commentSkipper = new CommentSkipHelper();
LINEREAD_LOOP: while (exitShellRequest == null && (lineRead = reader.readLine()) != null) {
if (linesBuffer == null) {
linesBuffer = new StringBuilder();
}
String lineWithoutComments = commentSkipper.skipComments(lineRead);
if (lineWithoutComments == null || lineWithoutComments.isEmpty()) {
continue;
}
if (linesBuffer.length() != 0) {// add " " between lines
linesBuffer.append(" ");
}
linesBuffer.append(lineWithoutComments);
linesBufferString = linesBuffer.toString();
// NOTE: Similar code is in promptLoop()
if (!linesBufferString.endsWith(GfshParser.CONTINUATION_CHARACTER)) { // see 45893
List<String> commandList = MultiCommandHelper.getMultipleCommands(linesBufferString);
for (String cmdLet : commandList) {
if (!cmdLet.isEmpty()) {
String redactedCmdLet = ArgumentRedactor.redact(cmdLet);
++commandSrNum;
Gfsh.println(commandSrNum + ". Executing - " + redactedCmdLet);
Gfsh.println();
boolean executeSuccess = executeScriptLine(cmdLet);
if (!executeSuccess) {
setLastExecutionStatus(-1);
}
scriptInfo.addCommandAndStatus(cmdLet,
getLastExecutionStatus() == -1 || getLastExecutionStatus() == -2 ? "FAILED"
: "PASSED");
if ((getLastExecutionStatus() == -1 || getLastExecutionStatus() == -2)
&& !continueOnError) {
break LINEREAD_LOOP;
}
}
}
// reset buffer
linesBuffer = null;
linesBufferString = null;
} else {
linesBuffer.deleteCharAt(linesBuffer.length() - 1);
}
}
reader.close();
} else {
throw new CommandProcessingException(scriptFile.getPath() + " doesn't exist.",
CommandProcessingException.ARGUMENT_INVALID, scriptFile);
}
result = scriptInfo.getResult();
scriptInfo.logScriptExecutionInfo(gfshFileLogger, result);
if (quiet) {
// Create empty result when in quiet mode
result = ResultBuilder.createInfoResult("");
}
} catch (IOException e) {
throw new CommandProcessingException("Error while reading file " + scriptFile,
CommandProcessingException.RESOURCE_ACCESS_ERROR, e);
} finally {
// reset to original Quiet Execution value
setEnvProperty(ENV_APP_QUIET_EXECUTION, initialIsQuiet);
this.isScriptRunning = false;
}
return result;
}
public String setEnvProperty(String propertyName, String propertyValue) {
if (propertyName == null || propertyValue == null) {
throw new IllegalArgumentException(
"Environment Property name and/or value can not be set to null.");
}
if (propertyName.startsWith("SYS") || readonlyAppEnv.contains(propertyName)) {
throw new IllegalArgumentException("The Property " + propertyName + " can not be modified.");
}
return env.put(propertyName, propertyValue);
}
public String getEnvProperty(String propertyName) {
return env.get(propertyName);
}
public String getEnvAppContextPath() {
String path = getEnvProperty(Gfsh.ENV_APP_CONTEXT_PATH);
if (path == null) {
return "";
}
return path;
}
public Map<String, String> getEnv() {
Map<String, String> map = new TreeMap<>();
map.putAll(env);
return map;
}
public boolean isQuietMode() {
return Boolean.parseBoolean(env.get(ENV_APP_QUIET_EXECUTION));
}
@Override
public void promptLoop() {
String line = null;
String prompt = getPromptText();
try {
gfshHistory.setAutoFlush(false);
// NOTE: Similar code is in executeScript()
while (exitShellRequest == null && (line = readLine(reader, prompt)) != null) {
if (!line.endsWith(GfshParser.CONTINUATION_CHARACTER)) { // see 45893
List<String> commandList = MultiCommandHelper.getMultipleCommands(line);
for (String cmdLet : commandList) {
String trimmedCommand = cmdLet.trim();
if (!trimmedCommand.isEmpty()) {
executeCommand(cmdLet);
}
}
prompt = getPromptText();
} else {
prompt = getDefaultSecondaryPrompt();
reader.getCursorBuffer().cursor = 0;
reader.getCursorBuffer().write(removeBackslash(line) + LINE_SEPARATOR);
}
}
if (line == null) {
// Possibly Ctrl-D was pressed on empty prompt. ConsoleReader.readLine
// returns null on Ctrl-D
this.exitShellRequest = ExitShellRequest.NORMAL_EXIT;
gfshFileLogger.info("Exiting gfsh, it seems Ctrl-D was pressed.");
}
} catch (IOException e) {
logSevere(e.getMessage(), e);
}
println((line == null ? LINE_SEPARATOR : "") + "Exiting... ");
setShellStatus(Status.SHUTTING_DOWN);
}
String getDefaultSecondaryPrompt() {
return ansiHandler.decorateString(DEFAULT_SECONDARY_PROMPT, ANSIStyle.YELLOW);
}
public boolean isConnectedAndReady() {
return operationInvoker != null && operationInvoker.isConnected() && operationInvoker.isReady();
}
public static boolean isCurrentInstanceConnectedAndReady() {
return (getCurrentInstance() != null && getCurrentInstance().isConnectedAndReady());
}
/**
* @return the operationInvoker
*/
public OperationInvoker getOperationInvoker() {
return operationInvoker;
}
/**
* @param operationInvoker the operationInvoker to set
*/
public void setOperationInvoker(final OperationInvoker operationInvoker) {
this.operationInvoker = operationInvoker;
}
public GfshConfig getGfshConfig() {
return this.gfshConfig;
}
@Override
protected String getHistoryFileName() {
return gfshConfig.getHistoryFileName();
}
public void clearHistory() {
gfshHistory.clear();
if (!gfshConfig.deleteHistoryFile()) {
printAsWarning("Gfsh history file is not deleted");
}
}
public String getLogFilePath() {
return gfshConfig.getLogFilePath();
}
public boolean isLoggingEnabled() {
return gfshConfig.isLoggingEnabled();
}
@Override
protected String getPromptText() {
String defaultPrompt = gfshConfig.getDefaultPrompt();
String contextPath = "";
String clusterString = "";
if (getOperationInvoker() != null && isConnectedAndReady()) {
int clusterId = getOperationInvoker().getClusterId();
if (clusterId != OperationInvoker.CLUSTER_ID_WHEN_NOT_CONNECTED) {
clusterString = "Cluster-" + clusterId + " ";
}
}
defaultPrompt = MessageFormat.format(defaultPrompt, clusterString, contextPath);
return ansiHandler.decorateString(defaultPrompt, ANSIStyle.YELLOW);
}
public void notifyDisconnect(String endPoints) {
String message =
CliStrings.format(CliStrings.GFSH__MSG__NO_LONGER_CONNECTED_TO_0, new Object[] {endPoints});
printAsSevere(LINE_SEPARATOR + message);
if (gfshFileLogger.severeEnabled()) {
gfshFileLogger.severe(message);
}
setPromptPath(getEnvAppContextPath());
}
public boolean getDebug() {
return debugON;
}
public void setDebug(boolean flag) {
debugON = flag;
}
public boolean isHeadlessMode() {
return isHeadlessMode;
}
public GfshHistory getGfshHistory() {
return gfshHistory;
}
private String expandProperties(final String input) {
String output = input;
Scanner s = new Scanner(output);
String foundInLine;
while ((foundInLine = s.findInLine("(\\$[\\{]\\w+[\\}])")) != null) {
String envProperty = getEnvProperty(extractKey(foundInLine));
envProperty = envProperty != null ? envProperty : "";
output = output.replace(foundInLine, envProperty);
}
return output;
}
}
| |
/*
* PBrtJ -- Port of pbrt v3 to Java.
* Copyright (c) 2017 Rick Weyrauch.
*
* pbrt source code is Copyright(c) 1998-2016
* Matt Pharr, Greg Humphreys, and Wenzel Jakob.
*
*/
package org.pbrt.core;
public class Vector3f {
// Vector3 Public Data
public float x, y, z;
public Vector3f() {
x = y = z = 0.0f;
}
public Vector3f(float xx, float yy, float zz) {
x = xx;
y = yy;
z = zz;
assert !HasNaNs();
}
public boolean HasNaNs() {
return Float.isNaN(x) || Float.isNaN(y) || Float.isNaN(z);
}
public Vector3f(Point3f p) {
x = p.x;
y = p.y;
z = p.z;
}
public Vector3f(Normal3f n) {
x = n.x;
y = n.y;
z = n.z;
}
public Vector3f(Vector3f v) {
x = v.x;
y = v.y;
z = v.z;
assert !HasNaNs();
}
public Vector3f add(Vector3f v) {
assert !v.HasNaNs();
return new Vector3f(x + v.x, y + v.y, z + v.z);
}
public Vector3f add(Normal3f n) {
assert !n.HasNaNs();
return new Vector3f(x + n.x, y + n.y, z + n.z);
}
public void increment(Vector3f v) {
assert !v.HasNaNs();
x += v.x;
y += v.y;
z += v.z;
}
public Vector3f subtract(Vector3f v) {
assert !v.HasNaNs();
return new Vector3f(x - v.x, y - v.y, z - v.z);
}
public boolean equal(Vector3f v) {
return x == v.x && y == v.y && z == v.z;
}
public boolean newEqual(Vector3f v) {
return x != v.x || y != v.y || z != v.z;
}
public Vector3f scale(float s) {
return new Vector3f(s * x, s * y, s * z);
}
public Vector3f invScale(float f) {
// assert (f != 0.0f);
float inv = 0;
if (f != 0)
inv = 1.0f / f;
return new Vector3f(x * inv, y * inv, z * inv);
}
public Vector3f negate() {
return new Vector3f(-x, -y, -z);
}
@Override
public String toString() {
return "[ " + this.x + ", " + this.y + ", " + this.z + " ]";
}
public float LengthSquared() {
return x * x + y * y + z * z;
}
public float Length() {
return (float)Math.sqrt(LengthSquared());
}
public float at(int i) {
assert (i >= 0 && i <= 2);
if (i == 0) return x;
if (i == 1) return y;
return z;
}
public static Vector3f Abs(Vector3f v) {
return new Vector3f(Math.abs(v.x), Math.abs(v.y), Math.abs(v.z));
}
public static float Dot(Vector3f v1, Vector3f v2) {
assert (!v1.HasNaNs() && !v2.HasNaNs());
return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z;
}
public static float AbsDot(Vector3f v1, Vector3f v2) {
assert (!v1.HasNaNs() && !v2.HasNaNs());
return Math.abs(Dot(v1, v2));
}
public static Vector3f Cross(Vector3f v1, Vector3f v2) {
assert (!v1.HasNaNs() && !v2.HasNaNs());
double v1x = v1.x, v1y = v1.y, v1z = v1.z;
double v2x = v2.x, v2y = v2.y, v2z = v2.z;
return new Vector3f((float)((v1y * v2z) - (v1z * v2y)), (float)((v1z * v2x) - (v1x * v2z)), (float)((v1x * v2y) - (v1y * v2x)));
}
public static Vector3f Cross(Vector3f v1, Normal3f v2) {
assert (!v1.HasNaNs() && !v2.HasNaNs());
double v1x = v1.x, v1y = v1.y, v1z = v1.z;
double v2x = v2.x, v2y = v2.y, v2z = v2.z;
return new Vector3f((float)((v1y * v2z) - (v1z * v2y)), (float)((v1z * v2x) - (v1x * v2z)), (float)((v1x * v2y) - (v1y * v2x)));
}
public static Vector3f Cross(Normal3f v1, Vector3f v2) {
assert (!v1.HasNaNs() && !v2.HasNaNs());
double v1x = v1.x, v1y = v1.y, v1z = v1.z;
double v2x = v2.x, v2y = v2.y, v2z = v2.z;
return new Vector3f((float)((v1y * v2z) - (v1z * v2y)), (float)((v1z * v2x) - (v1x * v2z)), (float)((v1x * v2y) - (v1y * v2x)));
}
public static Vector3f Normalize(Vector3f v) {
return v.invScale(v.Length());
}
public static float MinComponent(Vector3f v) {
return Math.min(v.x, Math.min(v.y, v.z));
}
public static float MaxComponent(Vector3f v) {
return Math.max(v.x, Math.max(v.y, v.z));
}
public static int MaxDimension(Vector3f v) {
return (v.x > v.y) ? ((v.x > v.z) ? 0 : 2) : ((v.y > v.z) ? 1 : 2);
}
public static Vector3f Min(Vector3f p1, Vector3f p2) {
return new Vector3f(Math.min(p1.x, p2.x), Math.min(p1.y, p2.y),
Math.min(p1.z, p2.z));
}
public static Vector3f Max(Vector3f p1, Vector3f p2) {
return new Vector3f(Math.max(p1.x, p2.x), Math.max(p1.y, p2.y),
Math.max(p1.z, p2.z));
}
public static Vector3f Permute(Vector3f v, int x, int y, int z) {
return new Vector3f(v.at(x), v.at(y), v.at(z));
}
public static class CoordSystem {
public Vector3f v1, v2, v3;
}
public static CoordSystem CoordinateSystem(Vector3f v1) {
CoordSystem coord = new CoordSystem();
coord.v1 = v1;
if (Math.abs(v1.x) > Math.abs(v1.y))
coord.v2 = new Vector3f(-v1.z, 0, v1.x).invScale((float)Math.sqrt(v1.x * v1.x + v1.z * v1.z));
else
coord.v2 = new Vector3f(0, v1.z, -v1.y).invScale((float)Math.sqrt(v1.y * v1.y + v1.z * v1.z));
coord.v3 = Cross(v1, coord.v2);
return coord;
}
public static Vector3f Faceforward(Vector3f v, Vector3f v2) {
return (Dot(v, v2) < 0) ? v.negate() : v;
}
public static Vector3f SphericalDirection(float sinTheta, float cosTheta, float phi) {
return new Vector3f(sinTheta * (float)Math.cos(phi), sinTheta * (float)Math.sin(phi), cosTheta);
}
public static Vector3f SphericalDirection(float sinTheta, float cosTheta, float phi, Vector3f x, Vector3f y, Vector3f z) {
return x.scale(sinTheta * (float)Math.cos(phi)).add(y.scale(sinTheta * (float)Math.sin(phi))).add(z.scale(cosTheta));
}
public static float SphericalTheta(Vector3f v) {
return (float)Math.acos(Pbrt.Clamp(v.z, -1, 1));
}
public static float SphericalPhi(Vector3f v) {
float p = (float)Math.atan2(v.y, v.x);
return (p < 0) ? (p + 2 * Pbrt.Pi) : p;
}
}
| |
/*
* 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.index.fielddata;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import com.carrotsearch.randomizedtesting.generators.RandomStrings;
import com.google.common.collect.Lists;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.*;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.English;
import org.apache.lucene.util.LuceneTestCase;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.unit.DistanceUnit.Distance;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.junit.Test;
import java.util.*;
import java.util.Map.Entry;
import static org.hamcrest.Matchers.*;
public class DuelFieldDataTests extends AbstractFieldDataTests {
@Override
protected FieldDataType getFieldDataType() {
return null;
}
@Test
public void testDuelAllTypesSingleValue() throws Exception {
final String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("bytes").field("type", "string").field("index", "not_analyzed").startObject("fielddata").field("format", LuceneTestCase.defaultCodecSupportsSortedSet() ? "doc_values" : "fst").endObject().endObject()
.startObject("byte").field("type", "byte").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("short").field("type", "short").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("integer").field("type", "integer").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("long").field("type", "long").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("float").field("type", "float").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("double").field("type", "double").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.endObject().endObject().endObject().string();
final DocumentMapper mapper = mapperService.documentMapperParser().parse(mapping);
Random random = getRandom();
int atLeast = scaledRandomIntBetween(1000, 1500);
for (int i = 0; i < atLeast; i++) {
String s = Integer.toString(randomByte());
XContentBuilder doc = XContentFactory.jsonBuilder().startObject();
for (String fieldName : Arrays.asList("bytes", "byte", "short", "integer", "long", "float", "double")) {
doc = doc.field(fieldName, s);
}
doc = doc.endObject();
final ParsedDocument d = mapper.parse("type", Integer.toString(i), doc.bytes());
writer.addDocument(d.rootDoc());
if (random.nextInt(10) == 0) {
refreshReader();
}
}
AtomicReaderContext context = refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<>();
typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "fst")), Type.Bytes);
typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "paged_bytes")), Type.Bytes);
typeMap.put(new FieldDataType("byte", ImmutableSettings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("short", ImmutableSettings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("int", ImmutableSettings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("long", ImmutableSettings.builder().put("format", "array")), Type.Long);
typeMap.put(new FieldDataType("double", ImmutableSettings.builder().put("format", "array")), Type.Double);
typeMap.put(new FieldDataType("float", ImmutableSettings.builder().put("format", "array")), Type.Float);
typeMap.put(new FieldDataType("byte", ImmutableSettings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("short", ImmutableSettings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("int", ImmutableSettings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("long", ImmutableSettings.builder().put("format", "doc_values")), Type.Long);
typeMap.put(new FieldDataType("double", ImmutableSettings.builder().put("format", "doc_values")), Type.Double);
typeMap.put(new FieldDataType("float", ImmutableSettings.builder().put("format", "doc_values")), Type.Float);
typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "doc_values")), Type.Bytes);
ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<>(typeMap.entrySet());
Preprocessor pre = new ToDoublePreprocessor();
while (!list.isEmpty()) {
Entry<FieldDataType, Type> left;
Entry<FieldDataType, Type> right;
if (list.size() > 1) {
left = list.remove(random.nextInt(list.size()));
right = list.remove(random.nextInt(list.size()));
} else {
right = left = list.remove(0);
}
ifdService.clear();
IndexFieldData<?> leftFieldData = getForField(left.getKey(), left.getValue().name().toLowerCase(Locale.ROOT));
ifdService.clear();
IndexFieldData<?> rightFieldData = getForField(right.getKey(), right.getValue().name().toLowerCase(Locale.ROOT));
duelFieldDataBytes(random, context, leftFieldData, rightFieldData, pre);
duelFieldDataBytes(random, context, rightFieldData, leftFieldData, pre);
DirectoryReader perSegment = DirectoryReader.open(writer, true);
CompositeReaderContext composite = perSegment.getContext();
List<AtomicReaderContext> leaves = composite.leaves();
for (AtomicReaderContext atomicReaderContext : leaves) {
duelFieldDataBytes(random, atomicReaderContext, leftFieldData, rightFieldData, pre);
}
}
}
@Test
public void testDuelIntegers() throws Exception {
final String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("byte").field("type", "byte").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("short").field("type", "short").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("integer").field("type", "integer").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("long").field("type", "long").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.endObject().endObject().endObject().string();
final DocumentMapper mapper = mapperService.documentMapperParser().parse(mapping);
Random random = getRandom();
int atLeast = scaledRandomIntBetween(1000, 1500);
final int maxNumValues = randomBoolean() ? 1 : randomIntBetween(2, 40);
byte[] values = new byte[maxNumValues];
for (int i = 0; i < atLeast; i++) {
int numValues = randomInt(maxNumValues);
// FD loses values if they are duplicated, so we must deduplicate for this test
Set<Byte> vals = new HashSet<Byte>();
for (int j = 0; j < numValues; ++j) {
vals.add(randomByte());
}
numValues = vals.size();
int upto = 0;
for (Byte bb : vals) {
values[upto++] = bb.byteValue();
}
XContentBuilder doc = XContentFactory.jsonBuilder().startObject();
for (String fieldName : Arrays.asList("byte", "short", "integer", "long")) {
doc = doc.startArray(fieldName);
for (int j = 0; j < numValues; ++j) {
doc = doc.value(values[j]);
}
doc = doc.endArray();
}
doc = doc.endObject();
final ParsedDocument d = mapper.parse("type", Integer.toString(i), doc.bytes());
writer.addDocument(d.rootDoc());
if (random.nextInt(10) == 0) {
refreshReader();
}
}
AtomicReaderContext context = refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<>();
typeMap.put(new FieldDataType("byte", ImmutableSettings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("short", ImmutableSettings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("int", ImmutableSettings.builder().put("format", "array")), Type.Integer);
typeMap.put(new FieldDataType("long", ImmutableSettings.builder().put("format", "array")), Type.Long);
typeMap.put(new FieldDataType("byte", ImmutableSettings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("short", ImmutableSettings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("int", ImmutableSettings.builder().put("format", "doc_values")), Type.Integer);
typeMap.put(new FieldDataType("long", ImmutableSettings.builder().put("format", "doc_values")), Type.Long);
ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<>(typeMap.entrySet());
while (!list.isEmpty()) {
Entry<FieldDataType, Type> left;
Entry<FieldDataType, Type> right;
if (list.size() > 1) {
left = list.remove(random.nextInt(list.size()));
right = list.remove(random.nextInt(list.size()));
} else {
right = left = list.remove(0);
}
ifdService.clear();
IndexNumericFieldData leftFieldData = getForField(left.getKey(), left.getValue().name().toLowerCase(Locale.ROOT));
ifdService.clear();
IndexNumericFieldData rightFieldData = getForField(right.getKey(), right.getValue().name().toLowerCase(Locale.ROOT));
duelFieldDataLong(random, context, leftFieldData, rightFieldData);
duelFieldDataLong(random, context, rightFieldData, leftFieldData);
DirectoryReader perSegment = DirectoryReader.open(writer, true);
CompositeReaderContext composite = perSegment.getContext();
List<AtomicReaderContext> leaves = composite.leaves();
for (AtomicReaderContext atomicReaderContext : leaves) {
duelFieldDataLong(random, atomicReaderContext, leftFieldData, rightFieldData);
}
}
}
@Test
public void testDuelDoubles() throws Exception {
final String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("float").field("type", "float").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.startObject("double").field("type", "double").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.endObject().endObject().endObject().string();
final DocumentMapper mapper = mapperService.documentMapperParser().parse(mapping);
Random random = getRandom();
int atLeast = scaledRandomIntBetween(1000, 1500);
final int maxNumValues = randomBoolean() ? 1 : randomIntBetween(2, 40);
float[] values = new float[maxNumValues];
for (int i = 0; i < atLeast; i++) {
int numValues = randomInt(maxNumValues);
float def = randomBoolean() ? randomFloat() : Float.NaN;
// FD loses values if they are duplicated, so we must deduplicate for this test
Set<Float> vals = new HashSet<Float>();
for (int j = 0; j < numValues; ++j) {
if (randomBoolean()) {
vals.add(def);
} else {
vals.add(randomFloat());
}
}
numValues = vals.size();
int upto = 0;
for (Float f : vals) {
values[upto++] = f.floatValue();
}
XContentBuilder doc = XContentFactory.jsonBuilder().startObject().startArray("float");
for (int j = 0; j < numValues; ++j) {
doc = doc.value(values[j]);
}
doc = doc.endArray().startArray("double");
for (int j = 0; j < numValues; ++j) {
doc = doc.value(values[j]);
}
doc = doc.endArray().endObject();
final ParsedDocument d = mapper.parse("type", Integer.toString(i), doc.bytes());
writer.addDocument(d.rootDoc());
if (random.nextInt(10) == 0) {
refreshReader();
}
}
AtomicReaderContext context = refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<>();
typeMap.put(new FieldDataType("double", ImmutableSettings.builder().put("format", "array")), Type.Double);
typeMap.put(new FieldDataType("float", ImmutableSettings.builder().put("format", "array")), Type.Float);
typeMap.put(new FieldDataType("double", ImmutableSettings.builder().put("format", "doc_values")), Type.Double);
typeMap.put(new FieldDataType("float", ImmutableSettings.builder().put("format", "doc_values")), Type.Float);
ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<>(typeMap.entrySet());
while (!list.isEmpty()) {
Entry<FieldDataType, Type> left;
Entry<FieldDataType, Type> right;
if (list.size() > 1) {
left = list.remove(random.nextInt(list.size()));
right = list.remove(random.nextInt(list.size()));
} else {
right = left = list.remove(0);
}
ifdService.clear();
IndexNumericFieldData leftFieldData = getForField(left.getKey(), left.getValue().name().toLowerCase(Locale.ROOT));
ifdService.clear();
IndexNumericFieldData rightFieldData = getForField(right.getKey(), right.getValue().name().toLowerCase(Locale.ROOT));
duelFieldDataDouble(random, context, leftFieldData, rightFieldData);
duelFieldDataDouble(random, context, rightFieldData, leftFieldData);
DirectoryReader perSegment = DirectoryReader.open(writer, true);
CompositeReaderContext composite = perSegment.getContext();
List<AtomicReaderContext> leaves = composite.leaves();
for (AtomicReaderContext atomicReaderContext : leaves) {
duelFieldDataDouble(random, atomicReaderContext, leftFieldData, rightFieldData);
}
}
}
@Test
public void testDuelStrings() throws Exception {
Random random = getRandom();
int atLeast = scaledRandomIntBetween(1000, 1500);
for (int i = 0; i < atLeast; i++) {
Document d = new Document();
d.add(new StringField("_id", "" + i, Field.Store.NO));
if (random.nextInt(15) != 0) {
int[] numbers = getNumbers(random, Integer.MAX_VALUE);
for (int j : numbers) {
final String s = English.longToEnglish(j);
d.add(new StringField("bytes", s, Field.Store.NO));
d.add(new SortedSetDocValuesField("bytes", new BytesRef(s)));
}
if (random.nextInt(10) == 0) {
d.add(new StringField("bytes", "", Field.Store.NO));
d.add(new SortedSetDocValuesField("bytes", new BytesRef()));
}
}
writer.addDocument(d);
if (random.nextInt(10) == 0) {
refreshReader();
}
}
AtomicReaderContext context = refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<>();
typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "fst")), Type.Bytes);
typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "paged_bytes")), Type.Bytes);
typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "doc_values")), Type.Bytes);
// TODO add filters
ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<>(typeMap.entrySet());
Preprocessor pre = new Preprocessor();
while (!list.isEmpty()) {
Entry<FieldDataType, Type> left;
Entry<FieldDataType, Type> right;
if (list.size() > 1) {
left = list.remove(random.nextInt(list.size()));
right = list.remove(random.nextInt(list.size()));
} else {
right = left = list.remove(0);
}
ifdService.clear();
IndexFieldData<?> leftFieldData = getForField(left.getKey(), left.getValue().name().toLowerCase(Locale.ROOT));
ifdService.clear();
IndexFieldData<?> rightFieldData = getForField(right.getKey(), right.getValue().name().toLowerCase(Locale.ROOT));
duelFieldDataBytes(random, context, leftFieldData, rightFieldData, pre);
duelFieldDataBytes(random, context, rightFieldData, leftFieldData, pre);
DirectoryReader perSegment = DirectoryReader.open(writer, true);
CompositeReaderContext composite = perSegment.getContext();
List<AtomicReaderContext> leaves = composite.leaves();
for (AtomicReaderContext atomicReaderContext : leaves) {
duelFieldDataBytes(random, atomicReaderContext, leftFieldData, rightFieldData, pre);
}
perSegment.close();
}
}
public void testDuelGlobalOrdinals() throws Exception {
Random random = getRandom();
final int numDocs = scaledRandomIntBetween(10, 1000);
final int numValues = scaledRandomIntBetween(10, 500);
final String[] values = new String[numValues];
for (int i = 0; i < numValues; ++i) {
values[i] = new String(RandomStrings.randomAsciiOfLength(random, 10));
}
for (int i = 0; i < numDocs; i++) {
Document d = new Document();
final int numVals = randomInt(3);
for (int j = 0; j < numVals; ++j) {
final String value = RandomPicks.randomFrom(random, Arrays.asList(values));
d.add(new StringField("string", value, Field.Store.NO));
d.add(new SortedSetDocValuesField("bytes", new BytesRef(value)));
}
writer.addDocument(d);
if (randomInt(10) == 0) {
refreshReader();
}
}
refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<FieldDataType, DuelFieldDataTests.Type>();
typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "fst")), Type.Bytes);
typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "paged_bytes")), Type.Bytes);
typeMap.put(new FieldDataType("string", ImmutableSettings.builder().put("format", "doc_values")), Type.Bytes);
for (Map.Entry<FieldDataType, Type> entry : typeMap.entrySet()) {
ifdService.clear();
IndexOrdinalsFieldData fieldData = getForField(entry.getKey(), entry.getValue().name().toLowerCase(Locale.ROOT));
RandomAccessOrds left = fieldData.load(readerContext).getOrdinalsValues();
fieldData.clear();
RandomAccessOrds right = fieldData.loadGlobal(topLevelReader).load(topLevelReader.leaves().get(0)).getOrdinalsValues();
assertEquals(left.getValueCount(), right.getValueCount());
for (long ord = 0; ord < left.getValueCount(); ++ord) {
assertEquals(left.lookupOrd(ord), right.lookupOrd(ord));
}
}
}
public void testDuelGeoPoints() throws Exception {
final String mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties")
.startObject("geopoint").field("type", "geo_point").startObject("fielddata").field("format", "doc_values").endObject().endObject()
.endObject().endObject().endObject().string();
final DocumentMapper mapper = mapperService.documentMapperParser().parse(mapping);
Random random = getRandom();
int atLeast = scaledRandomIntBetween(1000, 1500);
int maxValuesPerDoc = randomBoolean() ? 1 : randomIntBetween(2, 40);
// to test deduplication
double defaultLat = randomDouble() * 180 - 90;
double defaultLon = randomDouble() * 360 - 180;
for (int i = 0; i < atLeast; i++) {
final int numValues = randomInt(maxValuesPerDoc);
XContentBuilder doc = XContentFactory.jsonBuilder().startObject().startArray("geopoint");
for (int j = 0; j < numValues; ++j) {
if (randomBoolean()) {
doc.startObject().field("lat", defaultLat).field("lon", defaultLon).endObject();
} else {
doc.startObject().field("lat", randomDouble() * 180 - 90).field("lon", randomDouble() * 360 - 180).endObject();
}
}
doc = doc.endArray().endObject();
final ParsedDocument d = mapper.parse("type", Integer.toString(i), doc.bytes());
writer.addDocument(d.rootDoc());
if (random.nextInt(10) == 0) {
refreshReader();
}
}
AtomicReaderContext context = refreshReader();
Map<FieldDataType, Type> typeMap = new HashMap<>();
final Distance precision = new Distance(1, randomFrom(DistanceUnit.values()));
typeMap.put(new FieldDataType("geo_point", ImmutableSettings.builder().put("format", "array")), Type.GeoPoint);
typeMap.put(new FieldDataType("geo_point", ImmutableSettings.builder().put("format", "compressed").put("precision", precision)), Type.GeoPoint);
typeMap.put(new FieldDataType("geo_point", ImmutableSettings.builder().put("format", "doc_values")), Type.GeoPoint);
ArrayList<Entry<FieldDataType, Type>> list = new ArrayList<>(typeMap.entrySet());
while (!list.isEmpty()) {
Entry<FieldDataType, Type> left;
Entry<FieldDataType, Type> right;
if (list.size() > 1) {
left = list.remove(random.nextInt(list.size()));
right = list.remove(random.nextInt(list.size()));
} else {
right = left = list.remove(0);
}
ifdService.clear();
IndexGeoPointFieldData leftFieldData = getForField(left.getKey(), left.getValue().name().toLowerCase(Locale.ROOT));
ifdService.clear();
IndexGeoPointFieldData rightFieldData = getForField(right.getKey(), right.getValue().name().toLowerCase(Locale.ROOT));
duelFieldDataGeoPoint(random, context, leftFieldData, rightFieldData, precision);
duelFieldDataGeoPoint(random, context, rightFieldData, leftFieldData, precision);
DirectoryReader perSegment = DirectoryReader.open(writer, true);
CompositeReaderContext composite = perSegment.getContext();
List<AtomicReaderContext> leaves = composite.leaves();
for (AtomicReaderContext atomicReaderContext : leaves) {
duelFieldDataGeoPoint(random, atomicReaderContext, leftFieldData, rightFieldData, precision);
}
perSegment.close();
}
}
private int[] getNumbers(Random random, int margin) {
if (random.nextInt(20) == 0) {
int[] num = new int[1 + random.nextInt(10)];
for (int i = 0; i < num.length; i++) {
int v = (random.nextBoolean() ? -1 * random.nextInt(margin) : random.nextInt(margin));
num[i] = v;
}
return num;
}
return new int[]{(random.nextBoolean() ? -1 * random.nextInt(margin) : random.nextInt(margin))};
}
private static void duelFieldDataBytes(Random random, AtomicReaderContext context, IndexFieldData<?> left, IndexFieldData<?> right, Preprocessor pre) throws Exception {
AtomicFieldData leftData = random.nextBoolean() ? left.load(context) : left.loadDirect(context);
AtomicFieldData rightData = random.nextBoolean() ? right.load(context) : right.loadDirect(context);
int numDocs = context.reader().maxDoc();
SortedBinaryDocValues leftBytesValues = leftData.getBytesValues();
SortedBinaryDocValues rightBytesValues = rightData.getBytesValues();
BytesRefBuilder leftSpare = new BytesRefBuilder();
BytesRefBuilder rightSpare = new BytesRefBuilder();
for (int i = 0; i < numDocs; i++) {
leftBytesValues.setDocument(i);
rightBytesValues.setDocument(i);
int numValues = leftBytesValues.count();
assertThat(numValues, equalTo(rightBytesValues.count()));
BytesRef previous = null;
for (int j = 0; j < numValues; j++) {
rightSpare.copyBytes(rightBytesValues.valueAt(j));
leftSpare.copyBytes(leftBytesValues.valueAt(j));
if (previous != null) {
assertThat(pre.compare(previous, rightSpare.get()), lessThan(0));
}
previous = BytesRef.deepCopyOf(rightSpare.get());
pre.toString(rightSpare.get());
pre.toString(leftSpare.get());
assertThat(pre.toString(leftSpare.get()), equalTo(pre.toString(rightSpare.get())));
}
}
}
private static void duelFieldDataDouble(Random random, AtomicReaderContext context, IndexNumericFieldData left, IndexNumericFieldData right) throws Exception {
AtomicNumericFieldData leftData = random.nextBoolean() ? left.load(context) : left.loadDirect(context);
AtomicNumericFieldData rightData = random.nextBoolean() ? right.load(context) : right.loadDirect(context);
int numDocs = context.reader().maxDoc();
SortedNumericDoubleValues leftDoubleValues = leftData.getDoubleValues();
SortedNumericDoubleValues rightDoubleValues = rightData.getDoubleValues();
for (int i = 0; i < numDocs; i++) {
leftDoubleValues.setDocument(i);
rightDoubleValues.setDocument(i);
int numValues = leftDoubleValues.count();
assertThat(numValues, equalTo(rightDoubleValues.count()));
double previous = 0;
for (int j = 0; j < numValues; j++) {
double current = rightDoubleValues.valueAt(j);
if (Double.isNaN(current)) {
assertTrue(Double.isNaN(leftDoubleValues.valueAt(j)));
} else {
assertThat(leftDoubleValues.valueAt(j), closeTo(current, 0.0001));
}
if (j > 0) {
assertThat(Double.compare(previous,current), lessThan(0));
}
previous = current;
}
}
}
private static void duelFieldDataLong(Random random, AtomicReaderContext context, IndexNumericFieldData left, IndexNumericFieldData right) throws Exception {
AtomicNumericFieldData leftData = random.nextBoolean() ? left.load(context) : left.loadDirect(context);
AtomicNumericFieldData rightData = random.nextBoolean() ? right.load(context) : right.loadDirect(context);
int numDocs = context.reader().maxDoc();
SortedNumericDocValues leftLongValues = leftData.getLongValues();
SortedNumericDocValues rightLongValues = rightData.getLongValues();
for (int i = 0; i < numDocs; i++) {
leftLongValues.setDocument(i);
rightLongValues.setDocument(i);
int numValues = leftLongValues.count();
long previous = 0;
assertThat(numValues, equalTo(rightLongValues.count()));
for (int j = 0; j < numValues; j++) {
long current;
assertThat(leftLongValues.valueAt(j), equalTo(current = rightLongValues.valueAt(j)));
if (j > 0) {
assertThat(previous, lessThan(current));
}
previous = current;
}
}
}
private static void duelFieldDataGeoPoint(Random random, AtomicReaderContext context, IndexGeoPointFieldData left, IndexGeoPointFieldData right, Distance precision) throws Exception {
AtomicGeoPointFieldData leftData = random.nextBoolean() ? left.load(context) : left.loadDirect(context);
AtomicGeoPointFieldData rightData = random.nextBoolean() ? right.load(context) : right.loadDirect(context);
int numDocs = context.reader().maxDoc();
MultiGeoPointValues leftValues = leftData.getGeoPointValues();
MultiGeoPointValues rightValues = rightData.getGeoPointValues();
for (int i = 0; i < numDocs; ++i) {
leftValues.setDocument(i);
final int numValues = leftValues.count();
rightValues.setDocument(i);;
assertEquals(numValues, rightValues.count());
List<GeoPoint> leftPoints = Lists.newArrayList();
List<GeoPoint> rightPoints = Lists.newArrayList();
for (int j = 0; j < numValues; ++j) {
GeoPoint l = leftValues.valueAt(j);
leftPoints.add(new GeoPoint(l.getLat(), l.getLon()));
GeoPoint r = rightValues.valueAt(j);
rightPoints.add(new GeoPoint(r.getLat(), r.getLon()));
}
for (GeoPoint l : leftPoints) {
assertTrue("Couldn't find " + l + " among " + rightPoints, contains(l, rightPoints, precision));
}
for (GeoPoint r : rightPoints) {
assertTrue("Couldn't find " + r + " among " + leftPoints, contains(r, leftPoints, precision));
}
}
}
private static boolean contains(GeoPoint point, List<GeoPoint> set, Distance precision) {
for (GeoPoint r : set) {
final double distance = GeoDistance.PLANE.calculate(point.getLat(), point.getLon(), r.getLat(), r.getLon(), DistanceUnit.METERS);
if (new Distance(distance, DistanceUnit.METERS).compareTo(precision) <= 0) {
return true;
}
}
return false;
}
private static class Preprocessor {
public String toString(BytesRef ref) {
return ref.utf8ToString();
}
public int compare(BytesRef a, BytesRef b) {
return a.compareTo(b);
}
}
private static class ToDoublePreprocessor extends Preprocessor {
@Override
public String toString(BytesRef ref) {
assertTrue(ref.length > 0);
return Double.toString(Double.parseDouble(super.toString(ref)));
}
@Override
public int compare(BytesRef a, BytesRef b) {
Double _a = Double.parseDouble(super.toString(a));
return _a.compareTo(Double.parseDouble(super.toString(b)));
}
}
private static enum Type {
Float, Double, Integer, Long, Bytes, GeoPoint;
}
}
| |
/*
* 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.
*/
package com.intellij.tasks.lighthouse;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.tasks.*;
import com.intellij.tasks.impl.BaseRepository;
import com.intellij.tasks.impl.BaseRepositoryImpl;
import com.intellij.util.NullableFunction;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.xmlb.annotations.Tag;
import icons.TasksCoreIcons;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author Dennis.Ushakov
*/
@Tag("Lighthouse")
public class LighthouseRepository extends BaseRepositoryImpl {
private static final Logger LOG = Logger.getInstance("#com.intellij.tasks.lighthouse.LighthouseRepository");
private static final Pattern DATE_PATTERN = Pattern.compile("(\\d\\d\\d\\d\\-\\d\\d\\-\\d\\d).*(\\d\\d:\\d\\d:\\d\\d).*");
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private Pattern myPattern;
private String myProjectId;
private String myAPIKey;
/** for serialization */
@SuppressWarnings({"UnusedDeclaration"})
public LighthouseRepository() {
}
public LighthouseRepository(TaskRepositoryType type) {
super(type);
}
@NotNull
@Override
public BaseRepository clone() {
return new LighthouseRepository(this);
}
private LighthouseRepository(LighthouseRepository other) {
super(other);
setProjectId(other.myProjectId);
setAPIKey(myAPIKey = other.myAPIKey);
}
@Override
public void testConnection() throws Exception {
getIssues(null, 10, 0);
}
@Override
public boolean isConfigured() {
return super.isConfigured() &&
StringUtil.isNotEmpty(getProjectId()) &&
StringUtil.isNotEmpty(getAPIKey());
}
@Override
public Task[] getIssues(@Nullable String query, int max, long since) throws Exception {
String url = "/projects/" + myProjectId + "/tickets.xml";
url += "?q=" + encodeUrl("state:open sort:updated ");
if (!StringUtil.isEmpty(query)) {
url += encodeUrl(query);
}
final List<Task> tasks = new ArrayList<>();
int page = 1;
final HttpClient client = login();
while (tasks.size() < max) {
HttpMethod method = doREST(url + "&page=" + page, false, client);
InputStream stream = method.getResponseBodyAsStream();
Element element = new SAXBuilder(false).build(stream).getRootElement();
if ("nil-classes".equals(element.getName())) break;
if (!"tickets".equals(element.getName())) {
LOG.warn("Error fetching issues for: " + url + ", HTTP status code: " + method.getStatusCode());
throw new Exception("Error fetching issues for: " + url + ", HTTP status code: " + method.getStatusCode() +
"\n" + element.getText());
}
List<Element> children = element.getChildren("ticket");
List<Task> taskList = ContainerUtil.mapNotNull(children, (NullableFunction<Element, Task>)o -> createIssue(o));
tasks.addAll(taskList);
page++;
}
return tasks.toArray(new Task[tasks.size()]);
}
@Nullable
private Task createIssue(Element element) {
final String id = element.getChildText("number");
if (id == null) {
return null;
}
final String summary = element.getChildText("title");
if (summary == null) {
return null;
}
final String description = element.getChildText("original-body");
final boolean isClosed = "true".equals(element.getChildText("closed"));
final Ref<Date> updated = new Ref<>();
final Ref<Date> created = new Ref<>();
try {
updated.set(parseDate(element, "updated-at"));
created.set(parseDate(element, "created-at"));
} catch (ParseException e) {
LOG.warn(e);
}
return new Task() {
@Override
public boolean isIssue() {
return true;
}
@Override
public String getIssueUrl() {
return getUrl() + "/projects/" + myProjectId + "/tickets/" + getId() + ".xml";
}
@NotNull
@Override
public String getId() {
return myProjectId + "-" + id;
}
@NotNull
@Override
public String getSummary() {
return summary;
}
public String getDescription() {
return description;
}
@NotNull
@Override
public Comment[] getComments() {
return Comment.EMPTY_ARRAY;
}
@NotNull
@Override
public Icon getIcon() {
return TasksCoreIcons.Lighthouse;
}
@NotNull
@Override
public TaskType getType() {
return TaskType.BUG;
}
@Override
public Date getUpdated() {
return updated.get();
}
@Override
public Date getCreated() {
return created.get();
}
@Override
public boolean isClosed() {
return isClosed;
}
@Override
public TaskRepository getRepository() {
return LighthouseRepository.this;
}
@Override
public String getPresentableName() {
return getId() + ": " + getSummary();
}
};
}
@Nullable
private static Date parseDate(Element element, String name) throws ParseException {
final Matcher m = DATE_PATTERN.matcher(element.getChildText(name));
if (m.find()) {
return DATE_FORMAT.parse(m.group(1) + " " + m.group(2));
}
return null;
}
@Nullable
public String extractId(@NotNull String taskName) {
Matcher matcher = myPattern.matcher(taskName);
return matcher.find() ? matcher.group(1) : null;
}
private HttpMethod doREST(String request, boolean post, HttpClient client) throws Exception {
String uri = getUrl() + request;
HttpMethod method = post ? new PostMethod(uri) : new GetMethod(uri);
configureHttpMethod(method);
client.executeMethod(method);
return method;
}
private HttpClient login() throws Exception {
HttpClient client = getHttpClient();
GetMethod method = new GetMethod(getUrl() + "/projects.xml");
configureHttpMethod(method);
client.getParams().setContentCharset("UTF-8");
client.executeMethod(method);
if (method.getStatusCode() != 200) {
throw new Exception("Cannot login: HTTP returned " + method.getStatusCode());
}
String response = method.getResponseBodyAsString();
if (response == null) {
throw new NullPointerException();
}
if (response.contains("<errors>")) {
int pos = response.indexOf("</errors>");
int length = "<errors>".length();
if (pos > length) {
response = response.substring(length, pos);
}
throw new Exception("Cannot login: " + response);
}
return client;
}
@Override
protected void configureHttpMethod(HttpMethod method) {
method.addRequestHeader("X-LighthouseToken", myAPIKey);
}
@Nullable
@Override
public Task findTask(@NotNull String id) throws Exception {
final String[] split = id.split("\\-");
final String projectId = split[0];
final String realId = split[1];
if (!Comparing.strEqual(projectId, myProjectId)) return null;
HttpMethod method = doREST("/projects/" + myProjectId + "/tickets/" + realId +".xml", false, login());
InputStream stream = method.getResponseBodyAsStream();
Element element = new SAXBuilder(false).build(stream).getRootElement();
return element.getName().equals("ticket") ? createIssue(element) : null;
}
public String getProjectId() {
return myProjectId;
}
public void setProjectId(String projectId) {
myProjectId = projectId;
myPattern = Pattern.compile("(" + projectId + "\\-\\d+):\\s+");
}
public String getAPIKey() {
return myAPIKey;
}
public void setAPIKey(String APIKey) {
myAPIKey = APIKey;
}
@Override
public boolean equals(Object o) {
if (!super.equals(o)) return false;
if (!(o instanceof LighthouseRepository)) return false;
LighthouseRepository that = (LighthouseRepository)o;
if (getAPIKey() != null ? !getAPIKey().equals(that.getAPIKey()) : that.getAPIKey() != null) return false;
if (getProjectId() != null ? !getProjectId().equals(that.getProjectId()) : that.getProjectId() != null) return false;
return true;
}
}
| |
/*
* 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.client.cache;
import org.apache.druid.java.util.common.IAE;
import java.util.AbstractQueue;
import java.util.Collection;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Abstract implementation of a BlockingQueue bounded by the size of elements,
* works similar to LinkedBlockingQueue except that capacity is bounded by the size in bytes of the elements in the queue.
*/
public abstract class BytesBoundedLinkedQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>
{
private final Queue<E> delegate;
private final AtomicLong currentSize = new AtomicLong(0);
private final Lock putLock = new ReentrantLock();
private final Condition notFull = putLock.newCondition();
private final Lock takeLock = new ReentrantLock();
private final Condition notEmpty = takeLock.newCondition();
private final AtomicInteger elementCount = new AtomicInteger(0);
private long capacity;
public BytesBoundedLinkedQueue(long capacity)
{
delegate = new ConcurrentLinkedQueue<>();
this.capacity = capacity;
}
private static void checkNotNull(Object v)
{
if (v == null) {
throw new NullPointerException();
}
}
private void checkSize(E e)
{
if (getBytesSize(e) > capacity) {
throw new IAE("cannot add element of size[%d] greater than capacity[%d]", getBytesSize(e), capacity);
}
}
public abstract long getBytesSize(E e);
public void elementAdded(E e)
{
currentSize.addAndGet(getBytesSize(e));
elementCount.getAndIncrement();
}
public void elementRemoved(E e)
{
currentSize.addAndGet(-1 * getBytesSize(e));
elementCount.getAndDecrement();
}
private void fullyUnlock()
{
takeLock.unlock();
putLock.unlock();
}
private void fullyLock()
{
takeLock.lock();
putLock.lock();
}
private void signalNotEmpty()
{
takeLock.lock();
try {
notEmpty.signal();
}
finally {
takeLock.unlock();
}
}
private void signalNotFull()
{
putLock.lock();
try {
notFull.signal();
}
finally {
putLock.unlock();
}
}
@Override
public int size()
{
return elementCount.get();
}
@Override
public void put(E e) throws InterruptedException
{
while (!offer(e, Long.MAX_VALUE, TimeUnit.NANOSECONDS)) {
// keep trying until added successfully
}
}
@Override
public boolean offer(
E e, long timeout, TimeUnit unit
) throws InterruptedException
{
checkNotNull(e);
checkSize(e);
long nanos = unit.toNanos(timeout);
boolean added = false;
putLock.lockInterruptibly();
try {
while (currentSize.get() + getBytesSize(e) > capacity) {
if (nanos <= 0) {
return false;
}
nanos = notFull.awaitNanos(nanos);
}
delegate.add(e);
elementAdded(e);
added = true;
}
finally {
putLock.unlock();
}
if (added) {
signalNotEmpty();
}
return added;
}
@Override
public E take() throws InterruptedException
{
E e;
takeLock.lockInterruptibly();
try {
while (elementCount.get() == 0) {
notEmpty.await();
}
e = delegate.remove();
elementRemoved(e);
}
finally {
takeLock.unlock();
}
if (e != null) {
signalNotFull();
}
return e;
}
@Override
public int remainingCapacity()
{
int delegateSize;
long currentByteSize;
fullyLock();
try {
delegateSize = elementCount.get();
currentByteSize = currentSize.get();
}
finally {
fullyUnlock();
}
// return approximate remaining capacity based on current data
if (delegateSize == 0) {
return (int) Math.min(capacity, Integer.MAX_VALUE);
} else if (capacity > currentByteSize) {
long averageElementSize = currentByteSize / delegateSize;
return (int) ((capacity - currentByteSize) / averageElementSize);
} else {
// queue full
return 0;
}
}
@Override
public int drainTo(Collection<? super E> c)
{
return drainTo(c, Integer.MAX_VALUE);
}
@Override
public int drainTo(Collection<? super E> c, int maxElements)
{
if (c == null) {
throw new NullPointerException();
}
if (c == this) {
throw new IllegalArgumentException();
}
int n = 0;
takeLock.lock();
try {
// elementCount.get provides visibility to first n Nodes
n = Math.min(maxElements, elementCount.get());
if (n < 0) {
return 0;
}
for (int i = 0; i < n; i++) {
E e = delegate.remove();
elementRemoved(e);
c.add(e);
}
}
finally {
takeLock.unlock();
}
if (n > 0) {
signalNotFull();
}
return n;
}
@Override
public boolean offer(E e)
{
checkNotNull(e);
checkSize(e);
boolean added = false;
putLock.lock();
try {
if (currentSize.get() + getBytesSize(e) > capacity) {
return false;
} else {
added = delegate.add(e);
if (added) {
elementAdded(e);
}
}
}
finally {
putLock.unlock();
}
if (added) {
signalNotEmpty();
}
return added;
}
@Override
public E poll()
{
E e = null;
takeLock.lock();
try {
e = delegate.poll();
if (e != null) {
elementRemoved(e);
}
}
finally {
takeLock.unlock();
}
if (e != null) {
signalNotFull();
}
return e;
}
@Override
public E poll(long timeout, TimeUnit unit) throws InterruptedException
{
long nanos = unit.toNanos(timeout);
E e = null;
takeLock.lockInterruptibly();
try {
while (elementCount.get() == 0) {
if (nanos <= 0) {
return null;
}
nanos = notEmpty.awaitNanos(nanos);
}
e = delegate.poll();
if (e != null) {
elementRemoved(e);
}
}
finally {
takeLock.unlock();
}
if (e != null) {
signalNotFull();
}
return e;
}
@Override
public E peek()
{
takeLock.lock();
try {
return delegate.peek();
}
finally {
takeLock.unlock();
}
}
@Override
public Iterator<E> iterator()
{
return new Itr(delegate.iterator());
}
private class Itr implements Iterator<E>
{
private final Iterator<E> delegate;
private E lastReturned;
Itr(Iterator<E> delegate)
{
this.delegate = delegate;
}
@Override
public boolean hasNext()
{
fullyLock();
try {
return delegate.hasNext();
}
finally {
fullyUnlock();
}
}
@Override
public E next()
{
fullyLock();
try {
this.lastReturned = delegate.next();
return lastReturned;
}
finally {
fullyUnlock();
}
}
@Override
public void remove()
{
fullyLock();
try {
if (this.lastReturned == null) {
throw new IllegalStateException();
}
delegate.remove();
elementRemoved(lastReturned);
signalNotFull();
lastReturned = null;
}
finally {
fullyUnlock();
}
}
}
}
| |
package org.broadinstitute.hellbender.tools.walkers.rnaseq;
import com.google.common.primitives.Ints;
import htsjdk.samtools.Cigar;
import htsjdk.samtools.CigarElement;
import htsjdk.samtools.CigarOperator;
import htsjdk.samtools.SAMFileHeader;
import org.broadinstitute.hellbender.utils.read.GATKRead;
import org.broadinstitute.hellbender.utils.read.GATKReadWriter;
import org.broadinstitute.hellbender.GATKBaseTest;
import org.broadinstitute.hellbender.utils.read.ReadUtils;
import org.broadinstitute.hellbender.testutils.ReadClipperTestUtils;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
* Tests all possible (and valid) cigar strings that might contain any cigar elements. It uses a code that were written to test the ReadClipper walker.
* For valid cigar sting in length 8 there are few thousands options, with N in every possible option and with more than one N (for example 1M1N1M1N1M1N2M).
* The cigarElements array is used to provide all the possible cigar element that might be included.
*/
public final class SplitNCigarReadsUnitTest extends GATKBaseTest {
final static CigarElement[] cigarElements = {
new CigarElement(1, CigarOperator.HARD_CLIP),
new CigarElement(1, CigarOperator.SOFT_CLIP),
new CigarElement(1, CigarOperator.INSERTION),
new CigarElement(1, CigarOperator.DELETION),
new CigarElement(1, CigarOperator.MATCH_OR_MISMATCH),
new CigarElement(1, CigarOperator.SKIPPED_REGION)
};
private SAMFileHeader header = new SAMFileHeader();;
private final class TestManager extends OverhangFixingManager {
public TestManager( final SAMFileHeader header , DummyTestWriter writer) {
super(header, writer, hg19GenomeLocParser, hg19ReferenceReader, 10000, 1, 40, false, true);
}
}
@Test
public void testEmptyReads() {
DummyTestWriter writer = new DummyTestWriter();
header.setSequenceDictionary(hg19GenomeLocParser.getSequenceDictionary());
TestManager manager = new TestManager(header, writer);
manager.activateWriting();
//Testing that bogus splits make it through unaffected
GATKRead read1 = ReadUtils.emptyRead(ReadClipperTestUtils.makeReadFromCigar("1S4N2S3N4H"));
SplitNCigarReads.splitNCigarRead(read1, manager, true, header, true);
manager.flush();
Assert.assertEquals(1, writer.writtenReads.size());
Assert.assertEquals("*", writer.writtenReads.get(0).getCigar().toString());
}
@Test
public void testBogusNSplits() {
DummyTestWriter writer = new DummyTestWriter();
header.setSequenceDictionary(hg19GenomeLocParser.getSequenceDictionary());
TestManager manager = new TestManager(header, writer);
manager.activateWriting();
//Testing that bogus splits make it through unaffected
GATKRead read1 = ReadClipperTestUtils.makeReadFromCigar("1S4N2S3N4H");
SplitNCigarReads.splitNCigarRead(read1, manager, true, header, true);
manager.flush();
Assert.assertEquals(1, writer.writtenReads.size());
Assert.assertEquals("1S4N2S3N4H", writer.writtenReads.get(0).getCigar().toString());
}
@Test
public void testBogusMidNSection() {
//Testing that bogus subsections dont end up clipped
DummyTestWriter writer = new DummyTestWriter();
header.setSequenceDictionary(hg19GenomeLocParser.getSequenceDictionary());
TestManager manager = new TestManager(header, writer);
manager.activateWriting();
manager = new TestManager(header, writer);
manager.activateWriting();
GATKRead read2 = ReadClipperTestUtils.makeReadFromCigar("1S3N2M10N1M4H");
SplitNCigarReads.splitNCigarRead(read2, manager, true, header, true);
manager.flush();
Assert.assertEquals(2, writer.writtenReads.size());
Assert.assertEquals("1S2M1S4H", writer.writtenReads.get(0).getCigar().toString());
Assert.assertEquals("3S1M4H", writer.writtenReads.get(1).getCigar().toString());
}
@Test
public void testSplitNComplexCase() {
//Complex Case involving insertions & deletions
DummyTestWriter writer = new DummyTestWriter();
header.setSequenceDictionary(hg19GenomeLocParser.getSequenceDictionary());
TestManager manager = new TestManager(header, writer);
manager.activateWriting();
writer = new DummyTestWriter();
manager = new TestManager(header, writer);
manager.activateWriting();
GATKRead read3 = ReadClipperTestUtils.makeReadFromCigar("1H2M2D1M2N1M2I1N1M2S1N2S1N2S");
read3.setAttribute("MC", "11M4N11M");
SplitNCigarReads.splitNCigarRead(read3, manager,true, header, true);
manager.flush();
Assert.assertEquals(3, writer.writtenReads.size());
Assert.assertEquals("1H2M2D1M10S", writer.writtenReads.get(0).getCigar().toString());
Assert.assertEquals("1H3S1M2I7S", writer.writtenReads.get(1).getCigar().toString());
Assert.assertEquals("1H6S1M6S", writer.writtenReads.get(2).getCigar().toString());
// Testing that the mate cigar string setting is correct
Assert.assertEquals("11M11S", writer.writtenReads.get(0).getAttributeAsString("MC"));
Assert.assertEquals("11M11S", writer.writtenReads.get(1).getAttributeAsString("MC"));
Assert.assertEquals("11M11S", writer.writtenReads.get(2).getAttributeAsString("MC"));
}
@Test
public void splitReadAtN() {
final int maxCigarElements = 9;
final List<Cigar> cigarList = ReadClipperTestUtils.generateCigarList(maxCigarElements, cigarElements);
// For Debugging use those lines (instead of above cigarList) to create specific read:
//------------------------------------------------------------------------------------
// final SAMRecord tmpRead = SAMRecord.createRandomRead(6);
// tmpRead.setCigarString("1M1N1M");
// final List<Cigar> cigarList = new ArrayList<>();
// cigarList.add(tmpRead.getCigar());
for(Cigar cigar: cigarList){
final int numOfSplits = numOfNElements(cigar.getCigarElements());
if(numOfSplits != 0 && isCigarDoesNotHaveEmptyRegionsBetweenNs(cigar)){
final SAMFileHeader header = new SAMFileHeader();
header.setSequenceDictionary(hg19GenomeLocParser.getSequenceDictionary());
final TestManager manager = new TestManager(header, new DummyTestWriter());
manager.activateWriting();
GATKRead read = ReadClipperTestUtils.makeReadFromCigar(cigar);
SplitNCigarReads.splitNCigarRead(read, manager, true, header, true);
List<List<OverhangFixingManager.SplitRead>> splitReadGroups = manager.getReadsInQueueForTesting();
final int expectedReads = numOfSplits+1;
Assert.assertEquals(manager.getNReadsInQueue(), expectedReads, "wrong number of reads after split read with cigar: " + cigar + " at Ns [expected]: " + expectedReads + " [actual value]: " + manager.getNReadsInQueue());
final int readLengths = consecutiveNonNElements(read.getCigar().getCigarElements());
int index = 0;
for(final OverhangFixingManager.SplitRead splitRead: splitReadGroups.get(0)){
Assert.assertTrue(splitRead.read.getLength() == readLengths,
"the " + index + " (starting with 0) split read has a wrong length.\n" +
"cigar of original read: " + cigar + "\n" +
"expected length: " + readLengths + "\n" +
"actual length: " + splitRead.read.getLength() + "\n");
assertBases(splitRead.read.getBases(), read.getBases());
index++;
}
}
}
}
private int numOfNElements(final List<CigarElement> cigarElements){
return Ints.checkedCast(cigarElements.stream()
.filter(e -> e.getOperator() == CigarOperator.SKIPPED_REGION)
.count());
}
private static boolean isCigarDoesNotHaveEmptyRegionsBetweenNs(final Cigar cigar) {
boolean sawM = false;
for (CigarElement cigarElement : cigar.getCigarElements()) {
if (cigarElement.getOperator().equals(CigarOperator.SKIPPED_REGION)) {
if(!sawM)
return false;
sawM = false;
}
if (cigarElement.getOperator().equals(CigarOperator.MATCH_OR_MISMATCH))
sawM = true;
}
return sawM;
}
private int consecutiveNonNElements(final List<CigarElement> cigarElements){
int consecutiveLength = 0;
for(CigarElement element: cigarElements){
final CigarOperator op = element.getOperator();
if(op.equals(CigarOperator.MATCH_OR_MISMATCH) || op.equals(CigarOperator.SOFT_CLIP) || op.equals(CigarOperator.INSERTION)){
consecutiveLength += element.getLength();
}
}
return consecutiveLength;
}
private void assertBases(final byte[] actualBase, final byte[] expectedBase) {
for (int i = 0; i < actualBase.length; i++) {
Assert.assertEquals(actualBase[i], expectedBase[i], "unmatched bases between: " + Arrays.toString(actualBase) + "\nand:\n" + Arrays.toString(expectedBase) + "\nat position: " + i);
}
}
private static class DummyTestWriter implements GATKReadWriter {
public List<GATKRead> writtenReads = new ArrayList<>();
@Override
public void close() {}
@Override
public void addRead(GATKRead read) {
writtenReads.add(read);
}
}
}
| |
/*
* 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.wicket.model;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import org.apache.wicket.core.util.lang.WicketObjects;
import org.apache.wicket.model.lambda.Address;
import org.apache.wicket.model.lambda.Person;
import org.danekja.java.util.function.serializable.SerializableBiFunction;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Tests for {@link IModel}'s methods
*/
public class IModelTest extends Assert
{
private Person person;
private final String name = "John";
private final String street = "Strasse";
@Before
public void before()
{
person = new Person();
person.setName(name);
Address address = new Address();
person.setAddress(address);
address.setStreet(street);
address.setNumber(123);
}
@Test
public void filterMatch()
{
IModel<Person> johnModel = Model.of(person).filter((p) -> p.getName().equals(name));
assertThat(johnModel.getObject(), is(person));
}
@Test
public void filterNoMatch()
{
IModel<Person> johnModel = Model.of(person).filter((p) -> p.getName().equals("Jane"));
assertThat(johnModel.getObject(), is(nullValue()));
}
@Test(expected = IllegalArgumentException.class)
public void nullFilter()
{
Model.of(person).filter(null);
}
@Test
public void map()
{
IModel<String> personNameModel = Model.of(person).map(Person::getName);
assertThat(personNameModel.getObject(), is(equalTo(name)));
}
@Test
public void map2()
{
IModel<String> streetModel = Model.of(person)
.map(Person::getAddress)
.map(Address::getStreet);
assertThat(streetModel.getObject(), is(equalTo(street)));
}
@Test(expected = IllegalArgumentException.class)
public void nullMapper()
{
Model.of(person).map(null);
}
@Test
public void combineWith()
{
IModel<String> janeModel = Model.of("Jane");
SerializableBiFunction<Person, String, String> function = (SerializableBiFunction<Person, String, String>)(
person1, other) -> person1.getName() + " is in relationship with " + other;
IModel<String> relationShipModel = Model.of(person).combineWith(janeModel, function);
assertThat(relationShipModel.getObject(), is(equalTo("John is in relationship with Jane")));
}
@Test
public void combineWithNullObject()
{
IModel<String> janeModel = Model.of((String)null);
SerializableBiFunction<Person, String, String> function = (SerializableBiFunction<Person, String, String>)(
person1, other) -> person1.getName() + " is in relationship with " + other;
IModel<String> relationShipModel = Model.of(person).combineWith(janeModel, function);
assertThat(relationShipModel.getObject(), is(nullValue()));
}
@Test(expected = IllegalArgumentException.class)
public void combineWithNullModel()
{
IModel<String> janeModel = null;
SerializableBiFunction<Person, String, String> function = (SerializableBiFunction<Person, String, String>)(
person1, other) -> person1.getName() + " is in relationship with " + other;
Model.of(person).combineWith(janeModel, function);
}
@Test(expected = IllegalArgumentException.class)
public void combineWithNullCombiner()
{
Model.of(person).combineWith(Model.of("Jane"), null);
}
@Test
public void flatMap()
{
IModel<String> heirModel = Model.of(person)
.flatMap(john -> LambdaModel.of(() -> john.getName() + " is my parent", john::setName));
assertThat(heirModel.getObject(), is(equalTo("John is my parent")));
String newValue = "Matthias";
heirModel.setObject(newValue);
assertThat(heirModel.getObject(), is(equalTo("Matthias is my parent")));
}
@Test(expected = IllegalArgumentException.class)
public void nullFlatMapper()
{
Model.of(person).flatMap(null);
}
@Test
public void orElse()
{
person.setName(null);
String defaultName = "Default name";
IModel<String> defaultNameModel = Model.of(person).map(Person::getName).orElse(defaultName);
assertThat(defaultNameModel.getObject(), is(equalTo(defaultName)));
}
@Test
public void orElseGet()
{
person.setName(null);
String defaultName = "Default name";
IModel<String> defaultNameModel = Model.of(person)
.map(Person::getName)
.orElseGet(() -> defaultName);
assertThat(defaultNameModel.getObject(), is(equalTo(defaultName)));
}
@Test(expected = IllegalArgumentException.class)
public void orElseGetNullOther()
{
Model.of(person).map(Person::getName).orElseGet(null);
}
@Test
public void isPresent()
{
assertThat(Model.of(person).isPresent().getObject(), is(equalTo(true)));
}
@Test
public void isPresentNot()
{
assertThat(Model.of((Person)null).isPresent().getObject(), is(equalTo(false)));
}
@Test
public void serializableMethodReference()
{
Person p = new Person();
IModel<String> m = p::getName;
assertThat(WicketObjects.cloneObject(m), is(not(nullValue())));
}
static class Account
{
private Person person = new Person();
{
person.setName("Some Name");
}
public Person getPerson()
{
return person;
}
}
@Test
public void serializableMethodChainReference()
{
IModel<Account> accountModel = LoadableDetachableModel.of(Account::new);
IModel<Person> personModel = accountModel.map(Account::getPerson);
IModel<String> nameModel = personModel.map(Person::getName);
IModel<String> clone = WicketObjects.cloneObject(nameModel);
assertThat(clone, is(not(nullValue())));
assertThat(clone.getObject(), is("Some Name"));
}
}
| |
/**
*
*/
package ca.ualberta.cs.app.testPart4.activity;
import network_io.IoStreamHandler;
import model.Comment;
import activity.EditCommentPageActivity;
import android.content.Intent;
import android.location.Location;
import android.test.ActivityInstrumentationTestCase2;
import android.test.ViewAsserts;
import android.test.suitebuilder.annotation.MediumTest;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
/**
* JUnit test cases for EditCommentPageActivity.
*
* @author Yilu Su
*
*/
public class EditCommentPageActivityTest extends
ActivityInstrumentationTestCase2<EditCommentPageActivity> {
EditCommentPageActivity mActivity;
EditText title;
EditText content;
EditText latitude;
EditText longitude;
ImageView picture;
ImageButton commit;
ImageButton cancel;
/**
* Constructor
*/
public EditCommentPageActivityTest() {
super(EditCommentPageActivity.class);
}
/**
* Sets up the test environment before each test.
* @see android.test.ActivityInstrumentationTestCase2#setUp()
*/
@Override
protected void setUp() throws Exception {
super.setUp();
setActivityInitialTouchMode(true);
Location location = new Location("mock");
location.setLatitude(5.5);
location.setLongitude(10.5);
Comment comment = new Comment("title", "content", location, null, "user");
IoStreamHandler ioStreamHandler = new IoStreamHandler();
ioStreamHandler.addOrUpdateComment(comment);
Thread.sleep(1000);
Intent intent = new Intent();
intent.putExtra("commentID", comment.getId());
setActivityIntent(intent);
mActivity = getActivity();
Thread.sleep(1000);
title = (EditText)mActivity.findViewById(com.example.projectapp.R.id.edit_title);
content = (EditText)mActivity.findViewById(com.example.projectapp.R.id.edit_content);
latitude = (EditText)mActivity.findViewById(com.example.projectapp.R.id.edit_latitude);
longitude = (EditText)mActivity.findViewById(com.example.projectapp.R.id.edit_longitude);
picture = (ImageView)mActivity.findViewById(com.example.projectapp.R.id.edit_picture);
commit = (ImageButton) mActivity.findViewById(com.example.projectapp.R.id.edit_commit);
cancel = (ImageButton) mActivity.findViewById(com.example.projectapp.R.id.edit_cancel);
}
/**
* Verify Title Layout Parameters
* @throws Exception
*/
@MediumTest
public void testTitleLayout() throws Exception {
final View decorView = mActivity.getWindow().getDecorView();
ViewAsserts.assertOnScreen(decorView, title);
final ViewGroup.LayoutParams layoutParams = title.getLayoutParams();
assertNotNull(layoutParams);
assertEquals(layoutParams.width, WindowManager.LayoutParams.MATCH_PARENT);
assertEquals(layoutParams.height, WindowManager.LayoutParams.WRAP_CONTENT);
tearDown();
}
/**
* Verify Content Layout Parameters
* @throws Exception
*/
@MediumTest
public void testContentLayout() throws Exception {
final View decorView = mActivity.getWindow().getDecorView();
ViewAsserts.assertOnScreen(decorView, content);
final ViewGroup.LayoutParams layoutParams = content.getLayoutParams();
assertNotNull(layoutParams);
assertEquals(layoutParams.width, WindowManager.LayoutParams.MATCH_PARENT);
assertEquals(layoutParams.height, WindowManager.LayoutParams.WRAP_CONTENT);
tearDown();
}
/**
* Verify Picture Layout Parameters
* @throws Exception
*/
@MediumTest
public void testPictureLayout() throws Exception {
final View decorView = mActivity.getWindow().getDecorView();
ViewAsserts.assertOnScreen(decorView, picture);
final ViewGroup.LayoutParams layoutParams = picture.getLayoutParams();
assertNotNull(layoutParams);
assertEquals(layoutParams.width, WindowManager.LayoutParams.WRAP_CONTENT);
assertEquals(layoutParams.height, WindowManager.LayoutParams.WRAP_CONTENT);
tearDown();
}
/**
* Verify Latitude Layout Parameters
* @throws Exception
*/
@MediumTest
public void testLatitudeLayout() throws Exception {
final View decorView = mActivity.getWindow().getDecorView();
ViewAsserts.assertOnScreen(decorView, latitude);
final ViewGroup.LayoutParams layoutParams = latitude.getLayoutParams();
assertNotNull(layoutParams);
assertEquals(layoutParams.width, WindowManager.LayoutParams.WRAP_CONTENT);
assertEquals(layoutParams.height, WindowManager.LayoutParams.WRAP_CONTENT);
tearDown();
}
/**
* Verify Longitude Layout Parameters
* @throws Exception
*/
@MediumTest
public void testLongitudeLayout() throws Exception {
final View decorView = mActivity.getWindow().getDecorView();
ViewAsserts.assertOnScreen(decorView, longitude);
final ViewGroup.LayoutParams layoutParams = longitude.getLayoutParams();
assertNotNull(layoutParams);
assertEquals(layoutParams.width, WindowManager.LayoutParams.WRAP_CONTENT);
assertEquals(layoutParams.height, WindowManager.LayoutParams.WRAP_CONTENT);
tearDown();
}
/**
* Verify CommitButton Layout Parameters
* @throws Exception
*/
@MediumTest
public void testCommitLayout() throws Exception {
final View decorView = mActivity.getWindow().getDecorView();
ViewAsserts.assertOnScreen(decorView, commit);
final ViewGroup.LayoutParams layoutParams = commit.getLayoutParams();
assertNotNull(layoutParams);
assertEquals(layoutParams.width, WindowManager.LayoutParams.WRAP_CONTENT);
assertEquals(layoutParams.height, WindowManager.LayoutParams.WRAP_CONTENT);
tearDown();
}
/**
* Verify CancelButton Layout Parameters
* @throws Exception
*/
@MediumTest
public void testCancleLayout() throws Exception {
final View decorView = mActivity.getWindow().getDecorView();
ViewAsserts.assertOnScreen(decorView, cancel);
final ViewGroup.LayoutParams layoutParams = cancel.getLayoutParams();
assertNotNull(layoutParams);
assertEquals(layoutParams.width, WindowManager.LayoutParams.WRAP_CONTENT);
assertEquals(layoutParams.height, WindowManager.LayoutParams.WRAP_CONTENT);
tearDown();
}
/**
* Test whether the content of the Views are correct.
* @throws Exception
*/
public void testSetupEditPage() throws Exception {
assertEquals("title", title.getText().toString());
assertEquals("content", content.getText().toString());
assertEquals(5.5, Double.parseDouble(latitude.getText().toString()));
assertEquals(10.5, Double.parseDouble(longitude.getText().toString()));
tearDown();
}
// /**
// * Test whether a comment can be pulled from the server and displayed in views used in EditCommentPageActivity <br>
// * Update a comment to the server. Then run the method and check content of the views in EditCommentPageActivity. <br>
// * Methods tested: addOrUpdateComment and loadAndSetSpecificComment.
// * @throws InterruptedException
// */
// public void testSetupEditPage() throws InterruptedException {
// Comment comment = new Comment("Title", "Content", null, null, "User");
// IoStreamHandler ioStreamHandler = new IoStreamHandler();
// Thread thread = new Thread();
//
// EditText title = (EditText)this.getActivity().findViewById(com.example.projectapp.R.id.edit_title);
// EditText content = (EditText)this.getActivity().findViewById(com.example.projectapp.R.id.edit_content);
// EditText latitude = (EditText)this.getActivity().findViewById(com.example.projectapp.R.id.edit_latitude);
// EditText longitude = (EditText)this.getActivity().findViewById(com.example.projectapp.R.id.edit_longitude);
// ImageView picture = (ImageView)this.getActivity().findViewById(com.example.projectapp.R.id.edit_picture);
//
// thread = ioStreamHandler.addOrUpdateComment(comment);
// thread.join();
// Thread.sleep(1000);
// thread = ioStreamHandler.setupEditPage(comment.getId(), title, content, latitude, longitude, picture, this.getActivity());
// thread.join();
// Thread.sleep(1000);
//
// assertEquals("Title", title.getText());
// assertEquals("Content", content.getText());
// assertNotNull(picture.getDrawable());
// ioStreamHandler.clean();
// Thread.sleep(500);
// }
}
| |
// 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.
package com.google.ads.googleads.examples.planning;
import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v10.common.DeviceInfo;
import com.google.ads.googleads.v10.common.GenderInfo;
import com.google.ads.googleads.v10.enums.DeviceEnum.Device;
import com.google.ads.googleads.v10.enums.GenderTypeEnum.GenderType;
import com.google.ads.googleads.v10.enums.ReachPlanAdLengthEnum.ReachPlanAdLength;
import com.google.ads.googleads.v10.enums.ReachPlanAgeRangeEnum.ReachPlanAgeRange;
import com.google.ads.googleads.v10.errors.GoogleAdsError;
import com.google.ads.googleads.v10.errors.GoogleAdsException;
import com.google.ads.googleads.v10.services.CampaignDuration;
import com.google.ads.googleads.v10.services.GenerateProductMixIdeasRequest;
import com.google.ads.googleads.v10.services.GenerateProductMixIdeasResponse;
import com.google.ads.googleads.v10.services.GenerateReachForecastRequest;
import com.google.ads.googleads.v10.services.GenerateReachForecastResponse;
import com.google.ads.googleads.v10.services.ListPlannableLocationsRequest;
import com.google.ads.googleads.v10.services.ListPlannableLocationsResponse;
import com.google.ads.googleads.v10.services.ListPlannableProductsRequest;
import com.google.ads.googleads.v10.services.ListPlannableProductsResponse;
import com.google.ads.googleads.v10.services.PlannableLocation;
import com.google.ads.googleads.v10.services.PlannedProduct;
import com.google.ads.googleads.v10.services.PlannedProductReachForecast;
import com.google.ads.googleads.v10.services.Preferences;
import com.google.ads.googleads.v10.services.ProductAllocation;
import com.google.ads.googleads.v10.services.ProductMetadata;
import com.google.ads.googleads.v10.services.ReachForecast;
import com.google.ads.googleads.v10.services.ReachPlanServiceClient;
import com.google.ads.googleads.v10.services.Targeting;
import com.google.common.base.Joiner;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Demonstrates how to interact with the ReachPlanService to find plannable locations and product
* codes, build a media plan, and generate a video ads reach forecast.
*/
public class ForecastReach {
private static class ForecastReachParams extends CodeSampleParams {
@Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
private Long customerId;
}
public static void main(String[] args) {
ForecastReachParams params = new ForecastReachParams();
if (!params.parseArguments(args)) {
// Either pass the required parameters for this example on the command line, or insert them
// into the code here. See the parameter class definition above for descriptions.
params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
}
GoogleAdsClient googleAdsClient;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
return;
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
return;
}
try {
new ForecastReach().runExample(googleAdsClient, params.customerId);
} catch (GoogleAdsException gae) {
// GoogleAdsException is the base class for most exceptions thrown by an API request.
// Instances of this exception have a message and a GoogleAdsFailure that contains a
// collection of GoogleAdsErrors that indicate the underlying causes of the
// GoogleAdsException.
System.err.printf(
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
gae.getRequestId());
int i = 0;
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
}
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the customer ID for the reach forecast.
*/
private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
String locationId = "2840"; // US
String currencyCode = "USD";
long budgetMicros = 5_000_000L; // $5 USD
try (ReachPlanServiceClient reachPlanServiceClient =
googleAdsClient.getLatestVersion().createReachPlanServiceClient()) {
showPlannableLocations(reachPlanServiceClient);
showPlannableProducts(reachPlanServiceClient, locationId);
forecastManualMix(reachPlanServiceClient, customerId, locationId, currencyCode, budgetMicros);
forecastSuggestedMix(
reachPlanServiceClient, customerId, locationId, currencyCode, budgetMicros);
}
}
/**
* Maps friendly names of plannable locations to location IDs usable with ReachPlanServiceClient.
*
* @param reachPlanServiceClient instance of Reach Plan Service client.
*/
private void showPlannableLocations(ReachPlanServiceClient reachPlanServiceClient) {
ListPlannableLocationsRequest request = ListPlannableLocationsRequest.newBuilder().build();
ListPlannableLocationsResponse response =
reachPlanServiceClient.listPlannableLocations(request);
System.out.println("Plannable Locations:");
for (PlannableLocation location : response.getPlannableLocationsList()) {
System.out.printf(
"Name: %s, ID: %s, ParentCountryId: %s%n",
location.getName(), location.getId(), location.getParentCountryId());
}
}
/**
* Lists plannable products for a given location.
*
* @param reachPlanServiceClient instance of Reach Plan Service client.
* @param locationId location ID to plan for. To find a valid location ID, either see
* https://developers.google.com/google-ads/api/reference/data/geotargets or call
* ReachPlanServiceClient.listPlannableLocations().
*/
// [START forecast_reach_2]
private void showPlannableProducts(
ReachPlanServiceClient reachPlanServiceClient, String locationId) {
ListPlannableProductsRequest request =
ListPlannableProductsRequest.newBuilder().setPlannableLocationId(locationId).build();
ListPlannableProductsResponse response = reachPlanServiceClient.listPlannableProducts(request);
System.out.printf("Plannable Products for location %s:%n", locationId);
for (ProductMetadata product : response.getProductMetadataList()) {
System.out.printf("%s:%n", product.getPlannableProductCode());
System.out.println("Age Ranges:");
for (ReachPlanAgeRange ageRange : product.getPlannableTargeting().getAgeRangesList()) {
System.out.printf("\t- %s%n", ageRange);
}
System.out.println("Genders:");
for (GenderInfo gender : product.getPlannableTargeting().getGendersList()) {
System.out.printf("\t- %s%n", gender.getType());
}
System.out.println("Devices:");
for (DeviceInfo device : product.getPlannableTargeting().getDevicesList()) {
System.out.printf("\t- %s%n", device.getType());
}
}
}
// [END forecast_reach_2]
/**
* Creates a base request to generate a reach forecast.
*
* @param customerId the customer ID for the reach forecast.
* @param productMix the product mix for the reach forecast.
* @param locationId location ID to plan for. To find a valid location ID, either see
* https://developers.google.com/google-ads/api/reference/data/geotargets or call
* ReachPlanServiceClient.ListPlannableLocations.
* @param currencyCode three-character ISO 4217 currency code.
* @return populated GenerateReachForecastRequest object.
*/
private GenerateReachForecastRequest buildReachRequest(
Long customerId, List<PlannedProduct> productMix, String locationId, String currencyCode) {
CampaignDuration duration = CampaignDuration.newBuilder().setDurationInDays(28).build();
List<GenderInfo> genders =
Arrays.asList(
GenderInfo.newBuilder().setType(GenderType.FEMALE).build(),
GenderInfo.newBuilder().setType(GenderType.MALE).build());
List<DeviceInfo> devices =
Arrays.asList(
DeviceInfo.newBuilder().setType(Device.DESKTOP).build(),
DeviceInfo.newBuilder().setType(Device.MOBILE).build(),
DeviceInfo.newBuilder().setType(Device.TABLET).build());
Targeting targeting =
Targeting.newBuilder()
.setPlannableLocationId(locationId)
.setAgeRange(ReachPlanAgeRange.AGE_RANGE_18_65_UP)
.addAllGenders(genders)
.addAllDevices(devices)
.build();
// See the docs for defaults and valid ranges:
// https://developers.google.com/google-ads/api/reference/rpc/latest/GenerateReachForecastRequest
return GenerateReachForecastRequest.newBuilder()
.setCustomerId(Long.toString(customerId))
.setCurrencyCode(currencyCode)
.setCampaignDuration(duration)
.setTargeting(targeting)
.setMinEffectiveFrequency(1)
.addAllPlannedProducts(productMix)
.build();
}
/**
* Pulls and prints the reach curve for the given request.
*
* @param reachPlanServiceClient instance of Reach Plan Service client.
* @param request an already-populated reach curve request.
*/
// [START forecast_reach]
private void getReachCurve(
ReachPlanServiceClient reachPlanServiceClient, GenerateReachForecastRequest request) {
GenerateReachForecastResponse response = reachPlanServiceClient.generateReachForecast(request);
System.out.println("Reach curve output:");
System.out.println(
"Currency, Cost Micros, On-Target Reach, On-Target Imprs, Total Reach, Total Imprs,"
+ " Products");
for (ReachForecast point : response.getReachCurve().getReachForecastsList()) {
System.out.printf(
"%s, \"",
Joiner.on(", ")
.join(
request.getCurrencyCode(),
String.valueOf(point.getCostMicros()),
String.valueOf(point.getForecast().getOnTargetReach()),
String.valueOf(point.getForecast().getOnTargetImpressions()),
String.valueOf(point.getForecast().getTotalReach()),
String.valueOf(point.getForecast().getTotalImpressions())));
for (PlannedProductReachForecast product : point.getPlannedProductReachForecastsList()) {
System.out.printf("[Product: %s, ", product.getPlannableProductCode());
System.out.printf("Budget Micros: %s]", product.getCostMicros());
}
System.out.printf("\"%n");
}
}
// [END forecast_reach]
/**
* Pulls a forecast for a budget split 15% and 85% between two products.
*
* @param reachPlanServiceClient instance of Reach Plan Service client.
* @param customerId the customer ID for the reach forecast.
* @param locationId location ID to plan for. To find a valid location ID, either see
* https://developers.google.com/google-ads/api/reference/data/geotargets or call
* ReachPlanServiceClient.listPlannableLocations().
* @param currencyCode three-character ISO 4217 currency code.
* @param budgetMicros budget in currency to plan for.
*/
// [START forecast_reach_3]
private void forecastManualMix(
ReachPlanServiceClient reachPlanServiceClient,
long customerId,
String locationId,
String currencyCode,
long budgetMicros) {
List<PlannedProduct> productMix = new ArrayList<>();
// Set up a ratio to split the budget between two products.
double trueviewAllocation = 0.15;
double bumperAllocation = 1 - trueviewAllocation;
// See listPlannableProducts on ReachPlanService to retrieve a list
// of valid PlannableProductCode's for a given location:
// https://developers.google.com/google-ads/api/reference/rpc/latest/ReachPlanService
productMix.add(
PlannedProduct.newBuilder()
.setPlannableProductCode("TRUEVIEW_IN_STREAM")
.setBudgetMicros((long) (budgetMicros * bumperAllocation))
.build());
productMix.add(
PlannedProduct.newBuilder()
.setPlannableProductCode("BUMPER")
.setBudgetMicros((long) (budgetMicros * bumperAllocation))
.build());
GenerateReachForecastRequest request =
buildReachRequest(customerId, productMix, locationId, currencyCode);
getReachCurve(reachPlanServiceClient, request);
}
// [END forecast_reach_3]
/**
* Pulls a forecast for a product mix suggested based on preferences for whether the ad would have
* a guaranteed price, play with sound, would be skippable, would include top content, and have a
* desired ad length.
*
* @param reachPlanServiceClient instance of Reach Plan Service client.
* @param customerId the customer ID for the reach forecast.
* @param locationId location ID to plan for. To find a valid location ID, either see
* https://developers.google.com/adwords/api/docs/appendix/geotargeting or call
* ReachPlanServiceClient.ListPlannableLocations.
* @param currencyCode three-character ISO 4217 currency code.
* @param budgetMicros budget in currency to plan for.
*/
// [START forecast_reach_1]
private void forecastSuggestedMix(
ReachPlanServiceClient reachPlanServiceClient,
long customerId,
String locationId,
String currencyCode,
long budgetMicros) {
// Note: If preferences are too restrictive, then the response will be empty.
Preferences preferences =
Preferences.newBuilder()
.setHasGuaranteedPrice(true)
.setStartsWithSound(true)
.setIsSkippable(false)
.setTopContentOnly(true)
.setAdLength(ReachPlanAdLength.FIFTEEN_OR_TWENTY_SECONDS)
.build();
GenerateProductMixIdeasRequest mixRequest =
GenerateProductMixIdeasRequest.newBuilder()
.setBudgetMicros(budgetMicros)
.setCurrencyCode(currencyCode)
.setCustomerId(Long.toString(customerId))
.setPlannableLocationId(locationId)
.setPreferences(preferences)
.build();
GenerateProductMixIdeasResponse mixResponse =
reachPlanServiceClient.generateProductMixIdeas(mixRequest);
List<PlannedProduct> productMix = new ArrayList<>();
for (ProductAllocation product : mixResponse.getProductAllocationList()) {
productMix.add(
PlannedProduct.newBuilder()
.setPlannableProductCode(product.getPlannableProductCode())
.setBudgetMicros(product.getBudgetMicros())
.build());
}
GenerateReachForecastRequest curveRequest =
buildReachRequest(customerId, productMix, locationId, currencyCode);
getReachCurve(reachPlanServiceClient, curveRequest);
}
// [END forecast_reach_1]
}
| |
/*
* 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;
import java.io.Externalizable;
import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.HashSet;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.GridDirectCollection;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.plugin.extensions.communication.MessageCollectionItemType;
import org.apache.ignite.plugin.extensions.communication.MessageReader;
import org.apache.ignite.plugin.extensions.communication.MessageWriter;
/**
* Cache eviction response.
*/
public class GridCacheEvictionResponse extends GridCacheMessage {
/** */
private static final long serialVersionUID = 0L;
/** Future ID. */
private long futId;
/** Rejected keys. */
@GridToStringInclude
@GridDirectCollection(KeyCacheObject.class)
private Collection<KeyCacheObject> rejectedKeys = new HashSet<>();
/** Flag to indicate whether request processing has finished with error. */
private boolean err;
/**
* Required by {@link Externalizable}.
*/
public GridCacheEvictionResponse() {
// No-op.
}
/**
* @param cacheId Cache ID.
* @param futId Future ID.
*/
GridCacheEvictionResponse(int cacheId, long futId) {
this(cacheId, futId, false);
}
/**
* @param cacheId Cache ID.
* @param futId Future ID.
* @param err {@code True} if request processing has finished with error.
*/
GridCacheEvictionResponse(int cacheId, long futId, boolean err) {
this.cacheId = cacheId;
this.futId = futId;
this.err = err;
}
/** {@inheritDoc}
* @param ctx*/
@Override public void prepareMarshal(GridCacheSharedContext ctx) throws IgniteCheckedException {
super.prepareMarshal(ctx);
prepareMarshalCacheObjects(rejectedKeys, ctx.cacheContext(cacheId));
}
/** {@inheritDoc} */
@Override public void finishUnmarshal(GridCacheSharedContext ctx, ClassLoader ldr) throws IgniteCheckedException {
super.finishUnmarshal(ctx, ldr);
finishUnmarshalCacheObjects(rejectedKeys, ctx.cacheContext(cacheId), ldr);
}
/** {@inheritDoc} */
@Override public boolean addDeploymentInfo() {
return false;
}
/**
* @return Future ID.
*/
long futureId() {
return futId;
}
/**
* @return Rejected keys.
*/
Collection<KeyCacheObject> rejectedKeys() {
return rejectedKeys;
}
/**
* Add rejected key to response.
*
* @param key Evicted key.
*/
void addRejected(KeyCacheObject key) {
assert key != null;
rejectedKeys.add(key);
}
/**
* @return {@code True} if request processing has finished with error.
*/
boolean evictError() {
return err;
}
/** {@inheritDoc} */
@Override public boolean ignoreClassErrors() {
return true;
}
/** {@inheritDoc} */
@Override public boolean writeTo(ByteBuffer buf, MessageWriter writer) {
writer.setBuffer(buf);
if (!super.writeTo(buf, writer))
return false;
if (!writer.isHeaderWritten()) {
if (!writer.writeHeader(directType(), fieldsCount()))
return false;
writer.onHeaderWritten();
}
switch (writer.state()) {
case 3:
if (!writer.writeBoolean("err", err))
return false;
writer.incrementState();
case 4:
if (!writer.writeLong("futId", futId))
return false;
writer.incrementState();
case 5:
if (!writer.writeCollection("rejectedKeys", rejectedKeys, MessageCollectionItemType.MSG))
return false;
writer.incrementState();
}
return true;
}
/** {@inheritDoc} */
@Override public boolean readFrom(ByteBuffer buf, MessageReader reader) {
reader.setBuffer(buf);
if (!reader.beforeMessageRead())
return false;
if (!super.readFrom(buf, reader))
return false;
switch (reader.state()) {
case 3:
err = reader.readBoolean("err");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 4:
futId = reader.readLong("futId");
if (!reader.isLastRead())
return false;
reader.incrementState();
case 5:
rejectedKeys = reader.readCollection("rejectedKeys", MessageCollectionItemType.MSG);
if (!reader.isLastRead())
return false;
reader.incrementState();
}
return reader.afterMessageRead(GridCacheEvictionResponse.class);
}
/** {@inheritDoc} */
@Override public byte directType() {
return 15;
}
/** {@inheritDoc} */
@Override public byte fieldsCount() {
return 6;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GridCacheEvictionResponse.class, this);
}
}
| |
package com.planet_ink.coffee_mud.Abilities.Traps;
import com.planet_ink.coffee_mud.Abilities.StdAbility;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2014 Bo Zimmerman
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.
*/
@SuppressWarnings({"unchecked","rawtypes"})
public class Trap_Trap extends StdAbility implements Trap
{
@Override public String ID() { return "Trap_Trap"; }
private final static String localizedName = CMLib.lang()._("a Trap!");
@Override public String name() { return localizedName; }
@Override protected int canAffectCode(){return Ability.CAN_EXITS|Ability.CAN_ROOMS|Ability.CAN_ITEMS;}
@Override protected int canTargetCode(){return 0;}
protected static MOB benefactor=CMClass.getMOB("StdMOB");
protected boolean sprung=false;
protected Room myPit=null;
protected Room myPitUp=null;
protected int reset=60; // 5 minute reset is standard
protected int trapType(){return CMLib.dice().roll(1,3,-1);}
public Trap_Trap()
{
super();
if(benefactor==null)
benefactor=CMClass.getMOB("StdMOB");
}
@Override public void activateBomb(){}
@Override public boolean isABomb(){return false;}
@Override public boolean sprung(){return sprung;}
@Override public boolean disabled(){return sprung;}
@Override public void disable(){ sprung=true;}
@Override public void setReset(int Reset){reset=Reset;}
@Override public int getReset(){return reset;}
// as these are not standard traps, we return this!
@Override public boolean maySetTrap(MOB mob, int asLevel){return false;}
@Override public boolean canSetTrapOn(MOB mob, Physical P){return false;}
@Override public List<Item> getTrapComponents() { return new Vector(); }
@Override public String requiresToSet(){return "";}
@Override
public Trap setTrap(MOB mob, Physical P, int trapBonus, int qualifyingClassLevel, boolean perm)
{
if(P==null) return null;
int level=mob.phyStats().level();
if(level<qualifyingClassLevel) level=qualifyingClassLevel;
level+=trapBonus;
if(level>=100) level=99;
final int rejuv=((100-level)*30);
final Trap T=(Trap)copyOf();
T.setReset(rejuv);
T.setInvoker(mob);
P.addEffect(T);
T.setAbilityCode(trapBonus);
if(perm)
{
T.setSavable(true);
T.makeNonUninvokable();
}
else
{
T.setSavable(false);
CMLib.threads().startTickDown(T,Tickable.TICKID_TRAP_DESTRUCTION,level*30);
}
return T;
}
public void gas(MOB mob)
{
if(CMLib.dice().rollPercentage()<mob.charStats().getSave(CharStats.STAT_SAVE_TRAPS))
mob.location().show(mob,affected,this,CMMsg.MSG_OK_ACTION,_("<S-NAME> avoid(s) a gas trap set in <T-NAME>."));
else
if(mob.location().show(mob,affected,this,CMMsg.MSG_OK_ACTION,_("<S-NAME> trigger(s) a trap set in <T-NAME>!")))
if(mob.phyStats().level()>15)
{
mob.location().showHappens(CMMsg.MSG_OK_ACTION,_("The room fills with gas!"));
for(int i=0;i<mob.location().numInhabitants();i++)
{
final MOB target=mob.location().fetchInhabitant(i);
if(target==null) break;
int dmg=CMLib.dice().roll(target.phyStats().level(),10,1);
final CMMsg msg=CMClass.getMsg(invoker(),target,this,CMMsg.MSG_OK_ACTION,CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_GAS,CMMsg.MSG_NOISYMOVEMENT,null);
if(target.location().okMessage(target,msg))
{
target.location().send(target,msg);
if(msg.value()>0)
dmg=(int)Math.round(CMath.div(dmg,2.0));
CMLib.combat().postDamage(invoker(),target,this,dmg,CMMsg.MASK_ALWAYS|CMMsg.MASK_MALICIOUS|CMMsg.TYP_GAS,Weapon.TYPE_GASSING,"The gas <DAMAGE> <T-NAME>!");
}
}
}
else
{
final MOB target=mob;
int dmg=CMLib.dice().roll(target.phyStats().level(),10,1);
final CMMsg msg=CMClass.getMsg(invoker(),target,this,CMMsg.MSG_OK_ACTION,CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_GAS,CMMsg.MSG_NOISYMOVEMENT,null);
if(target.location().okMessage(target,msg))
{
target.location().send(target,msg);
if(msg.value()>0)
dmg=(int)Math.round(CMath.div(dmg,2.0));
CMLib.combat().postDamage(invoker(),target,this,dmg,CMMsg.MASK_ALWAYS|CMMsg.MASK_MALICIOUS|CMMsg.TYP_GAS,Weapon.TYPE_GASSING,"A sudden blast of gas <DAMAGE> <T-NAME>!");
}
}
}
public void needle(MOB mob)
{
if(CMLib.dice().rollPercentage()<mob.charStats().getSave(CharStats.STAT_SAVE_TRAPS))
mob.location().show(mob,affected,this,CMMsg.MSG_OK_ACTION,_("<S-NAME> avoid(s) a needle trap set in <T-NAME>."));
else
if(mob.location().show(mob,affected,this,CMMsg.MSG_OK_ACTION,_("<S-NAME> trigger(s) a needle trap set in <T-NAME>!")))
{
final MOB target=mob;
int dmg=CMLib.dice().roll(target.phyStats().level(),5,1);
final CMMsg msg=CMClass.getMsg(invoker(),target,this,CMMsg.MSG_OK_ACTION,CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_JUSTICE,CMMsg.MSG_NOISYMOVEMENT,null);
if(target.location().okMessage(target,msg))
{
target.location().send(target,msg);
if(msg.value()>0)
dmg=(int)Math.round(CMath.div(dmg,2.0));
CMLib.combat().postDamage(invoker(),target,this,dmg,CMMsg.MASK_ALWAYS|CMMsg.MASK_MALICIOUS|CMMsg.TYP_JUSTICE,Weapon.TYPE_PIERCING,"The needle <DAMAGE> <T-NAME>!");
final Ability P=CMClass.getAbility("Poison");
if(P!=null) P.invoke(invoker(),target,true,0);
}
}
}
public void blade(MOB mob)
{
if(CMLib.dice().rollPercentage()<mob.charStats().getSave(CharStats.STAT_SAVE_TRAPS))
mob.location().show(mob,affected,this,CMMsg.MSG_OK_ACTION,_("<S-NAME> avoid(s) a blade trap set in <T-NAME>."));
else
if(mob.location().show(mob,affected,this,CMMsg.MSG_OK_ACTION,_("<S-NAME> trigger(s) a blade trap set in <T-NAME>!")))
{
final MOB target=mob;
int dmg=CMLib.dice().roll(target.phyStats().level(),2,0);
final CMMsg msg=CMClass.getMsg(invoker(),target,this,CMMsg.MSG_OK_ACTION,CMMsg.MSK_MALICIOUS_MOVE|CMMsg.TYP_JUSTICE,CMMsg.MSG_NOISYMOVEMENT,null);
if(target.location().okMessage(target,msg))
{
target.location().send(target,msg);
if(msg.value()>0)
dmg=(int)Math.round(CMath.div(dmg,2.0));
final Ability P=CMClass.getAbility("Poison");
if(P!=null) P.invoke(invoker(),target,true,0);
CMLib.combat().postDamage(invoker(),target,this,dmg,CMMsg.MASK_ALWAYS|CMMsg.MASK_MALICIOUS|CMMsg.TYP_JUSTICE,Weapon.TYPE_PIERCING,"The blade <DAMAGE> <T-NAME>!");
}
}
}
public void victimOfSpell(MOB mob)
{
if(CMLib.dice().rollPercentage()<mob.charStats().getSave(CharStats.STAT_SAVE_TRAPS))
mob.location().show(mob,affected,this,CMMsg.MSG_OK_ACTION,_("<S-NAME> avoid(s) a magic trap set in <T-NAME>."));
else
if(mob.location().show(mob,affected,this,CMMsg.MSG_OK_ACTION,_("<S-NAME> trigger(s) a trap set in <T-NAME>!")))
{
String spell=text();
final int x=spell.indexOf(';');
Vector V=new Vector();
V.addElement(mob.name());
if(x>0)
{
V=CMParms.parse(spell.substring(x+1));
V.insertElementAt(mob.name(),0);
spell=spell.substring(0,x);
}
final Ability A=CMClass.findAbility(spell);
if(A==null)
{
mob.location().showHappens(CMMsg.MSG_OK_VISUAL,_("But nothing happened..."));
return;
}
A.invoke(invoker(),V,mob,true,0);
}
}
public void fallInPit(MOB mob)
{
if(CMLib.flags().isInFlight(mob))
{
mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,_("<S-NAME> trigger(s) a trap door beneath <S-HIS-HER> feet! <S-NAME> pause(s) over it in flight."));
return;
}
else
if(CMLib.dice().rollPercentage()<mob.charStats().getSave(CharStats.STAT_SAVE_TRAPS))
mob.location().show(mob,affected,this,CMMsg.MSG_OK_ACTION,_("<S-NAME> avoid(s) a trap door beneath <S-HIS-HER> feet."));
else
if(mob.location().show(mob,affected,this,CMMsg.MSG_OK_ACTION,_("<S-NAME> trigger(s) a trap door beneath <S-HIS-HER> feet! <S-NAME> fall(s) in!")))
{
if((myPit==null)||(myPitUp==null))
{
myPitUp=CMClass.getLocale("ClimbableSurface");
myPitUp.setRoomID("");
myPitUp.setSavable(false);
myPitUp.setArea(mob.location().getArea());
myPitUp.basePhyStats().setDisposition(myPitUp.basePhyStats().disposition()|PhyStats.IS_DARK);
myPitUp.setDisplayText(_("Inside a dark pit"));
myPitUp.setDescription(_("The walls here are slick and tall. The trap door is just above you."));
myPitUp.recoverPhyStats();
myPit=CMClass.getLocale("StdRoom");
myPit.setSavable(false);
myPit.setRoomID("");
myPit.setArea(mob.location().getArea());
myPit.basePhyStats().setDisposition(myPit.basePhyStats().disposition()|PhyStats.IS_DARK);
myPit.setDisplayText(_("Inside a dark pit"));
myPit.setDescription(_("The walls here are slick and tall. You can barely see the trap door well above you."));
myPit.setRawExit(Directions.UP,CMClass.getExit("StdOpenDoorway"));
myPit.rawDoors()[Directions.UP]=myPitUp;
myPitUp.recoverPhyStats();
}
final Exit exit=CMClass.getExit("StdClosedDoorway");
exit.setSavable(false);
myPitUp.setRawExit(Directions.UP,exit);
myPitUp.rawDoors()[Directions.UP]=mob.location();
if((mob.location().getRoomInDir(Directions.DOWN)==null)
&&(mob.location().getExitInDir(Directions.DOWN)==null))
{
mob.location().setRawExit(Directions.DOWN,exit);
mob.location().rawDoors()[Directions.DOWN]=myPitUp;
}
myPit.bringMobHere(mob,false);
if(mob.phyStats().weight()<5)
mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,_("<S-NAME> float(s) gently into the pit!"));
else
{
mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,_("<S-NAME> hit(s) the pit floor with a THUMP!"));
final int damage=CMLib.dice().roll(mob.phyStats().level(),3,1);
CMLib.combat().postDamage(invoker(),mob,this,damage,CMMsg.MASK_MALICIOUS|CMMsg.TYP_JUSTICE,-1,null);
}
CMLib.commands().postLook(mob,true);
}
}
@Override
public MOB invoker()
{
if(invoker==null) return benefactor;
return super.invoker();
}
@Override
public int classificationCode()
{
return Ability.ACODE_TRAP;
}
@Override
public void spring(MOB target)
{
sprung=true;
benefactor.setLocation(target.location());
benefactor.basePhyStats().setLevel(target.phyStats().level());
benefactor.recoverCharStats();
benefactor.recoverPhyStats();
switch(trapType())
{
case TRAP_GAS:
gas(target);
break;
case TRAP_NEEDLE:
needle(target);
break;
case TRAP_PIT_BLADE:
if(affected instanceof Exit)
fallInPit(target);
else
blade(target);
break;
case TRAP_SPELL:
victimOfSpell(target);
break;
default:
target.location().show(target,null,CMMsg.MSG_OK_ACTION,_("<S-NAME> trigger(s) a trap, but it appears to have misfired."));
break;
}
if((getReset()>0)&&(getReset()<Integer.MAX_VALUE))
CMLib.threads().startTickDown(this,Tickable.TICKID_TRAP_RESET,getReset());
else
unInvoke();
}
@Override
public void unInvoke()
{
if((trapType()==Trap.TRAP_PIT_BLADE)
&&(affected instanceof Exit)
&&(myPit!=null)
&&(canBeUninvoked())
&&(myPitUp!=null))
{
final Room R=myPitUp.getRoomInDir(Directions.UP);
if((R!=null)&&(R.getRoomInDir(Directions.DOWN)==myPitUp))
{
R.rawDoors()[Directions.DOWN]=null;
R.setRawExit(Directions.DOWN,null);
}
/**
don't do this, cuz someone might still be down there.
myPitUp.rawDoors()[Directions.UP]=null;
myPitUp.getRawExit(Directions.UP]=null;
myPitUp.rawDoors()[Directions.DOWN]=null;
myPitUp.getRawExit(Directions.DOWN]=null;
myPit.rawDoors()[Directions.UP]=null;
myPit.getRawExit(Directions.UP]=null;
*/
if(myPit!=null) myPit.destroy();
if(myPitUp!=null) myPitUp.destroy();
}
super.unInvoke();
}
@Override
public boolean tick(Tickable ticking, int tickID)
{
if(!super.tick(ticking,tickID))
return false;
if(tickID==Tickable.TICKID_TRAP_RESET)
{
sprung=false;
return false;
}
else
if(tickID==Tickable.TICKID_TRAP_DESTRUCTION)
{
unInvoke();
return false;
}
return true;
}
}
| |
/*
* Generated by Abacus.
*/
package com.landawn.abacus.entity;
import java.util.List;
import java.util.Map;
import com.landawn.abacus.util.BiMap;
import com.landawn.abacus.util.N;
/**
* Generated by Abacus. DO NOT edit it!
* @version ${version}
*/
public interface CodesPNL {
public static final String _DN = "codes".intern();
public static interface LoginPNL {
/**
* Name of "Login" entity.
*/
public static final String _ = "Login".intern();
/**
* Name of "id" property.
* type: long.
* column: "id".
*/
public static final String ID = (_ + ".id").intern();
/**
* Name of "accountId" property.
* type: long.
* column: "account_id".
*/
public static final String ACCOUNT_ID = (_ + ".accountId").intern();
/**
* Name of "loginId" property.
* type: String.
* column: "login_id".
*/
public static final String LOGIN_ID = (_ + ".loginId").intern();
/**
* Name of "loginPassword" property.
* type: String.
* column: "login_password".
*/
public static final String LOGIN_PASSWORD = (_ + ".loginPassword").intern();
/**
* Name of "status" property.
* type: int.
* column: "status".
*/
public static final String STATUS = (_ + ".status").intern();
/**
* Name of "lastUpdateTime" property.
* type: Timestamp.
* column: "last_update_time".
*/
public static final String LAST_UPDATE_TIME = (_ + ".lastUpdateTime").intern();
/**
* Name of "createTime" property.
* type: Timestamp.
* column: "create_time".
*/
public static final String CREATE_TIME = (_ + ".createTime").intern();
/**
* Immutable property name list
*/
public static final List<String> _PNL = N.asUnmodifiableList(ID, ACCOUNT_ID, LOGIN_ID, LOGIN_PASSWORD, STATUS, LAST_UPDATE_TIME, CREATE_TIME);
/**
* Immutable property name to entityName.propName mapper
*/
@SuppressWarnings("rawtypes")
public static final BiMap<String, String> _PNM = N.asUnmodifiableBiMapForInterface((Map)N.asLinkedHashMap(ID, "id".intern(), ACCOUNT_ID, "accountId".intern(), LOGIN_ID, "loginId".intern(), LOGIN_PASSWORD, "loginPassword".intern(), STATUS, "status".intern(), LAST_UPDATE_TIME, "lastUpdateTime".intern(), CREATE_TIME, "createTime".intern()));
/**
* Immutable property name to column name mapper
*/
@SuppressWarnings("rawtypes")
public static final BiMap<String, String> _PCM = N.asUnmodifiableBiMapForInterface((Map)N.asLinkedHashMap(ID, "login.id".intern(), ACCOUNT_ID, "login.account_id".intern(), LOGIN_ID, "login.login_id".intern(), LOGIN_PASSWORD, "login.login_password".intern(), STATUS, "login.status".intern(), LAST_UPDATE_TIME, "login.last_update_time".intern(), CREATE_TIME, "login.create_time".intern()));
/**
* Immutable column name list
*/
public static final List<String> _CNL = N.asUnmodifiableList("login.id".intern(), "login.account_id".intern(), "login.login_id".intern(), "login.login_password".intern(), "login.status".intern(), "login.last_update_time".intern(), "login.create_time".intern());
/**
* Immutable column name to tableName.columnName mapper
*/
@SuppressWarnings("rawtypes")
public static final BiMap<String, String> _CNM = N.asUnmodifiableBiMapForInterface((Map)N.asLinkedHashMap("login.id".intern(), "id".intern(), "login.account_id".intern(), "account_id".intern(), "login.login_id".intern(), "login_id".intern(), "login.login_password".intern(), "login_password".intern(), "login.status".intern(), "status".intern(), "login.last_update_time".intern(), "last_update_time".intern(), "login.create_time".intern(), "create_time".intern()));
}
public static interface AccountDevicePNL {
/**
* Name of "AccountDevice" entity.
*/
public static final String _ = "AccountDevice".intern();
/**
* Name of "id" property.
* type: long.
* column: "id".
*/
public static final String ID = (_ + ".id").intern();
/**
* Name of "accountId" property.
* type: long.
* column: "account_id".
*/
public static final String ACCOUNT_ID = (_ + ".accountId").intern();
/**
* Name of "name" property.
* type: String.
* column: "name".
*/
public static final String NAME = (_ + ".name").intern();
/**
* Name of "UDID" property.
* type: String.
* column: "udid".
*/
public static final String UDID = (_ + ".UDID").intern();
/**
* Name of "platform" property.
* type: String.
* column: "platform".
*/
public static final String PLATFORM = (_ + ".platform").intern();
/**
* Name of "model" property.
* type: String.
* column: "model".
*/
public static final String MODEL = (_ + ".model").intern();
/**
* Name of "manufacturer" property.
* type: String.
* column: "manufacturer".
*/
public static final String MANUFACTURER = (_ + ".manufacturer").intern();
/**
* Name of "produceTime" property.
* type: Timestamp.
* column: "produce_time".
*/
public static final String PRODUCE_TIME = (_ + ".produceTime").intern();
/**
* Name of "category" property.
* type: String.
* column: "category".
*/
public static final String CATEGORY = (_ + ".category").intern();
/**
* Name of "description" property.
* type: String.
* column: "description".
*/
public static final String DESCRIPTION = (_ + ".description").intern();
/**
* Name of "status" property.
* type: int.
* column: "status".
*/
public static final String STATUS = (_ + ".status").intern();
/**
* Name of "lastUpdateTime" property.
* type: Timestamp.
* column: "last_update_time".
*/
public static final String LAST_UPDATE_TIME = (_ + ".lastUpdateTime").intern();
/**
* Name of "createTime" property.
* type: Timestamp.
* column: "create_time".
*/
public static final String CREATE_TIME = (_ + ".createTime").intern();
/**
* Immutable property name list
*/
public static final List<String> _PNL = N.asUnmodifiableList(ID, ACCOUNT_ID, NAME, UDID, PLATFORM, MODEL, MANUFACTURER, PRODUCE_TIME, CATEGORY, DESCRIPTION, STATUS, LAST_UPDATE_TIME, CREATE_TIME);
/**
* Immutable property name to entityName.propName mapper
*/
@SuppressWarnings("rawtypes")
public static final BiMap<String, String> _PNM = N.asUnmodifiableBiMapForInterface((Map)N.asLinkedHashMap(ID, "id".intern(), ACCOUNT_ID, "accountId".intern(), NAME, "name".intern(), UDID, "UDID".intern(), PLATFORM, "platform".intern(), MODEL, "model".intern(), MANUFACTURER, "manufacturer".intern(), PRODUCE_TIME, "produceTime".intern(), CATEGORY, "category".intern(), DESCRIPTION, "description".intern(), STATUS, "status".intern(), LAST_UPDATE_TIME, "lastUpdateTime".intern(), CREATE_TIME, "createTime".intern()));
/**
* Immutable property name to column name mapper
*/
@SuppressWarnings("rawtypes")
public static final BiMap<String, String> _PCM = N.asUnmodifiableBiMapForInterface((Map)N.asLinkedHashMap(ID, "account_device.id".intern(), ACCOUNT_ID, "account_device.account_id".intern(), NAME, "account_device.name".intern(), UDID, "account_device.udid".intern(), PLATFORM, "account_device.platform".intern(), MODEL, "account_device.model".intern(), MANUFACTURER, "account_device.manufacturer".intern(), PRODUCE_TIME, "account_device.produce_time".intern(), CATEGORY, "account_device.category".intern(), DESCRIPTION, "account_device.description".intern(), STATUS, "account_device.status".intern(), LAST_UPDATE_TIME, "account_device.last_update_time".intern(), CREATE_TIME, "account_device.create_time".intern()));
/**
* Immutable column name list
*/
public static final List<String> _CNL = N.asUnmodifiableList("account_device.id".intern(), "account_device.account_id".intern(), "account_device.name".intern(), "account_device.udid".intern(), "account_device.platform".intern(), "account_device.model".intern(), "account_device.manufacturer".intern(), "account_device.produce_time".intern(), "account_device.category".intern(), "account_device.description".intern(), "account_device.status".intern(), "account_device.last_update_time".intern(), "account_device.create_time".intern());
/**
* Immutable column name to tableName.columnName mapper
*/
@SuppressWarnings("rawtypes")
public static final BiMap<String, String> _CNM = N.asUnmodifiableBiMapForInterface((Map)N.asLinkedHashMap("account_device.id".intern(), "id".intern(), "account_device.account_id".intern(), "account_id".intern(), "account_device.name".intern(), "name".intern(), "account_device.udid".intern(), "udid".intern(), "account_device.platform".intern(), "platform".intern(), "account_device.model".intern(), "model".intern(), "account_device.manufacturer".intern(), "manufacturer".intern(), "account_device.produce_time".intern(), "produce_time".intern(), "account_device.category".intern(), "category".intern(), "account_device.description".intern(), "description".intern(), "account_device.status".intern(), "status".intern(), "account_device.last_update_time".intern(), "last_update_time".intern(), "account_device.create_time".intern(), "create_time".intern()));
}
public static interface AccountPNL {
/**
* Name of "Account" entity.
*/
public static final String _ = "Account".intern();
/**
* Name of "id" property.
* type: long.
* column: "id".
*/
public static final String ID = (_ + ".id").intern();
/**
* Name of "gui" property.
* type: String.
* column: "gui".
*/
public static final String GUI = (_ + ".gui").intern();
/**
* Name of "firstName" property.
* type: String.
* column: "first_name".
*/
public static final String FIRST_NAME = (_ + ".firstName").intern();
/**
* Name of "lastName" property.
* type: String.
* column: "last_name".
*/
public static final String LAST_NAME = (_ + ".lastName").intern();
/**
* Name of "status" property.
* type: int.
* column: "status".
*/
public static final String STATUS = (_ + ".status").intern();
/**
* Name of "lastUpdateTime" property.
* type: Timestamp.
* column: "last_update_time".
*/
public static final String LAST_UPDATE_TIME = (_ + ".lastUpdateTime").intern();
/**
* Name of "createTime" property.
* type: Timestamp.
* column: "create_time".
*/
public static final String CREATE_TIME = (_ + ".createTime").intern();
/**
* Name of "devices" property.
* type: List<com.landawn.abacus.entity.AccountDevice>.
* column: "AccountDevice".
*/
public static final String DEVICES = (_ + ".devices").intern();
/**
* Immutable property name list
*/
public static final List<String> _PNL = N.asUnmodifiableList(ID, GUI, FIRST_NAME, LAST_NAME, STATUS, LAST_UPDATE_TIME, CREATE_TIME, DEVICES);
/**
* Immutable property name to entityName.propName mapper
*/
@SuppressWarnings("rawtypes")
public static final BiMap<String, String> _PNM = N.asUnmodifiableBiMapForInterface((Map)N.asLinkedHashMap(ID, "id".intern(), GUI, "gui".intern(), FIRST_NAME, "firstName".intern(), LAST_NAME, "lastName".intern(), STATUS, "status".intern(), LAST_UPDATE_TIME, "lastUpdateTime".intern(), CREATE_TIME, "createTime".intern(), DEVICES, "devices".intern()));
/**
* Immutable property name to column name mapper
*/
@SuppressWarnings("rawtypes")
public static final BiMap<String, String> _PCM = N.asUnmodifiableBiMapForInterface((Map)N.asLinkedHashMap(ID, "account.id".intern(), GUI, "account.gui".intern(), FIRST_NAME, "account.first_name".intern(), LAST_NAME, "account.last_name".intern(), STATUS, "account.status".intern(), LAST_UPDATE_TIME, "account.last_update_time".intern(), CREATE_TIME, "account.create_time".intern()));
/**
* Immutable column name list
*/
public static final List<String> _CNL = N.asUnmodifiableList("account.id".intern(), "account.gui".intern(), "account.first_name".intern(), "account.last_name".intern(), "account.status".intern(), "account.last_update_time".intern(), "account.create_time".intern());
/**
* Immutable column name to tableName.columnName mapper
*/
@SuppressWarnings("rawtypes")
public static final BiMap<String, String> _CNM = N.asUnmodifiableBiMapForInterface((Map)N.asLinkedHashMap("account.id".intern(), "id".intern(), "account.gui".intern(), "gui".intern(), "account.first_name".intern(), "first_name".intern(), "account.last_name".intern(), "last_name".intern(), "account.status".intern(), "status".intern(), "account.last_update_time".intern(), "last_update_time".intern(), "account.create_time".intern(), "create_time".intern()));
}
public static final String ACCOUNT_ID = "accountId".intern();
public static final String CATEGORY = "category".intern();
public static final String CREATE_TIME = "createTime".intern();
public static final String DESCRIPTION = "description".intern();
public static final String DEVICES = "devices".intern();
public static final String FIRST_NAME = "firstName".intern();
public static final String GUI = "gui".intern();
public static final String ID = "id".intern();
public static final String LAST_NAME = "lastName".intern();
public static final String LAST_UPDATE_TIME = "lastUpdateTime".intern();
public static final String LOGIN_ID = "loginId".intern();
public static final String LOGIN_PASSWORD = "loginPassword".intern();
public static final String MANUFACTURER = "manufacturer".intern();
public static final String MODEL = "model".intern();
public static final String NAME = "name".intern();
public static final String PLATFORM = "platform".intern();
public static final String PRODUCE_TIME = "produceTime".intern();
public static final String STATUS = "status".intern();
public static final String UDID = "UDID".intern();
/**
* Mapping of property name to column name
*/
@SuppressWarnings("rawtypes")
public static final BiMap<String, String> _PCM = N.asUnmodifiableBiMapForInterface((Map) N.asLinkedHashMap(ACCOUNT_ID, "account_id".intern(), CATEGORY, "category".intern(), CREATE_TIME, "create_time".intern(), DESCRIPTION, "description".intern(), FIRST_NAME, "first_name".intern(), GUI, "gui".intern(), ID, "id".intern(), LAST_NAME, "last_name".intern(), LAST_UPDATE_TIME, "last_update_time".intern(), LOGIN_ID, "login_id".intern(), LOGIN_PASSWORD, "login_password".intern(), MANUFACTURER, "manufacturer".intern(), MODEL, "model".intern(), NAME, "name".intern(), PLATFORM, "platform".intern(), PRODUCE_TIME, "produce_time".intern(), STATUS, "status".intern(), UDID, "udid".intern()));
}
| |
package com.hector.luis.spaceapp2016.earthlivelh.Activities;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;
import com.hector.luis.spaceapp2016.earthlivelh.Generic.AppConstant;
import com.hector.luis.spaceapp2016.earthlivelh.Helpers.AppController;
import com.hector.luis.spaceapp2016.earthlivelh.Helpers.BitmapLruCache;
import com.hector.luis.spaceapp2016.earthlivelh.Helpers.CustomRequest;
import com.hector.luis.spaceapp2016.earthlivelh.Helpers.DialogDatePiker;
import com.hector.luis.spaceapp2016.earthlivelh.Helpers.Utils;
import com.hector.luis.spaceapp2016.earthlivelh.Models.ColorMapEntry;
import com.hector.luis.spaceapp2016.earthlivelh.Models.Layer;
import com.hector.luis.spaceapp2016.earthlivelh.Models.MetaDataColor;
import com.hector.luis.spaceapp2016.earthlivelh.Models.TileMatrix;
import com.hector.luis.spaceapp2016.earthlivelh.Models.TileMatrixSet;
import com.hector.luis.spaceapp2016.earthlivelh.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import uk.co.senab.photoview.PhotoViewAttacher;
public class MapActivity extends AppCompatActivity {
private Layer layer;
private Bitmap bmpLayout = null;
private MetaDataColor metaDataColors = new MetaDataColor();
private ArrayList<ColorMapEntry> colorMapEntries = new ArrayList<>();
private PhotoViewAttacher mAttacher;
private ImageView imgCoastLines;
private TextView txvResolution;
private EditText edtDate;
private TextView txvZoomLevel;
private LinearLayout lyBottom;
private LinearLayout lyRight;
private TextView txvUnits;
private TextView txvMin;
private TextView txvMax;
private ListView listViewMetaData;
private ColorMapEntitiesAdapter colorMapEntitiesAdapter;
private final int ICON_ARROW_UP = R.drawable.ic_keyboard_arrow_up_white_36dp;
private final int ICON_ARROW_DOWN = R.drawable.ic_keyboard_arrow_down_white_36dp;
private final int ICON_ARROW_LEFT = R.drawable.ic_keyboard_arrow_left_white_36dp;
private final int ICON_ARROW_RIGHT = R.drawable.ic_keyboard_arrow_right_white_36dp;
private Realm realm;
private final int TIME_OUT_REQUEST = 45000; //45 seg
private int mZoom = 0;
private int mTileRow = 2;
private int mTileCol = 1;
private String mTime = "";
private final int[] mTitleRowScale = {2, 3, 5, 10};
private final int[] mTitleColScale = {1, 2, 3, 5};
private ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
String layerTitle = getIntent().getStringExtra(AppConstant.KEY_INTENT_MAP);
String title = layerTitle.replace("_"," ");
title = title.replace("Day", "(Day)");
title = title.replace(" Night", " (Night)");
toolbar.setTitle(title);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_36dp);
setSupportActionBar(toolbar);
RealmConfiguration realmConfig = new RealmConfiguration.Builder(this).build();
// Get a Realm instance for this thread
realm = Realm.getInstance(realmConfig);
dialog = new ProgressDialog(this);
layer = realm.where(Layer.class)
.equalTo("title", layerTitle).findFirst();
imgCoastLines = (ImageView) findViewById(R.id.imgCoastLines);
txvResolution = (TextView) findViewById(R.id.txvResolution);
txvZoomLevel = (TextView) findViewById(R.id.txvZoomLevel);
edtDate = (EditText) findViewById(R.id.edtDate);
lyBottom = (LinearLayout) findViewById(R.id.lyBottom);
lyRight = (LinearLayout) findViewById(R.id.lyRight);
txvUnits = (TextView) findViewById(R.id.txvUnits);
txvMin = (TextView) findViewById(R.id.txvMin);
txvMax = (TextView) findViewById(R.id.txvMax);
listViewMetaData = (ListView) findViewById(R.id.listMetaData);
colorMapEntitiesAdapter = new ColorMapEntitiesAdapter(this, R.layout.item_meta_data_colors, colorMapEntries);
mAttacher = new PhotoViewAttacher(imgCoastLines, true);
mAttacher.setScaleType(ImageView.ScaleType.FIT_START);
mAttacher.setScaleLevels(1, 5, 10);
listViewMetaData.setAdapter(colorMapEntitiesAdapter);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
if (layer != null) {
String url = createUrlTemplete();
getDataRequest(); //obtiene la metadata del layout
getUrlImagenFromGIBS(url);
} else{
Toast.makeText(MapActivity.this, R.string.err_result_null, Toast.LENGTH_SHORT).show();
this.finish();
}
String resolution = getResources().getString(R.string.resolution_per_pixel);
String[] layoutResoluion = layer.getTileMatrixSet().split("_");
if (layoutResoluion.length > 0)
txvResolution.setText(resolution + layoutResoluion[1]);
mTime = layer.getDimencionDefault();
if (!TextUtils.isEmpty(mTime)) {
edtDate.setText(mTime);
}
}
public void loadImagenRequest(String url) {
startDialog(R.string.load_img);
ImageRequest request0 = new ImageRequest(url, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
bmpLayout = response;
imgCoastLines.setImageBitmap(response);
//mAttacher.setScale(2, true);
mAttacher.update();
closeDialog();
}
}, 0, 0, null, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
imgCoastLines.setImageResource(R.drawable.coast_lines_zoom_0);
closeDialog();
Toast.makeText(MapActivity.this, R.string.err_create_file, Toast.LENGTH_SHORT).show();
}
});
request0.setRetryPolicy(new DefaultRetryPolicy(TIME_OUT_REQUEST, 1, 1f));
AppController.getInstance().addToRequestQueue(request0);
}
private void handlePanels(LinearLayout prLayout) {
int lVisibility = View.GONE;
if (prLayout.getVisibility() == View.GONE) {
lVisibility = View.VISIBLE;
}
prLayout.setVisibility(lVisibility);
//setPaddingLyRight();
}
/**
* @deprecated
*/
private void setPaddingLyRight() {
if (lyBottom.getVisibility() == View.VISIBLE) {
int paddingPixel = 50;
float density = getResources().getDisplayMetrics().density;
int paddingDp = (int) (paddingPixel * density);
lyRight.setPadding(0, 0, 0, paddingDp);
} else {
lyRight.setPadding(0, 0, 0, 0);
}
}
public void onClickZoomOut(View v) {
if (mZoom > 0) {
mZoom--;
boolean inRange = setMatrixSet();
mTileRow = mTitleRowScale[mZoom];
mTileCol = mTitleColScale[mZoom];
// if (inRange) {
String url = createUrlTemplete();
getUrlImagenFromGIBS(url);
// } else {
// mZoom++;
// }
layer.getTileMatrixSet();
}
}
public void onClickZoomIn(View v) {
if (mZoom < 3) {
mZoom++;
boolean inRange = setMatrixSet();
mTileRow = mTitleRowScale[mZoom];
mTileCol = mTitleColScale[mZoom];
// if (inRange) {
String url = createUrlTemplete();
getUrlImagenFromGIBS(url);
// } else {
// mZoom--;
// }
updateZoomLevel();
}
}
private boolean setMatrixSet() {
boolean has = true;
String aaa = layer.getTileMatrixSet();
List<TileMatrixSet> matrixSet = realm.where(TileMatrixSet.class).findAll();
//.equalTo("identifier", layer.getTileMatrixSet()).findFirst();
if (matrixSet != null) {
TileMatrix tileMatrix = null;
// for (TileMatrix item : matrixSet.getTileMatrixes()) {
// if (item.getIdentifier() == mZoom) {
// tileMatrix = item;
// break;
// }
// }
if (tileMatrix != null) {
mTileRow = tileMatrix.getTileWidth();
mTileCol = tileMatrix.getTileHeight();
} else {
has = false;
}
}
return has;
}
public void getUrlImagenFromGIBS(String url) {
bmpLayout = null; //Limpiando la imagen de memoria
imgCoastLines.setImageDrawable(Utils.getDrawableById(MapActivity.this, R.drawable.coast_lines_zoom_0));
mAttacher.update();
updateZoomLevel();
startDialog();
CustomRequest request = new CustomRequest(this, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
ImageLoader.ImageCache imageCache = new BitmapLruCache();
ImageLoader imageLoader = new ImageLoader(Volley.newRequestQueue(MapActivity.this), imageCache);
try {
dialog.setMessage("Creando imagen...");
String lUrl = response.getString("data");
lUrl = AppConstant.URL_SERVER + lUrl.replace('\\','/');
//closeDialog();
loadImagenRequest(lUrl);
} catch (JSONException e) {
e.printStackTrace();
closeDialog();
Toast.makeText(MapActivity.this, "Ocurrio un error al cargar la imagen :(", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
closeDialog();
Toast.makeText(MapActivity.this, "Ocurrio un error al cargar la imagen :(", Toast.LENGTH_SHORT).show();
}
});
request.setRetryPolicy(new DefaultRetryPolicy(TIME_OUT_REQUEST, 1, 1f));
AppController.getInstance().addToRequestQueue(request);
}
private String createUrlTemplete(){
String lTemplete = layer.getResourceURLTemplete();
String lTileMatrixSet = layer.getTileMatrixSet();
String lTime = layer.getDimencionDefault();
String lTitle = layer.getTitle();
String lUrl = AppConstant.GET_IMAGE
+ "?Templete=" + lTemplete
+ "&TileMatrixSet=" + lTileMatrixSet
+ "&TileMatrix=" + + mZoom
+ "&TileMaxRow=" + mTileRow
+ "&TileMaxCol=" + mTileCol
+ "&TitleTemplete=" + lTitle;
if (!TextUtils.isEmpty(lTime)) {
lUrl += ("&Time=" + lTime);
}
return lUrl;
}
private void updateZoomLevel() {
txvZoomLevel.setText(String.valueOf(mZoom));
}
private void getDataRequest() {
String href = layer.getMetaDataHref();
if (TextUtils.isEmpty(href))
return;
startDialog(R.string.load_meta_data);
Map<String,String> params = new HashMap<>();
params.put("xmlFile", layer.getMetaDataHref());
CustomRequest request = new CustomRequest(this, Request.Method.POST, AppConstant.DECODE_META_DATA, params, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (!response.isNull("data")) {
try {
JSONObject jsoData = response.getJSONObject("data");
JSONArray jsaColorMap = jsoData.getJSONArray("ColorMap");
JSONObject jsoColorEntities = jsaColorMap.getJSONObject(0);
//
JSONObject jsoEntities = jsoColorEntities.getJSONObject("Entries");
JSONObject jsoLegends = jsoColorEntities.getJSONObject("Legend");
JSONObject jsoLeyendsArrt = jsoLegends.getJSONObject("@attributes");
JSONArray jsaLegendEntry = jsoLegends.getJSONArray("LegendEntry");
ArrayList<ColorMapEntry> lColorMapEntries = new ArrayList<>();
//continuous
if (!jsoColorEntities.isNull("@attributes")) {
JSONObject jsoAttributes = jsoColorEntities.getJSONObject("@attributes");
metaDataColors.setUnits(jsoAttributes.getString("units"));
metaDataColors.setType(jsoLeyendsArrt.getString("type"));
metaDataColors.setMinLabel(jsoLeyendsArrt.optString("minLabel"));
metaDataColors.setMaxLabel(jsoLeyendsArrt.optString("maxLabel"));
//String lUnit = MapActivity.this.getResources().getString(R.string.units);
String lUnit = jsoAttributes.getString("title");
txvUnits.setText(lUnit + " " + metaDataColors.getUnits());
txvMin.setText("Min: " + metaDataColors.getMaxLabel());
txvMax.setText("Max: " + metaDataColors.getMaxLabel());
}
for (int i = 0; i < jsaLegendEntry.length(); i++) {
JSONObject item = jsaLegendEntry.getJSONObject(i).getJSONObject("@attributes");
ColorMapEntry lColorMapEntry = new ColorMapEntry();
//boolean isTransparent = item.getBoolean("transparent");
lColorMapEntry.setRgb(item.getString("rgb"));
// lColorMapEntry.setTransparent(isTransparent);
// lColorMapEntry.setValue(String.valueOf(item.opt("value")));
// lColorMapEntry.setLabel(item.getString("label"));
MapActivity.this.colorMapEntries.add(lColorMapEntry);
}
metaDataColors.setColorMapEntries(lColorMapEntries);
colorMapEntitiesAdapter.notifyDataSetChanged();
// closeDialog();
} catch (JSONException e) {
e.printStackTrace();
closeDialog();
Toast.makeText(MapActivity.this, "Server error" , Toast.LENGTH_SHORT).show();
}
} else {
closeDialog();
Toast.makeText(MapActivity.this, "Meta data is null" , Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
closeDialog();
Toast.makeText(MapActivity.this, R.string.err_load_data, Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().addToRequestQueue(request, AppConstant.DATA);
}
private void startDialog() {
String msj = getResources().getString(R.string.loading);
showDialog(msj);
}
private void startDialog(int prString) {
String msj = MapActivity.this.getResources().getString(prString);
}
private void closeDialog() {
if (dialog.isShowing())
dialog.dismiss();
}
private void showDialog(String prMsj) {
dialog.setMessage(prMsj);
if (!dialog.isShowing()) {
dialog.setCancelable(false);
dialog.show();
}
}
public void onShowDatePiker(View v) {
new DialogDatePiker(this){
@Override
public void showDate(int year, int month, int day) {
super.showDate(year, month, day);
edtDate.setText(year + "-" + month + "-" + day);
edtDate.clearFocus();
}
}.createDialog().show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_map, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.action_shared:
if (bmpLayout != null) {
Uri lUri = Utils.storeImage(this, bmpLayout);
Utils.sharedImg(this, lUri);
}
return true;
case R.id.action_handle_menu_bottom:
if (item.isChecked()) {
item.setChecked(false);
} else {
item.setChecked(true);
}
handlePanels(lyBottom);
break;
case R.id.action_handle_menu_right:
if (item.isChecked()) {
item.setChecked(false);
} else {
item.setChecked(true);
}
handlePanels(lyRight);
break;
default:
}
return super.onOptionsItemSelected(item);
}
}
class ColorMapEntitiesAdapter extends ArrayAdapter<ColorMapEntry> {
private Context context;
private LayoutInflater inflater;
private int resource;
private ArrayList<ColorMapEntry> colorMapEntries;
public ColorMapEntitiesAdapter(Context context, int resource, ArrayList<ColorMapEntry> colorMapEntries) {
super(context, resource);
this.context = context;
this.resource = resource;
this.colorMapEntries = colorMapEntries;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return colorMapEntries.size();
}
@Override
public ColorMapEntry getItem(int position) {
return colorMapEntries.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null)
view = inflater.inflate(resource, null);
ImageView color = (ImageView) view.findViewById(R.id.color);
// TextView label = (TextView) view.findViewById(R.id.label);
color.setBackgroundColor(colorMapEntries.get(position).getRgb());
// label.setText(colorMapEntries.get(position).getLabel());
return view;
}
}
| |
package ml.puredark.hviewer.http;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.provider.DocumentFile;
import android.text.TextUtils;
import android.widget.ImageView;
import com.facebook.common.executors.CallerThreadExecutor;
import com.facebook.common.memory.PooledByteBuffer;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.BaseDataSubscriber;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeControllerBuilder;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ImageDecodeOptions;
import com.facebook.imagepipeline.common.ImageDecodeOptionsBuilder;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.google.gson.JsonObject;
import ml.puredark.hviewer.helpers.FileHelper;
import ml.puredark.hviewer.ui.customs.RetainingDataSourceSupplier;
import ml.puredark.hviewer.utils.DensityUtil;
import ml.puredark.hviewer.utils.MyThumbnailUtils;
import static ml.puredark.hviewer.HViewerApplication.getGson;
/**
* Created by PureDark on 2016/9/2.
*/
public class ImageLoader {
public static void loadImageFromUrl(Context context, ImageView imageView, String url) {
loadImageFromUrl(context, imageView, url, null, null, null);
}
public static void loadImageFromUrl(Context context, ImageView imageView, String url, String cookie) {
loadImageFromUrl(context, imageView, url, cookie, null, null);
}
public static void loadImageFromUrl(Context context, ImageView imageView, String url, String cookie, String referer) {
loadImageFromUrl(context, imageView, url, cookie, referer, null);
}
public static void loadImageFromUrl(Context context, ImageView imageView, String url, String cookie, String referer, boolean noCache) {
loadImageFromUrl(context, imageView, url, cookie, referer, noCache, null);
}
public static void loadImageFromUrl(Context context, ImageView imageView, String url, String cookie, String referer, ControllerListener controllerListener) {
loadImageFromUrl(context, imageView, url, cookie, referer, false, controllerListener);
}
public static void loadImageFromUrl(Context context, ImageView imageView, String url, String cookie, String referer, boolean noCache, ControllerListener controllerListener) {
if (TextUtils.isEmpty(url)) {
imageView.setImageURI(null);
return;
}
Uri uri = Uri.parse(url);
JsonObject header = new JsonObject();
header.addProperty("Cookie", cookie);
header.addProperty("Referer", referer);
if (url != null && url.startsWith("http")) {
if (HProxy.isEnabled() && HProxy.isAllowPicture()) {
HProxy proxy = new HProxy(url);
header.addProperty(proxy.getHeaderKey(), proxy.getHeaderValue());
}
MyOkHttpNetworkFetcher.headers.put(uri, getGson().toJson(header));
}
if (imageView instanceof SimpleDraweeView) {
SimpleDraweeView draweeView = ((SimpleDraweeView) imageView);
ImageRequestBuilder requestBuilder = ImageRequestBuilder.newBuilderWithSource(uri)
.setResizeOptions(new ResizeOptions(1080, 1920));
if (noCache)
requestBuilder.disableDiskCache();
ImageRequest request = requestBuilder.build();
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setCallerContext(context)
.setTapToRetryEnabled(true)
.setAutoPlayAnimations(true)
.setOldController(draweeView.getController())
.setControllerListener(controllerListener)
.setImageRequest(request)
.build();
draweeView.setController(controller);
}
}
public static RetainingDataSourceSupplier loadImageFromUrlRetainingImage(Context context, ImageView imageView, String url, String cookie, String referer, boolean noCache, ControllerListener controllerListener) {
if (TextUtils.isEmpty(url)) {
imageView.setImageURI(null);
return null;
}
Uri uri = Uri.parse(url);
JsonObject header = new JsonObject();
header.addProperty("Cookie", cookie);
header.addProperty("Referer", referer);
if (url != null && url.startsWith("http")) {
if (HProxy.isEnabled() && HProxy.isAllowPicture()) {
HProxy proxy = new HProxy(url);
header.addProperty(proxy.getHeaderKey(), proxy.getHeaderValue());
}
MyOkHttpNetworkFetcher.headers.put(uri, getGson().toJson(header));
}
if (imageView instanceof SimpleDraweeView) {
SimpleDraweeView draweeView = ((SimpleDraweeView) imageView);
RetainingDataSourceSupplier<CloseableReference<CloseableImage>> retainingSupplier = new RetainingDataSourceSupplier<>();
PipelineDraweeControllerBuilder draweeControllerBuilder = Fresco.newDraweeControllerBuilder();
draweeControllerBuilder.setDataSourceSupplier(retainingSupplier);
DraweeController controller = draweeControllerBuilder
.setCallerContext(context)
.setTapToRetryEnabled(true)
.setAutoPlayAnimations(true)
.setOldController(draweeView.getController())
.setControllerListener(controllerListener)
.build();
draweeView.setController(controller);
ImageRequestBuilder requestBuilder = ImageRequestBuilder.newBuilderWithSource(uri)
.setResizeOptions(new ResizeOptions(1080, 1920));
if (noCache)
requestBuilder.disableDiskCache();
ImageRequest request = requestBuilder.build();
retainingSupplier.setSupplier(Fresco.getImagePipeline().getDataSourceSupplier(request, null, ImageRequest.RequestLevel.FULL_FETCH));
return retainingSupplier;
}
return null;
}
public static void loadBitmapFromUrl(Context context, String url, String cookie, String referer, BaseBitmapDataSubscriber dataSubscriber) {
if (TextUtils.isEmpty(url))
return;
Uri uri = Uri.parse(url);
JsonObject header = new JsonObject();
header.addProperty("Cookie", cookie);
header.addProperty("Referer", referer);
if (HProxy.isEnabled() && HProxy.isAllowPicture()) {
HProxy proxy = new HProxy(url);
header.addProperty(proxy.getHeaderKey(), proxy.getHeaderValue());
}
MyOkHttpNetworkFetcher.headers.put(uri, getGson().toJson(header));
ImagePipeline imagePipeline = Fresco.getImagePipeline();
ImageRequestBuilder builder = ImageRequestBuilder.newBuilderWithSource(uri);
ImageRequest request = builder.build();
DataSource<CloseableReference<CloseableImage>>
dataSource = imagePipeline.fetchDecodedImage(request, context);
dataSource.subscribe(dataSubscriber, CallerThreadExecutor.getInstance());
}
public static void loadResourceFromUrl(Context context, String url, String cookie, String referer, BaseDataSubscriber dataSubscriber) {
if (TextUtils.isEmpty(url))
return;
Uri uri = Uri.parse(url);
loadResourceFromUrl(context, uri, cookie, referer, dataSubscriber);
}
public static void loadResourceFromUrl(Context context, Uri uri, String cookie, String referer, BaseDataSubscriber dataSubscriber) {
if (uri.getScheme().startsWith("http")) {
JsonObject header = new JsonObject();
header.addProperty("Cookie", cookie);
header.addProperty("Referer", referer);
if (HProxy.isEnabled() && HProxy.isAllowPicture()) {
HProxy proxy = new HProxy(uri.toString());
header.addProperty(proxy.getHeaderKey(), proxy.getHeaderValue());
}
MyOkHttpNetworkFetcher.headers.put(uri, getGson().toJson(header));
}
ImagePipeline imagePipeline = Fresco.getImagePipeline();
ImageRequestBuilder builder = ImageRequestBuilder.newBuilderWithSource(uri);
ImageRequest request = builder.build();
DataSource<CloseableReference<PooledByteBuffer>>
dataSource = imagePipeline.fetchEncodedImage(request, context);
dataSource.subscribe(dataSubscriber, CallerThreadExecutor.getInstance());
}
public static void loadThumbFromUrl(Context context, ImageView imageView, int resizeWidthDp, int resizeHeightDp, String url) {
loadThumbFromUrl(context, imageView, resizeWidthDp, resizeHeightDp, url, null, null, null);
}
public static void loadThumbFromUrl(Context context, ImageView imageView, int resizeWidthDp, int resizeHeightDp, String url, String cookie) {
loadThumbFromUrl(context, imageView, resizeWidthDp, resizeHeightDp, url, cookie, null, null);
}
public static void loadThumbFromUrl(Context context, ImageView imageView, int resizeWidthDp, int resizeHeightDp, String url, String cookie, String referer) {
loadThumbFromUrl(context, imageView, resizeWidthDp, resizeHeightDp, url, cookie, referer, null);
}
public static void loadThumbFromUrl(Context context, ImageView imageView, int resizeWidthDp, int resizeHeightDp, String url, String cookie, String referer, ControllerListener controllerListener) {
if (TextUtils.isEmpty(url)) {
imageView.setImageURI(null);
return;
}
Uri uri = Uri.parse(url);
JsonObject header = new JsonObject();
header.addProperty("Cookie", cookie);
header.addProperty("Referer", referer);
if (url != null && url.startsWith("http")) {
if (HProxy.isEnabled() && HProxy.isAllowPicture()) {
HProxy proxy = new HProxy(url);
header.addProperty(proxy.getHeaderKey(), proxy.getHeaderValue());
MyOkHttpNetworkFetcher.headers.put(uri, getGson().toJson(header));
}
MyOkHttpNetworkFetcher.headers.put(uri, getGson().toJson(header));
}
if (imageView instanceof SimpleDraweeView) {
ImageDecodeOptions imageDecodeOptions = new ImageDecodeOptionsBuilder()
.setForceStaticImage(true)
.setDecodePreviewFrame(true)
.build();
ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
.setResizeOptions(new ResizeOptions(DensityUtil.dp2px(context, resizeWidthDp), DensityUtil.dp2px(context, resizeHeightDp)))
.setImageDecodeOptions(imageDecodeOptions)
.setLocalThumbnailPreviewsEnabled(true)
.build();
DraweeController controller = Fresco.newDraweeControllerBuilder()
.setCallerContext(context)
.setTapToRetryEnabled(true)
.setAutoPlayAnimations(false)
.setOldController(((SimpleDraweeView) imageView).getController())
.setControllerListener(controllerListener)
.setImageRequest(request)
.build();
((SimpleDraweeView) imageView).setController(controller);
}
}
public static void loadThumbnailForVideo(Context context, ImageView imageView, int resizeWidthDp, int resizeHeightDp, String filePath) {
if (TextUtils.isEmpty(filePath)) {
imageView.setImageURI(null);
return;
}
new Thread(()->{
DocumentFile thumbnailFile = null;
try {
final String decodedPath = Uri.decode(filePath);
int lastSlash = decodedPath.lastIndexOf("/");
int last2ndSlash = decodedPath.substring(0, lastSlash).lastIndexOf("/");
final String rootPath = filePath.substring(0, filePath.lastIndexOf("/"));
String dirName = decodedPath.substring(last2ndSlash + 1, lastSlash);
final String fileName = decodedPath.substring(lastSlash + 1);
final String thumbnailName = decodedPath.substring(lastSlash + 1, decodedPath.lastIndexOf(".")) + ".jpg";
DocumentFile videoFile = FileHelper.getDocumentFile(fileName, rootPath, dirName);
thumbnailFile = FileHelper.getDocumentFile(thumbnailName, rootPath, dirName);
if ((thumbnailFile == null || !thumbnailFile.exists()) && videoFile != null) {
Bitmap bitmap = MyThumbnailUtils.createVideoThumbnail(context, videoFile.getUri(), MediaStore.Images.Thumbnails.MINI_KIND);
thumbnailFile = FileHelper.createFileIfNotExist(thumbnailName, rootPath, dirName);
if (thumbnailFile != null) {
FileHelper.saveBitmapToFile(bitmap, thumbnailFile);
final String tempPath = thumbnailFile.getUri().toString();
new Handler(context.getMainLooper()).post(()->
loadThumbFromUrl(context, imageView, resizeWidthDp, resizeHeightDp, tempPath));
}
} else if (thumbnailFile != null) {
final String tempPath = thumbnailFile.getUri().toString();
new Handler(context.getMainLooper()).post(()->
loadThumbFromUrl(context, imageView, resizeWidthDp, resizeHeightDp, tempPath));
}
} catch (Exception e) {
e.printStackTrace();
if(thumbnailFile!=null)
thumbnailFile.delete();
}
}).start();
}
}
| |
/*
* Copyright (c) 2007 Adobe Systems Incorporated
*
* 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 com.adobe.epubcheck.xml;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.xml.transform.TransformerFactory;
import org.idpf.epubcheck.util.saxon.ColumnNumberFunction;
import org.idpf.epubcheck.util.saxon.LineNumberFunction;
import org.idpf.epubcheck.util.saxon.SystemIdFunction;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import com.adobe.epubcheck.util.ResourceUtil;
import com.thaiopensource.resolver.Identifier;
import com.thaiopensource.resolver.Input;
import com.thaiopensource.resolver.Resolver;
import com.thaiopensource.resolver.ResolverException;
import com.thaiopensource.util.PropertyMapBuilder;
import com.thaiopensource.validate.Schema;
import com.thaiopensource.validate.SchemaReader;
import com.thaiopensource.validate.ValidateProperty;
import com.thaiopensource.validate.auto.AutoSchemaReader;
import com.thaiopensource.validate.auto.SchemaReaderFactorySchemaReceiverFactory;
import com.thaiopensource.validate.rng.CompactSchemaReader;
import com.thaiopensource.validate.schematron.NewSaxonSchemaReaderFactory;
import net.sf.saxon.Configuration;
import net.sf.saxon.TransformerFactoryImpl;
import net.sf.saxon.sxpath.IndependentContext;
import net.sf.saxon.sxpath.XPathStaticContext;
public class XMLValidator
{
Schema schema;
/**
* Basic Resolver from Jing modified to add support for resolving zip and
* jar relative locations.
*
* @author george@oxygenxml.com
*/
static public class BasicResolver implements Resolver
{
static private final BasicResolver theInstance = new BasicResolver();
BasicResolver()
{
}
public static BasicResolver getInstance()
{
return theInstance;
}
public void resolve(Identifier id, Input input) throws
IOException,
ResolverException
{
if (!input.isResolved())
{
input.setUri(resolveUri(id));
}
}
public void open(Input input) throws
IOException,
ResolverException
{
if (!input.isUriDefinitive())
{
return;
}
URI uri;
try
{
uri = new URI(input.getUri());
}
catch (URISyntaxException e)
{
throw new ResolverException(e);
}
if (!uri.isAbsolute())
{
throw new ResolverException("cannot open relative URI: " + uri);
}
URL url = new URL(uri.toASCIIString());
// XXX should set the encoding properly
// XXX if this is HTTP and we've been redirected, should do
// input.setURI with the new URI
input.setByteStream(url.openStream());
}
public static String resolveUri(Identifier id) throws
ResolverException
{
try
{
String uriRef = id.getUriReference();
URI uri = new URI(uriRef);
if (!uri.isAbsolute())
{
String base = id.getBase();
if (base != null)
{
// OXYGEN PATCH START
// Use class URL in order to resolve protocols like zip
// and jar.
URI baseURI = new URI(base);
if ("zip".equals(baseURI.getScheme())
|| "jar".equals(baseURI.getScheme()))
{
uriRef = new URL(new URL(base), uriRef)
.toExternalForm();
// OXYGEN PATCH END
}
else
{
uriRef = baseURI.resolve(uri).toString();
}
}
}
return uriRef;
}
catch (URISyntaxException e)
{
throw new ResolverException(e);
}
catch (MalformedURLException e)
{
throw new ResolverException(e);
}
}
}
/**
* Extends Jing's Saxon 9 schema reader factory by registering
* extension functions.
*/
static public class ExtendedSaxonSchemaReaderFactory extends NewSaxonSchemaReaderFactory
{
public void initTransformerFactory(TransformerFactory factory)
{
super.initTransformerFactory(factory);
if (factory instanceof TransformerFactoryImpl)
{
Configuration configuration = ((TransformerFactoryImpl) factory).getConfiguration();
XPathStaticContext xpathContext = new IndependentContext(configuration);
if (!xpathContext.getFunctionLibrary().isAvailable(LineNumberFunction.QNAME, -1))
{
configuration.registerExtensionFunction(new LineNumberFunction());
}
if (!xpathContext.getFunctionLibrary().isAvailable(ColumnNumberFunction.QNAME, -1))
{
configuration.registerExtensionFunction(new ColumnNumberFunction());
}
if (!xpathContext.getFunctionLibrary().isAvailable(SystemIdFunction.QNAME, -1))
{
configuration.registerExtensionFunction(new SystemIdFunction());
}
}
}
}
// handles errors in schemas
private class ErrorHandlerImpl implements ErrorHandler
{
public void error(SAXParseException exception) throws
SAXException
{
exception.printStackTrace();
}
public void fatalError(SAXParseException exception) throws
SAXException
{
exception.printStackTrace();
}
public void warning(SAXParseException exception) throws
SAXException
{
exception.printStackTrace();
}
}
public XMLValidator(String schemaName)
{
try
{
String resourcePath = ResourceUtil.getResourcePath(schemaName);
URL systemIdURL = ResourceUtil.getResourceURL(resourcePath);
if (systemIdURL == null)
{
throw new RuntimeException("Could not find resource "
+ resourcePath);
}
InputSource schemaSource = new InputSource(systemIdURL.toString());
PropertyMapBuilder mapBuilder = new PropertyMapBuilder();
mapBuilder.put(ValidateProperty.RESOLVER,
BasicResolver.getInstance());
mapBuilder.put(ValidateProperty.ERROR_HANDLER,
new ErrorHandlerImpl());
SchemaReader schemaReader;
if (schemaName.endsWith(".rnc"))
{
schemaReader = CompactSchemaReader.getInstance();
} else if (schemaName.endsWith(".sch")) {
schemaReader = new AutoSchemaReader(
new SchemaReaderFactorySchemaReceiverFactory(
new ExtendedSaxonSchemaReaderFactory()));
}
else
{
schemaReader = new AutoSchemaReader();
}
schema = schemaReader.createSchema(schemaSource,
mapBuilder.toPropertyMap());
}
catch (RuntimeException e)
{
throw e;
}
catch (Exception e)
{
e.printStackTrace();
throw new Error("Internal error: " + e + " " + schemaName);
}
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 by luxe - https://github.com/de-luxe - BURST-LUXE-RED2-G6JW-H4HG5
*
* 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 burstcoin.observer.service;
import burstcoin.observer.ObserverProperties;
import burstcoin.observer.bean.AssetBean;
import burstcoin.observer.bean.AssetCandleStickBean;
import burstcoin.observer.event.AssetUpdateEvent;
import burstcoin.observer.service.model.State;
import burstcoin.observer.service.model.asset.Asset;
import burstcoin.observer.service.model.asset.Assets;
import burstcoin.observer.service.model.asset.Order;
import burstcoin.observer.service.model.asset.OrderType;
import burstcoin.observer.service.model.asset.Orders;
import burstcoin.observer.service.model.asset.Trade;
import burstcoin.observer.service.model.asset.Trades;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.util.InputStreamResponseListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
@Component
public class AssetService
{
private static Log LOG = LogFactory.getLog(AssetService.class);
@Autowired
private ObjectMapper objectMapper;
@Autowired
private HttpClient httpClient;
@Autowired
private ApplicationEventPublisher publisher;
private Timer timer = new Timer();
@PostConstruct
private void postConstruct()
{
LOG.info("Started repeating 'check assets' task.");
startCheckAssetsTask();
}
private void startCheckAssetsTask()
{
timer.schedule(new TimerTask()
{
@Override
public void run()
{
try
{
LOG.info("START import asset data from " + ObserverProperties.getWalletUrl());
Map<String, Asset> assetLookup = createAssetLookup();
Map<OrderType, Map<Asset, List<Order>>> orderLookup = createOrderLookup(assetLookup);
Map<Asset, List<Trade>> tradeLookup = getTradeLookup(assetLookup);
State state = getState();
LOG.info("FINISH import asset data!");
List<AssetBean> assetBeans = new ArrayList<>();
List<AssetCandleStickBean> assetCandleStickBeans = new ArrayList<>();
for(Asset asset : assetLookup.values())
{
List<List> candleStickData = new ArrayList<List>();
long volume7Days = 0L;
long volume30Days = 0L;
String lastPrice = "";
List<Trade> trades = tradeLookup.get(asset);
if(trades != null && !trades.isEmpty())
{
Iterator<Trade> iterator = trades.iterator();
boolean withinLast30Days = true;
while(withinLast30Days && iterator.hasNext())
{
Trade trade = iterator.next();
if(StringUtils.isEmpty(lastPrice))
{
lastPrice = convertPrice(trade.getPriceNQT(), trade.getDecimals());
}
Integer bidOrderBlock = Integer.valueOf(trade.getBidOrderHeight());
Integer askOrderBlock = Integer.valueOf(trade.getAskOrderHeight());
int block = bidOrderBlock >= askOrderBlock ? bidOrderBlock : askOrderBlock;
withinLast30Days = state.getNumberOfBlocks() - 360 * 30 < block;
if(withinLast30Days)
{
long volume = Long.valueOf(trade.getPriceNQT()) * Long.valueOf(trade.getQuantityQNT());
volume30Days += volume;
if(state.getNumberOfBlocks() - 360 * 7 < block)
{
volume7Days += volume;
}
}
}
Long currentBlockHeight = Long.valueOf(state.getNumberOfBlocks());
for(int i = 1; i <= 60 /*days*/; i++)
{
List<Trade> tradesOfDay = new ArrayList<Trade>();
for(Trade trade : trades)
{
if(trade.getHeight() > currentBlockHeight - (360 * (i + 1)) && trade.getHeight() < currentBlockHeight - (360 * i))
{
tradesOfDay.add(trade);
}
}
Double min = null;
Double max = null;
Double first = null;
Double last = null;
for(Trade trade : tradesOfDay)
{
double price = Double.valueOf(convertPrice(trade.getPriceNQT(), trade.getDecimals()));
if(first == null)
{
first = price;
}
if(min == null || price < min)
{
min = price;
}
if(max == null || price > max)
{
max = price;
}
if(tradesOfDay.indexOf(trade) == tradesOfDay.size() - 1)
{
last = price;
}
}
if(min != null && max != null && first != null && last != null)
{
List x = Arrays.asList("" + i, min, first, last, max);
candleStickData.add(x);
}
else
{
candleStickData.add(Arrays.asList("" + i, null, null, null, null));
}
}
}
Collections.reverse(candleStickData);
List<Order> sellOrders = orderLookup.get(OrderType.ASK).get(asset) != null ? orderLookup.get(OrderType.ASK).get(asset) : new ArrayList<>();
List<Order> buyOrders = orderLookup.get(OrderType.BID).get(asset) != null ? orderLookup.get(OrderType.BID).get(asset) : new ArrayList<>();
if(!(buyOrders.isEmpty() && sellOrders.isEmpty() && asset.getNumberOfTrades() < 2))
{
assetBeans.add(new AssetBean(asset.getAsset(), asset.getName(), asset.getDescription(), asset.getAccountRS(), asset.getAccount(),
asset.getQuantityQNT(), asset.getDecimals(), asset.getNumberOfAccounts(), asset.getNumberOfTransfers(),
asset.getNumberOfTrades(), buyOrders.size(), sellOrders.size(),
formatAmountNQT(volume7Days, 8), formatAmountNQT(volume30Days, 8), lastPrice));
assetCandleStickBeans.add(new AssetCandleStickBean(asset.getAsset(), candleStickData));
}
}
Collections.sort(assetBeans, new Comparator<AssetBean>()
{
@Override
public int compare(AssetBean o1, AssetBean o2)
{
return Long.valueOf(o2.getVolume30Days()).compareTo(Long.valueOf(o1.getVolume30Days()));
}
});
Collections.sort(assetBeans, new Comparator<AssetBean>()
{
@Override
public int compare(AssetBean o1, AssetBean o2)
{
return Long.valueOf(o2.getVolume7Days()).compareTo(Long.valueOf(o1.getVolume7Days()));
}
});
// delete data of candleStick for all after index 24 todo remove as soon ui has show/hide charts per asset
List<String> assetOrder = new ArrayList<String>();
for(AssetBean assetBean : assetBeans)
{
assetOrder.add(assetBean.getAsset());
}
assetCandleStickBeans.sort(new Comparator<AssetCandleStickBean>()
{
@Override
public int compare(AssetCandleStickBean o1, AssetCandleStickBean o2)
{
return ((Integer)assetOrder.indexOf(o1.getAsset())).compareTo(assetOrder.indexOf(o2.getAsset()));
}
});
publisher.publishEvent(new AssetUpdateEvent(assetBeans, assetCandleStickBeans));
}
catch(Exception e)
{
LOG.error("Failed update assets!", e);
}
}
}, 200, ObserverProperties.getAssetRefreshInterval());
}
private String convertPrice(String priceString, int decimals)
{
BigInteger price = new BigInteger(priceString);
BigInteger amount = price.multiply(new BigInteger("" + (long) Math.pow(10, decimals)));
String negative = "";
String afterComma = "";
String fractionalPart = amount.mod(new BigInteger("100000000")).toString();
amount = amount.divide(new BigInteger("100000000"));
if(amount.compareTo(BigInteger.ZERO) < 0)
{
amount = amount.abs();
negative = "-";
}
if(!fractionalPart.equals("0"))
{
afterComma = ".";
for(int i = fractionalPart.length(); i < 8; i++)
{
afterComma += "0";
}
afterComma += fractionalPart.replace("0+$", "");
}
String result = negative + amount + afterComma;
while(result.lastIndexOf("0") == result.length() - 1 && result.contains("."))
{
result = result.substring(0, result.length() - 1);
}
if(result.lastIndexOf(".") == result.length() - 1)
{
result = result.substring(0, result.length() - 1);
}
return result;
}
// without decimal
private String formatAmountNQT(Long amount, int decimals)
{
String amountStr = String.valueOf(amount);
return amount != null && amountStr.length() >= decimals ? amountStr.substring(0, amountStr.length() - decimals) : "" + 0;
}
private Map<String, Asset> createAssetLookup()
{
Map<String, Asset> assetLookup = new HashMap<>();
try
{
ContentResponse response = httpClient.newRequest(ObserverProperties.getWalletUrl() + "/burst?requestType=getAllAssets")
.timeout(ObserverProperties.getConnectionTimeout(), TimeUnit.MILLISECONDS)
.send();
Assets assets = objectMapper.readValue(response.getContentAsString(), Assets.class);
LOG.info("received '" + assets.getAssets().size() + "' assets in '" + assets.getRequestProcessingTime() + "' ms");
assetLookup = new HashMap<>();
for(Asset asset : assets.getAssets())
{
assetLookup.put(asset.getAsset(), asset);
}
}
catch(Exception e)
{
LOG.warn("Error: Failed to 'getAllAssets': " + e.getMessage());
}
return assetLookup;
}
private Map<Asset, List<Trade>> getTradeLookup(Map<String, Asset> assetLookup)
{
Map<Asset, List<Trade>> tradeLookup = new HashMap<>();
boolean hasMoreTransactions = true;
int offset = 0;
int transactionsPerRequest = 1999;
while(hasMoreTransactions)
{
hasMoreTransactions = updateTradeLookup(tradeLookup, assetLookup, offset, transactionsPerRequest);
offset += transactionsPerRequest;
}
return tradeLookup;
}
private boolean updateTradeLookup(Map<Asset, List<Trade>> tradeLookup, Map<String, Asset> assetLookup, int offset, int transactionsPerRequest)
{
boolean hasMoreTrades = false;
try
{
InputStreamResponseListener listener = new InputStreamResponseListener();
Request request = httpClient.newRequest(ObserverProperties.getWalletUrl() + "/burst?requestType=getAllTrades")
.param("firstIndex", String.valueOf(offset))
.param("lastIndex", String.valueOf(offset + transactionsPerRequest))
.timeout(ObserverProperties.getConnectionTimeout(), TimeUnit.MILLISECONDS);
request.send(listener);
Response response = listener.get(ObserverProperties.getConnectionTimeout(), TimeUnit.MILLISECONDS);
// Look at the response
if(response.getStatus() == 200)
{
// Use try-with-resources to close input stream.
try (InputStream responseContent = listener.getInputStream())
{
Trades trades = objectMapper.readValue(responseContent, Trades.class);
if(!trades.getTrades().isEmpty() && trades.getTrades().size() >= transactionsPerRequest)
{
hasMoreTrades = true;
}
for(Trade trade : trades.getTrades())
{
Asset asset = assetLookup.get(trade.getAsset());
if(!tradeLookup.containsKey(asset))
{
tradeLookup.put(asset, new ArrayList<>());
}
tradeLookup.get(asset).add(trade);
}
LOG.info("received '" + trades.getTrades().size() + "' trades in '" + trades.getRequestProcessingTime() + "' ms");
}
catch(Exception e)
{
LOG.error("Failed to receive faucet account transactions.");
}
}
}
catch(Exception e)
{
LOG.warn("Error: Failed to 'getAllTrades': " + e.getMessage());
}
return hasMoreTrades;
}
private State getState()
{
State state = null;
try
{
InputStreamResponseListener listener = new InputStreamResponseListener();
Request request = httpClient.newRequest(ObserverProperties.getWalletUrl() + "/burst?requestType=getState&includeCounts=true")
.timeout(ObserverProperties.getConnectionTimeout(), TimeUnit.MILLISECONDS);
request.send(listener);
Response response = listener.get(ObserverProperties.getConnectionTimeout(), TimeUnit.MILLISECONDS);
if(response.getStatus() == 200)
{
try (InputStream responseContent = listener.getInputStream())
{
state = objectMapper.readValue(responseContent, State.class);
}
catch(Exception e)
{
LOG.error("Failed to receive faucet account transactions.");
}
}
}
catch(Exception e)
{
LOG.warn("Error: Failed to 'getAllTrades': " + e.getMessage());
}
return state;
}
private Map<OrderType, Map<Asset, List<Order>>> createOrderLookup(Map<String, Asset> assetLookup)
{
Map<OrderType, Map<Asset, List<Order>>> orderLookup = new HashMap<>();
try
{
ContentResponse response = httpClient.newRequest(ObserverProperties.getWalletUrl() + "/burst")
.param("requestType", "getAllOpenAskOrders")
.timeout(ObserverProperties.getConnectionTimeout(), TimeUnit.MILLISECONDS)
.send();
Orders askOrders = objectMapper.readValue(response.getContentAsString(), Orders.class);
LOG.info("received '" + askOrders.getOpenOrders().size() + "' askOrders in '" + askOrders.getRequestProcessingTime() + "' ms");
addOrders(OrderType.ASK, orderLookup, askOrders, assetLookup);
response = httpClient.newRequest(ObserverProperties.getWalletUrl() + "/burst")
.param("requestType", "getAllOpenBidOrders")
.timeout(ObserverProperties.getConnectionTimeout(), TimeUnit.MILLISECONDS)
.send();
Orders bidOrders = objectMapper.readValue(response.getContentAsString(), Orders.class);
LOG.info("received '" + bidOrders.getOpenOrders().size() + "' bidOrders in '" + bidOrders.getRequestProcessingTime() + "' ms");
addOrders(OrderType.BID, orderLookup, bidOrders, assetLookup);
}
catch(Exception e)
{
LOG.warn("Error: Failed to 'getAllOpenAskOrders' and 'getAllOpenBidOrders': " + e.getMessage());
}
return orderLookup;
}
private void addOrders(OrderType orderType, Map<OrderType, Map<Asset, List<Order>>> orderLookup, Orders orders, Map<String, Asset> assetLookup)
{
Map<Asset, List<Order>> askOrderLookup = new HashMap<>();
for(Order order : orders.getOpenOrders())
{
Asset asset = assetLookup.get(order.getAsset());
if(!askOrderLookup.containsKey(asset))
{
askOrderLookup.put(asset, new ArrayList<>());
}
askOrderLookup.get(asset).add(order);
}
orderLookup.put(orderType, askOrderLookup);
}
// 3 possibilities to blacklist a asset
// - issuer has blacklisted it (has to send assetId to provided account (from asset or issuer account))
// - blacklisted in properties
// - blacklisted via trusted community member accounts (from properties)
private List<String> getBlacklistedAssets()
{
// todo get messages from blacklist account
// todo filter valid messages
// todo filter allowed messages by moderator / issuer
// todo re-add whitelisted
// todo return remaining assetIds
return null;
}
}
| |
/*
* Copyright 2006-2021 Prowide
*
* 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.prowidesoftware.swift.model.field;
import com.prowidesoftware.swift.model.Tag;
import com.prowidesoftware.Generated;
import com.prowidesoftware.deprecation.ProwideDeprecated;
import com.prowidesoftware.deprecation.TargetYear;
import java.io.Serializable;
import java.util.Locale;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.apache.commons.lang3.StringUtils;
import com.prowidesoftware.swift.model.field.SwiftParseUtils;
import com.prowidesoftware.swift.model.field.Field;
import com.prowidesoftware.swift.model.*;
import com.prowidesoftware.swift.utils.SwiftFormatUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* SWIFT MT Field 18C.
* <p>
* Model and parser for field 18C of a SWIFT MT message.
*
* <p>Subfields (components) Data types
* <ol>
* <li><code>Long</code></li>
* </ol>
*
* <p>Structure definition
* <ul>
* <li>validation pattern: <code>3n</code></li>
* <li>parser pattern: <code>S</code></li>
* <li>components pattern: <code>N</code></li>
* </ul>
*
* <p>
* This class complies with standard release <strong>SRU2021</strong>
*/
@SuppressWarnings("unused")
@Generated
public class Field18C extends Field implements Serializable {
/**
* Constant identifying the SRU to which this class belongs to.
*/
public static final int SRU = 2021;
private static final long serialVersionUID = 1L;
/**
* Constant with the field name 18C.
*/
public static final String NAME = "18C";
/**
* Same as NAME, intended to be clear when using static imports.
*/
public static final String F_18C = "18C";
/**
* @deprecated use {@link #parserPattern()} method instead.
*/
@Deprecated
@ProwideDeprecated(phase2 = TargetYear.SRU2022)
public static final String PARSER_PATTERN = "S";
/**
* @deprecated use {@link #typesPattern()} method instead.
*/
@Deprecated
@ProwideDeprecated(phase2 = TargetYear.SRU2022)
public static final String COMPONENTS_PATTERN = "N";
/**
* @deprecated use {@link #typesPattern()} method instead.
*/
@Deprecated
@ProwideDeprecated(phase2 = TargetYear.SRU2022)
public static final String TYPES_PATTERN = "N";
/**
* Component number for the Number subfield.
*/
public static final Integer NUMBER = 1;
/**
* Default constructor. Creates a new field setting all components to null.
*/
public Field18C() {
super(1);
}
/**
* Creates a new field and initializes its components with content from the parameter value.
* @param value complete field value including separators and CRLF
*/
public Field18C(final String value) {
super(value);
}
/**
* Creates a new field and initializes its components with content from the parameter tag.
* The value is parsed with {@link #parse(String)}
* @throws IllegalArgumentException if the parameter tag is null or its tagname does not match the field name
* @since 7.8
*/
public Field18C(final Tag tag) {
this();
if (tag == null) {
throw new IllegalArgumentException("tag cannot be null.");
}
if (!StringUtils.equals(tag.getName(), "18C")) {
throw new IllegalArgumentException("cannot create field 18C from tag "+tag.getName()+", tagname must match the name of the field.");
}
parse(tag.getValue());
}
/**
* Copy constructor.
* Initializes the components list with a deep copy of the source components list.
* @param source a field instance to copy
* @since 7.7
*/
public static Field18C newInstance(Field18C source) {
Field18C cp = new Field18C();
cp.setComponents(new ArrayList<>(source.getComponents()));
return cp;
}
/**
* Create a Tag with this field name and the given value.
* Shorthand for <code>new Tag(NAME, value)</code>
* @see #NAME
* @since 7.5
*/
public static Tag tag(final String value) {
return new Tag(NAME, value);
}
/**
* Create a Tag with this field name and an empty string as value.
* Shorthand for <code>new Tag(NAME, "")</code>
* @see #NAME
* @since 7.5
*/
public static Tag emptyTag() {
return new Tag(NAME, "");
}
/**
* Parses the parameter value into the internal components structure.
*
* <p>Used to update all components from a full new value, as an alternative
* to setting individual components. Previous component values are overwritten.
*
* @param value complete field value including separators and CRLF
* @since 7.8
*/
@Override
public void parse(final String value) {
init(1);
setComponent1(value);
}
/**
* Serializes the fields' components into the single string value (SWIFT format)
*/
@Override
public String getValue() {
final StringBuilder result = new StringBuilder();
append(result, 1);
return result.toString();
}
/**
* Returns a localized suitable for showing to humans string of a field component.<br>
*
* @param component number of the component to display
* @param locale optional locale to format date and amounts, if null, the default locale is used
* @return formatted component value or null if component number is invalid or not present
* @throws IllegalArgumentException if component number is invalid for the field
* @since 7.8
*/
@Override
public String getValueDisplay(int component, Locale locale) {
if (component < 1 || component > 1) {
throw new IllegalArgumentException("invalid component number " + component + " for field 18C");
}
if (component == 1) {
//default format (as is)
return getComponent(1);
}
return null;
}
/**
* @deprecated use {@link #typesPattern()} instead.
*/
@Override
@Deprecated
@ProwideDeprecated(phase2 = TargetYear.SRU2022)
public String componentsPattern() {
return "N";
}
/**
* Returns the field component types pattern.
*
* This method returns a letter representing the type for each component in the Field. It supersedes
* the Components Pattern because it distinguishes between N (Number) and I (BigDecimal).
* @since 9.2.7
*/
@Override
public String typesPattern() {
return "N";
}
/**
* Returns the field parser pattern.
*/
@Override
public String parserPattern() {
return "S";
}
/**
* Returns the field validator pattern
*/
@Override
public String validatorPattern() {
return "3n";
}
/**
* Given a component number it returns true if the component is optional,
* regardless of the field being mandatory in a particular message.<br>
* Being the field's value conformed by a composition of one or several
* internal component values, the field may be present in a message with
* a proper value but with some of its internal components not set.
*
* @param component component number, first component of a field is referenced as 1
* @return true if the component is optional for this field, false otherwise
*/
@Override
public boolean isOptional(int component) {
return false;
}
/**
* Returns true if the field is a GENERIC FIELD as specified by the standard.
* @return true if the field is generic, false otherwise
*/
@Override
public boolean isGeneric() {
return false;
}
/**
* Returns the defined amount of components.<br>
* This is not the amount of components present in the field instance, but the total amount of components
* that this field accepts as defined.
* @since 7.7
*/
@Override
public int componentsSize() {
return 1;
}
/**
* Returns english label for components.
* <br>
* The index in the list is in sync with specific field component structure.
* @see #getComponentLabel(int)
* @since 7.8.4
*/
@Override
public List<String> getComponentLabels() {
List<String> result = new ArrayList<>();
result.add("Number");
return result;
}
/**
* Returns a mapping between component numbers and their label in camel case format.
* @since 7.10.3
*/
@Override
protected Map<Integer, String> getComponentMap() {
Map<Integer, String> result = new HashMap<>();
result.put(1, "number");
return result;
}
/**
* Gets the component 1 (Number).
* @return the component 1
*/
public String getComponent1() {
return getComponent(1);
}
/**
* Get the component 1 as Long
*
* @return the component 1 converted to Long or null if cannot be converted
* @since 9.2.7
*/
public java.lang.Long getComponent1AsLong() {
return SwiftFormatUtils.getLong(getComponent(1));
}
/**
* Get the component 1 as Number (BigDecimal)
*
* The value is returned as BigDecimal to keep compatibility with previous API. You should
* use <code>getComponent1AsLong()</code> to get the proper value.
*
* @return the component 1 converted to Number (BigDecimal) or null if cannot be converted
* @see #getComponent1AsLong()
*/
@Deprecated
@ProwideDeprecated(phase2 = TargetYear.SRU2022)
public java.lang.Number getComponent1AsNumber() {
Long l = getComponent1AsLong();
return l != null ? new BigDecimal(l) : null;
}
/**
* Gets the Number (component 1).
* @return the Number from component 1
*/
public String getNumber() {
return getComponent1();
}
/**
* Get the Number (component 1) as Long
* @return the Number from component 1 converted to Long or null if cannot be converted
* @since 9.2.7
*/
public java.lang.Long getNumberAsLong() {
return getComponent1AsLong();
}
/**
* Get the Number (component 1) as as Number (BigDecimal)
*
* The value is returned as BigDecimal to keep compatibility with previous API. You should
* use <code>getComponent1AsLong()</code> to get the proper value.
*
* @return the component 1 converted to Number (BigDecimal) or null if cannot be converted
* @see #getNumberAsLong()
*/
@Deprecated
@ProwideDeprecated(phase2 = TargetYear.SRU2022)
public java.lang.Number getNumberAsNumber() {
return getComponent1AsNumber();
}
/**
* Set the component 1 (Number).
*
* @param component1 the Number to set
* @return the field object to enable build pattern
*/
public Field18C setComponent1(String component1) {
setComponent(1, component1);
return this;
}
/**
* Set the component1 from a Long object.
* <br>
* <em>If the component being set is a fixed length number, the argument will not be
* padded.</em> It is recommended for these cases to use the setComponent1(String)
* method.
*
* @see #setComponent1(String)
* @since 9.2.7
*
* @param component1 the Long with the Number content to set
* @return the field object to enable build pattern
*/
public Field18C setComponent1(java.lang.Long component1) {
setComponent(1, SwiftFormatUtils.getLong(component1));
return this;
}
/**
* Alternative method setter for field's Number (component 1) as as Number
*
* This method supports java constant value boxing for simpler coding styles (ex: 10 becomes an Integer)
*
* @param component1 the Number with the Number content to set
* @return the field object to enable build pattern
* @see #setNumber(java.lang.Long)
*/
public Field18C setComponent1(java.lang.Number component1) {
// NOTE: remember instanceof implicitly checks for non-null
if (component1 instanceof Long) {
setComponent(1, SwiftFormatUtils.getLong((Long) component1));
} else if (component1 instanceof BigInteger || component1 instanceof Integer) {
setComponent(1, SwiftFormatUtils.getLong(component1.longValue()));
} else if (component1 != null) {
// it's another non-null Number (Float, Double, BigDecimal, etc...)
setComponent(1, SwiftFormatUtils.getLong(component1.longValue()));
} else {
// explicitly set component as null
setComponent(1, null);
}
return this;
}
/**
* Set the Number (component 1).
*
* @param component1 the Number to set
* @return the field object to enable build pattern
*/
public Field18C setNumber(String component1) {
return setComponent1(component1);
}
/**
* Set the Number (component 1) from a Long object.
*
* @see #setComponent1(java.lang.Long)
*
* @param component1 Long with the Number content to set
* @return the field object to enable build pattern
* @since 9.2.7
*/
public Field18C setNumber(java.lang.Long component1) {
return setComponent1(component1);
}
/**
* Alternative method setter for field's Number (component 1) as as Number
*
* This method supports java constant value boxing for simpler coding styles (ex: 10 becomes an Integer)
*
* @param component1 the Number with the Number content to set
* @return the field object to enable build pattern
* @see #setNumber(java.lang.Long)
*/
public Field18C setNumber(java.lang.Number component1) {
return setComponent1(component1);
}
/**
* Returns the field's name composed by the field number and the letter option (if any).
* @return the static value of Field18C.NAME
*/
@Override
public String getName() {
return NAME;
}
/**
* Gets the first occurrence form the tag list or null if not found.
* @return null if not found o block is null or empty
* @param block may be null or empty
*/
public static Field18C get(final SwiftTagListBlock block) {
if (block == null || block.isEmpty()) {
return null;
}
final Tag t = block.getTagByName(NAME);
if (t == null) {
return null;
}
return new Field18C(t);
}
/**
* Gets the first instance of Field18C in the given message.
* @param msg may be empty or null
* @return null if not found or msg is empty or null
* @see #get(SwiftTagListBlock)
*/
public static Field18C get(final SwiftMessage msg) {
if (msg == null || msg.getBlock4() == null || msg.getBlock4().isEmpty()) {
return null;
}
return get(msg.getBlock4());
}
/**
* Gets a list of all occurrences of the field Field18C in the given message
* an empty list is returned if none found.
* @param msg may be empty or null in which case an empty list is returned
* @see #getAll(SwiftTagListBlock)
*/
public static List<Field18C> getAll(final SwiftMessage msg) {
if (msg == null || msg.getBlock4() == null || msg.getBlock4().isEmpty()) {
return java.util.Collections.emptyList();
}
return getAll(msg.getBlock4());
}
/**
* Gets a list of all occurrences of the field Field18C from the given block
* an empty list is returned if none found.
*
* @param block may be empty or null in which case an empty list is returned
*/
public static List<Field18C> getAll(final SwiftTagListBlock block) {
final List<Field18C> result = new ArrayList<>();
if (block == null || block.isEmpty()) {
return result;
}
final Tag[] arr = block.getTagsByName(NAME);
if (arr != null && arr.length > 0) {
for (final Tag f : arr) {
result.add(new Field18C(f));
}
}
return result;
}
/**
* This method deserializes the JSON data into a Field18C object.
* @param json JSON structure including tuples with label and value for all field components
* @return a new field instance with the JSON data parsed into field components or an empty field id the JSON is invalid
* @since 7.10.3
* @see Field#fromJson(String)
*/
public static Field18C fromJson(final String json) {
final Field18C field = new Field18C();
final JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
// **** COMPONENT 1 - Number
if (jsonObject.get("number") != null) {
field.setComponent1(jsonObject.get("number").getAsString());
}
return field;
}
}
| |
/**
* Copyright (C) 2015 Jeeva Kandasamy (jkandasa@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mycontroller.standalone.db.tables;
import org.mycontroller.standalone.db.AlarmUtils;
import org.mycontroller.standalone.mysensors.MyMessages.MESSAGE_TYPE_SET_REQ;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
/**
* @author Jeeva Kandasamy (jkandasa)
* @since 0.0.1
*/
@DatabaseTable(tableName = "alarm")
@JsonIgnoreProperties(ignoreUnknown = true)
public class Alarm {
public static final String SENSOR_REF_ID = "sensor_ref_id";
public static final String ENABLED = "enabled";
public static final String TRIGGERED = "triggered";
public static final String VARIABLE_TYPE = "variable_type";
public Alarm() {
this.triggered = false;
}
@DatabaseField(generatedId = true)
private Integer id;
@DatabaseField(canBeNull = false, columnName = ENABLED)
private Boolean enabled;
@DatabaseField(canBeNull = false, uniqueCombo = true)
private String name;
@DatabaseField(canBeNull = false, foreign = true, uniqueCombo = true, columnName = SENSOR_REF_ID,
foreignAutoRefresh = true, maxForeignAutoRefreshLevel = 2)
private Sensor sensor;
@DatabaseField(canBeNull = false, columnName = VARIABLE_TYPE)
private Integer variableType;
@DatabaseField(canBeNull = true)
private Long timestamp;
@DatabaseField(canBeNull = true)
private Long lastTrigger;
@DatabaseField(canBeNull = true, defaultValue = "true")
private Boolean ignoreDuplicate;
@DatabaseField(canBeNull = true)
private Long lastNotification;
@DatabaseField(canBeNull = false, columnName = TRIGGERED)
private Boolean triggered;
@DatabaseField(canBeNull = false)
private Integer occurrenceCount = 0;
@DatabaseField(canBeNull = false)
private Integer evaluationCount = 0;
@DatabaseField(canBeNull = false)
private Integer type;
@DatabaseField(canBeNull = false)
private Integer trigger;
@DatabaseField(canBeNull = false)
private String thresholdValue;
@DatabaseField(canBeNull = false)
private Integer dampeningType;
@DatabaseField(canBeNull = true)
private String dampeningVar1;
@DatabaseField(canBeNull = true)
private String dampeningVar2;
@DatabaseField(canBeNull = true)
private String variable1;
@DatabaseField(canBeNull = true)
private String variable2;
@DatabaseField(canBeNull = true)
private String variable3;
@DatabaseField(canBeNull = true)
private String variable4;
@DatabaseField(canBeNull = true)
private String variable5;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public Sensor getSensor() {
return sensor;
}
public Long getTimestamp() {
return timestamp;
}
public Integer getType() {
return type;
}
public String getTypeString() {
if (type != null) {
return AlarmUtils.TYPE.get(type).value();
}
return null;
}
//To ignore json serialization
public void setTypeString(String typeString) {
}
public String getVariable1() {
return variable1;
}
public String getVariable2() {
return variable2;
}
public String getVariable3() {
return variable3;
}
public String getVariable4() {
return variable4;
}
public String getVariable5() {
return variable5;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setSensor(Sensor sensor) {
this.sensor = sensor;
}
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
public void setType(Integer type) {
this.type = type;
}
public void setVariable1(String variable1) {
this.variable1 = variable1;
}
public void setVariable2(String variable2) {
this.variable2 = variable2;
}
public void setVariable3(String variable3) {
this.variable3 = variable3;
}
public void setVariable4(String variable4) {
this.variable4 = variable4;
}
public void setVariable5(String variable5) {
this.variable5 = variable5;
}
public Integer getTrigger() {
return trigger;
}
public String getTriggerString() {
if (trigger != null) {
return AlarmUtils.TRIGGER.get(trigger).value();
}
return null;
}
public void setTrigger(Integer trigger) {
this.trigger = trigger;
}
//Ignore, just for JSON
public void setTriggerString(String triggerString) {
}
public String getThresholdValue() {
return thresholdValue;
}
public void setThresholdValue(String thresholdValue) {
this.thresholdValue = thresholdValue;
}
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public String getNotificationString() {
return AlarmUtils.getNotificationString(this);
}
//To ignore json serialization
public void setNotificationString(String notificationString) {
}
public Long getLastTrigger() {
return lastTrigger;
}
public void setLastTrigger(Long lastTrigger) {
this.lastTrigger = lastTrigger;
}
public Long getLastNotification() {
return lastNotification;
}
public void setLastNotification(Long lastNotification) {
this.lastNotification = lastNotification;
}
public Boolean getTriggered() {
return triggered;
}
public void setTriggered(Boolean triggered) {
this.triggered = triggered;
}
public Integer getDampeningType() {
return dampeningType;
}
public String getDampeningVar1() {
return dampeningVar1;
}
public String getDampeningVar2() {
return dampeningVar2;
}
public void setDampeningType(Integer dampeningType) {
this.dampeningType = dampeningType;
}
public void setDampeningVar1(String dampeningVar1) {
this.dampeningVar1 = dampeningVar1;
}
public void setDampeningVar2(String dampeningVar2) {
this.dampeningVar2 = dampeningVar2;
}
//To ignore json serialization error
public void setDampeningString(String dampeningString) {
}
public String getDampeningString() {
return AlarmUtils.getDampeningString(this);
}
public Integer getOccurrenceCount() {
return occurrenceCount;
}
public Integer getEvaluationCount() {
return evaluationCount;
}
public void setOccurrenceCount(Integer occurrenceCount) {
this.occurrenceCount = occurrenceCount;
}
public void setEvaluationCount(Integer evaluationCount) {
this.evaluationCount = evaluationCount;
}
public Boolean getIgnoreDuplicate() {
return ignoreDuplicate;
}
public void setIgnoreDuplicate(Boolean ignoreDuplicate) {
this.ignoreDuplicate = ignoreDuplicate;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Id:").append(this.id);
builder.append(", Enabled:").append(this.enabled);
builder.append(", Name:").append(this.name);
builder.append(", Sensor:[").append(this.sensor).append("]");
builder.append(", Variable Type:").append(this.getVariableTypeString());
builder.append(", timestamp:").append(this.timestamp);
builder.append(", ignoreDuplicate:").append(this.ignoreDuplicate);
builder.append(", lastTrigger:").append(this.lastTrigger);
builder.append(", lastNotification:").append(this.lastNotification);
builder.append(", triggered:").append(this.triggered);
builder.append(", occurrenceCount:").append(this.occurrenceCount);
builder.append(", evaluationCount:").append(this.evaluationCount);
builder.append(", type:").append(this.type);
builder.append(", trigger:").append(this.trigger);
builder.append(", thresholdValue:").append(this.thresholdValue);
builder.append(", dampeningType:").append(this.dampeningType);
builder.append(", dampeningVar1:").append(this.dampeningVar1);
builder.append(", dampeningVar2:").append(this.dampeningVar2);
builder.append(", variable1:").append(this.variable1);
builder.append(", variable2:").append(this.variable2);
builder.append(", variable3:").append(this.variable3);
builder.append(", variable4:").append(this.variable4);
builder.append(", variable5:").append(this.variable5);
return builder.toString();
}
public Integer getVariableType() {
return variableType;
}
public String getVariableTypeString() {
if (variableType != null) {
return MESSAGE_TYPE_SET_REQ.get(variableType).toString();
}
return "";
}
public void setVariableType(Integer variableType) {
this.variableType = variableType;
}
}
| |
/*
* Copyright 2005 Sascha Weinreuter
*
* 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.intellij.lang.xpath.completion;
import com.intellij.codeInsight.completion.CompletionInitializationContext;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlElement;
import com.intellij.util.PlatformIcons;
import com.intellij.util.containers.ContainerUtil;
import org.intellij.lang.xpath.XPathFile;
import org.intellij.lang.xpath.XPathTokenTypes;
import org.intellij.lang.xpath.context.ContextProvider;
import org.intellij.lang.xpath.context.NamespaceContext;
import org.intellij.lang.xpath.context.VariableContext;
import org.intellij.lang.xpath.context.XPathVersion;
import org.intellij.lang.xpath.context.functions.Function;
import org.intellij.lang.xpath.psi.*;
import javax.xml.namespace.QName;
import java.util.*;
public class CompletionLists {
public static final String INTELLIJ_IDEA_RULEZ = CompletionInitializationContext.DUMMY_IDENTIFIER_TRIMMED;
private CompletionLists() {
}
public static final Set<String> NODE_TYPE_FUNCS = new HashSet<String>(Arrays.asList(
"text", "node", "comment", "processing-instruction"
));
public static final Set<String> NODE_TYPE_FUNCS_V2 = new HashSet<String>(Arrays.asList(
"text", "node", "comment", "processing-instruction", "attribute", "element", "schema-element", "schema-attribute", "document-node"
));
public static final Set<String> OPERATORS = new HashSet<String>(Arrays.asList(
"mul", "div", "and", "or"
));
public static final Set<String> AXIS_NAMES = new HashSet<String>(Arrays.asList(
"ancestor",
"ancestor-or-self",
"attribute",
"child",
"descendant",
"descendant-or-self",
"following",
"following-sibling",
"namespace",
"parent",
"preceding",
"preceding-sibling",
"self"
));
private static final com.intellij.util.Function<String,Lookup> FUNCTION_MAPPING = new com.intellij.util.Function<String, Lookup>() {
@Override
public Lookup fun(String s) {
if (s.equals("processing-instruction")) {
return new FunctionLookup(s, s + "(pi-target?)");
} else {
return new FunctionLookup(s, s + "()");
}
}
};
public static Collection<Lookup> getFunctionCompletions(XPathElement element) {
final XPathFile xpathFile = (XPathFile)element.getContainingFile();
final ContextProvider contextProvider = ContextProvider.getContextProvider(xpathFile);
final NamespaceContext nsContext = contextProvider.getNamespaceContext();
String uri;
PrefixedName qn = null;
if (element instanceof QNameElement) {
qn = ((QNameElement)element).getQName();
if (qn != null) {
QName qName = contextProvider.getQName(qn, element);
if (qn.getPrefix() != null) {
if (qName != null) {
uri = qName.getNamespaceURI();
} else {
return Collections.emptySet();
}
} else {
uri = null;
}
} else {
uri = null;
}
} else {
uri = null;
}
final Map<Pair<QName, Integer>, ? extends Function> functions = contextProvider.getFunctionContext().getFunctions();
final List<Lookup> lookups = new ArrayList<Lookup>(functions.size());
for (Map.Entry<Pair<QName, Integer>, ? extends Function> entry : functions.entrySet()) {
final Function functionDecl = entry.getValue();
final QName f = entry.getKey().first;
final String p;
if (nsContext != null) {
String namespaceURI = f.getNamespaceURI();
if (uri != null && !namespaceURI.equals(uri)) {
continue;
}
final String prefixForURI = nsContext.getPrefixForURI(namespaceURI, PsiTreeUtil.getContextOfType(element, XmlElement.class, true));
if (prefixForURI == null && namespaceURI.length() > 0) {
continue;
}
p = qn == null || qn.getPrefix() == null ? makePrefix(prefixForURI) : "";
} else {
p = "";
}
lookups.add(FunctionLookup.newFunctionLookup(p + f.getLocalPart(), functionDecl));
}
return lookups;
}
public static Collection<Lookup> getVariableCompletions(XPathElement reference) {
final ContextProvider contextProvider = ContextProvider.getContextProvider(reference);
final VariableContext resolver = contextProvider.getVariableContext();
if (resolver != null) {
final Object[] variablesInScope = resolver.getVariablesInScope(reference);
final List<Lookup> lookups = new ArrayList<Lookup>(variablesInScope.length);
for (final Object o : variablesInScope) {
if (o instanceof PsiNamedElement) {
final String type;
if (o instanceof XPathVariable) {
final XPathType t = ((XPathVariable)o).getType();
if (t != XPathType.UNKNOWN) {
type = t.getName();
} else {
type = "";
}
} else {
type = "";
}
final String name = ((PsiNamedElement)o).getName();
lookups.add(new VariableLookup("$" + name, type, ((PsiNamedElement)o).getIcon(0), (PsiElement)o));
} else {
lookups.add(new VariableLookup("$" + String.valueOf(o), PlatformIcons.VARIABLE_ICON));
}
}
return lookups;
} else {
return Collections.emptySet();
}
}
public static Collection<Lookup> getNodeTestCompletions(final XPathNodeTest element) {
if (!element.isNameTest()) {
return Collections.emptyList();
}
final PrefixedName prefixedName = element.getQName();
assert prefixedName != null;
final String canonicalText = prefixedName.toString();
final String suffix = canonicalText.substring(canonicalText.indexOf(INTELLIJ_IDEA_RULEZ));
final XPathAxisSpecifier axisSpecifier = element.getStep().getAxisSpecifier();
final ContextProvider contextProvider = ContextProvider.getContextProvider(element);
final XmlElement context = contextProvider.getContextElement();
final boolean insidePrefix = suffix.contains(INTELLIJ_IDEA_RULEZ + ":");
final Set<Lookup> list = new HashSet<Lookup>();
addNameCompletions(contextProvider, element, list);
final String namespacePrefix = prefixedName.getPrefix();
if (namespacePrefix == null || insidePrefix) {
addNamespaceCompletions(contextProvider.getNamespaceContext(), list, context);
}
final XPathNodeTest.PrincipalType principalType = addContextNames(element, contextProvider, prefixedName, list);
if (namespacePrefix == null && !insidePrefix) {
if (axisSpecifier == null || axisSpecifier.isDefaultAxis()) {
list.addAll(getAxisCompletions());
// wow, this code sux. find a better implementation
PsiElement sibling = element.getParent().getPrevSibling();
while (sibling instanceof PsiWhiteSpace) {
sibling = sibling.getPrevSibling();
}
boolean check = sibling != null;
if (!check) {
XPathLocationPath lp = null;
do {
lp = PsiTreeUtil.getParentOfType(lp == null ? element : lp, XPathLocationPath.class, true);
} while (lp != null && lp.getPrevSibling() == null);
check = lp == null || (sibling = lp.getPrevSibling()) != null;
}
if (check) {
if (sibling instanceof XPathToken && XPathTokenTypes.PATH_OPS.contains(((XPathToken)sibling).getTokenType())) {
// xx/yy<caret> : prevSibl = /
} else {
list.addAll(getFunctionCompletions(element));
list.addAll(getVariableCompletions(element));
}
}
}
if (principalType == XPathNodeTest.PrincipalType.ELEMENT && prefixedName.getPrefix() == null) {
list.addAll(getNodeTypeCompletions(element));
}
}
return list;
}
private static XPathNodeTest.PrincipalType addContextNames(XPathNodeTest element, ContextProvider contextProvider, PrefixedName prefixedName, Set<Lookup> list) {
final NamespaceContext namespaceContext = contextProvider.getNamespaceContext();
final XmlElement context = contextProvider.getContextElement();
final XPathNodeTest.PrincipalType principalType = element.getPrincipalType();
if (principalType == XPathNodeTest.PrincipalType.ELEMENT) {
final Set<QName> elementNames = contextProvider.getElements(false);
if (elementNames != null) {
for (QName pair : elementNames) {
if ("*".equals(pair.getLocalPart())) continue;
if (namespaceMatches(prefixedName, pair.getNamespaceURI(), namespaceContext, context, true)) {
if (prefixedName.getPrefix() == null && namespaceContext != null) {
final String p = namespaceContext.getPrefixForURI(pair.getNamespaceURI(), context);
list.add(new NodeLookup(makePrefix(p) + pair.getLocalPart(), XPathNodeTest.PrincipalType.ELEMENT));
} else {
list.add(new NodeLookup(pair.getLocalPart(), XPathNodeTest.PrincipalType.ELEMENT));
}
}
}
}
} else if (principalType == XPathNodeTest.PrincipalType.ATTRIBUTE) {
final Set<QName> attributeNames = contextProvider.getAttributes(false);
if (attributeNames != null) {
for (QName pair : attributeNames) {
if ("*".equals(pair.getLocalPart())) continue;
if (namespaceMatches(prefixedName, pair.getNamespaceURI(), namespaceContext, context, false)) {
if (prefixedName.getPrefix() == null && namespaceContext != null) {
final String p = namespaceContext.getPrefixForURI(pair.getNamespaceURI(), context);
list.add(new NodeLookup(makePrefix(p) + pair.getLocalPart(), XPathNodeTest.PrincipalType.ATTRIBUTE));
} else {
list.add(new NodeLookup(pair.getLocalPart(), XPathNodeTest.PrincipalType.ATTRIBUTE));
}
}
}
}
}
return principalType;
}
private static String makePrefix(String p) {
return (p != null && p.length() > 0 ? p + ":" : "");
}
private static void addNamespaceCompletions(NamespaceContext namespaceContext, Set<Lookup> list, XmlElement context) {
if (namespaceContext != null) {
final Collection<String> knownPrefixes = namespaceContext.getKnownPrefixes(context);
for (String prefix : knownPrefixes) {
if (prefix != null && prefix.length() > 0) {
list.add(new NamespaceLookup(prefix));
}
}
}
}
private static void addNameCompletions(ContextProvider contextProvider, final XPathNodeTest element, final Set<Lookup> list) {
final PrefixedName prefixedName = element.getQName();
final XPathNodeTest.PrincipalType principalType = element.getPrincipalType();
final Set<PsiFile> files = new HashSet<PsiFile>();
final XPathFile file = (XPathFile)element.getContainingFile();
files.add(file);
ContainerUtil.addAll(files, contextProvider.getRelatedFiles(file));
for (PsiFile xpathFile : files) {
xpathFile.accept(new PsiRecursiveElementVisitor() {
public void visitElement(PsiElement e) {
if (e instanceof XPathNodeTest) {
final XPathNodeTest nodeTest = (XPathNodeTest)e;
final XPathNodeTest.PrincipalType _principalType = nodeTest.getPrincipalType();
if (_principalType == principalType) {
final PrefixedName _prefixedName = nodeTest.getQName();
if (_prefixedName != null && prefixedName != null) {
final String localName = _prefixedName.getLocalName();
if (!"*".equals(localName) && !localName.contains(INTELLIJ_IDEA_RULEZ)) {
if (Comparing.equal(_prefixedName.getPrefix(), prefixedName.getPrefix())) {
list.add(new NodeLookup(localName, _principalType));
} else if (prefixedName.getPrefix() == null) {
list.add(new NodeLookup(_prefixedName.toString(), _principalType));
}
}
}
}
}
super.visitElement(e);
}
});
}
}
private static boolean namespaceMatches(PrefixedName prefixedName,
String uri,
NamespaceContext namespaceContext,
XmlElement context,
boolean allowDefault) {
if (namespaceContext == null) return true;
final String namespaceURI;
if (prefixedName.getPrefix() != null) {
if (uri == null || uri.length() == 0) return false;
namespaceURI = namespaceContext.getNamespaceURI(prefixedName.getPrefix(), context);
} else {
if (!allowDefault) return (uri == null || uri.length() == 0);
if ((namespaceURI = namespaceContext.getDefaultNamespace(context)) == null) {
return (uri == null || uri.length() == 0);
}
}
return uri.equals(namespaceURI);
}
public static Collection<Lookup> getNodeTypeCompletions(XPathElement context) {
final Set<String> funcs = context.getXPathVersion() == XPathVersion.V1 ?
NODE_TYPE_FUNCS : NODE_TYPE_FUNCS_V2;
return ContainerUtil.map(funcs, FUNCTION_MAPPING);
}
public static Collection<Lookup> getAxisCompletions() {
final ArrayList<Lookup> lookups = new ArrayList<Lookup>(AXIS_NAMES.size());
for (String s : AXIS_NAMES) {
lookups.add(new AxisLookup(s));
}
return lookups;
}
@SuppressWarnings({"RawUseOfParameterizedType"})
public static Class[] getAllInterfaces(Class<?> clazz) {
Set<Class> set = new HashSet<Class>();
do {
ContainerUtil.addAll(set, clazz.getInterfaces());
clazz = clazz.getSuperclass();
} while (clazz != null);
return set.toArray(new Class[set.size()]);
}
}
| |
package org.trimatek.deep.lexer;
// Generated from Java.g4 by ANTLR 4.4
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.tree.ParseTreeListener;
/**
* This interface defines a complete listener for a parse tree produced by
* {@link JavaParser}.
*/
public interface JavaListener extends ParseTreeListener {
/**
* Enter a parse tree produced by {@link JavaParser#memberDeclaration}.
* @param ctx the parse tree
*/
void enterMemberDeclaration(@NotNull JavaParser.MemberDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#memberDeclaration}.
* @param ctx the parse tree
*/
void exitMemberDeclaration(@NotNull JavaParser.MemberDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#defaultValue}.
* @param ctx the parse tree
*/
void enterDefaultValue(@NotNull JavaParser.DefaultValueContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#defaultValue}.
* @param ctx the parse tree
*/
void exitDefaultValue(@NotNull JavaParser.DefaultValueContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#annotationTypeElementDeclaration}.
* @param ctx the parse tree
*/
void enterAnnotationTypeElementDeclaration(@NotNull JavaParser.AnnotationTypeElementDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#annotationTypeElementDeclaration}.
* @param ctx the parse tree
*/
void exitAnnotationTypeElementDeclaration(@NotNull JavaParser.AnnotationTypeElementDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#type}.
* @param ctx the parse tree
*/
void enterType(@NotNull JavaParser.TypeContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#type}.
* @param ctx the parse tree
*/
void exitType(@NotNull JavaParser.TypeContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#annotationTypeBody}.
* @param ctx the parse tree
*/
void enterAnnotationTypeBody(@NotNull JavaParser.AnnotationTypeBodyContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#annotationTypeBody}.
* @param ctx the parse tree
*/
void exitAnnotationTypeBody(@NotNull JavaParser.AnnotationTypeBodyContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#genericInterfaceMethodDeclaration}.
* @param ctx the parse tree
*/
void enterGenericInterfaceMethodDeclaration(@NotNull JavaParser.GenericInterfaceMethodDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#genericInterfaceMethodDeclaration}.
* @param ctx the parse tree
*/
void exitGenericInterfaceMethodDeclaration(@NotNull JavaParser.GenericInterfaceMethodDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#classBodyDeclaration}.
* @param ctx the parse tree
*/
void enterClassBodyDeclaration(@NotNull JavaParser.ClassBodyDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#classBodyDeclaration}.
* @param ctx the parse tree
*/
void exitClassBodyDeclaration(@NotNull JavaParser.ClassBodyDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#block}.
* @param ctx the parse tree
*/
void enterBlock(@NotNull JavaParser.BlockContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#block}.
* @param ctx the parse tree
*/
void exitBlock(@NotNull JavaParser.BlockContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#enumBodyDeclarations}.
* @param ctx the parse tree
*/
void enterEnumBodyDeclarations(@NotNull JavaParser.EnumBodyDeclarationsContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#enumBodyDeclarations}.
* @param ctx the parse tree
*/
void exitEnumBodyDeclarations(@NotNull JavaParser.EnumBodyDeclarationsContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#forUpdate}.
* @param ctx the parse tree
*/
void enterForUpdate(@NotNull JavaParser.ForUpdateContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#forUpdate}.
* @param ctx the parse tree
*/
void exitForUpdate(@NotNull JavaParser.ForUpdateContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#enhancedForControl}.
* @param ctx the parse tree
*/
void enterEnhancedForControl(@NotNull JavaParser.EnhancedForControlContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#enhancedForControl}.
* @param ctx the parse tree
*/
void exitEnhancedForControl(@NotNull JavaParser.EnhancedForControlContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#annotationConstantRest}.
* @param ctx the parse tree
*/
void enterAnnotationConstantRest(@NotNull JavaParser.AnnotationConstantRestContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#annotationConstantRest}.
* @param ctx the parse tree
*/
void exitAnnotationConstantRest(@NotNull JavaParser.AnnotationConstantRestContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#explicitGenericInvocation}.
* @param ctx the parse tree
*/
void enterExplicitGenericInvocation(@NotNull JavaParser.ExplicitGenericInvocationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#explicitGenericInvocation}.
* @param ctx the parse tree
*/
void exitExplicitGenericInvocation(@NotNull JavaParser.ExplicitGenericInvocationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#nonWildcardTypeArgumentsOrDiamond}.
* @param ctx the parse tree
*/
void enterNonWildcardTypeArgumentsOrDiamond(@NotNull JavaParser.NonWildcardTypeArgumentsOrDiamondContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#nonWildcardTypeArgumentsOrDiamond}.
* @param ctx the parse tree
*/
void exitNonWildcardTypeArgumentsOrDiamond(@NotNull JavaParser.NonWildcardTypeArgumentsOrDiamondContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#expressionList}.
* @param ctx the parse tree
*/
void enterExpressionList(@NotNull JavaParser.ExpressionListContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#expressionList}.
* @param ctx the parse tree
*/
void exitExpressionList(@NotNull JavaParser.ExpressionListContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#annotationTypeElementRest}.
* @param ctx the parse tree
*/
void enterAnnotationTypeElementRest(@NotNull JavaParser.AnnotationTypeElementRestContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#annotationTypeElementRest}.
* @param ctx the parse tree
*/
void exitAnnotationTypeElementRest(@NotNull JavaParser.AnnotationTypeElementRestContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#classOrInterfaceType}.
* @param ctx the parse tree
*/
void enterClassOrInterfaceType(@NotNull JavaParser.ClassOrInterfaceTypeContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#classOrInterfaceType}.
* @param ctx the parse tree
*/
void exitClassOrInterfaceType(@NotNull JavaParser.ClassOrInterfaceTypeContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#typeBound}.
* @param ctx the parse tree
*/
void enterTypeBound(@NotNull JavaParser.TypeBoundContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#typeBound}.
* @param ctx the parse tree
*/
void exitTypeBound(@NotNull JavaParser.TypeBoundContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#variableDeclaratorId}.
* @param ctx the parse tree
*/
void enterVariableDeclaratorId(@NotNull JavaParser.VariableDeclaratorIdContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#variableDeclaratorId}.
* @param ctx the parse tree
*/
void exitVariableDeclaratorId(@NotNull JavaParser.VariableDeclaratorIdContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#primary}.
* @param ctx the parse tree
*/
void enterPrimary(@NotNull JavaParser.PrimaryContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#primary}.
* @param ctx the parse tree
*/
void exitPrimary(@NotNull JavaParser.PrimaryContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#classCreatorRest}.
* @param ctx the parse tree
*/
void enterClassCreatorRest(@NotNull JavaParser.ClassCreatorRestContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#classCreatorRest}.
* @param ctx the parse tree
*/
void exitClassCreatorRest(@NotNull JavaParser.ClassCreatorRestContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#interfaceBodyDeclaration}.
* @param ctx the parse tree
*/
void enterInterfaceBodyDeclaration(@NotNull JavaParser.InterfaceBodyDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#interfaceBodyDeclaration}.
* @param ctx the parse tree
*/
void exitInterfaceBodyDeclaration(@NotNull JavaParser.InterfaceBodyDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#typeArguments}.
* @param ctx the parse tree
*/
void enterTypeArguments(@NotNull JavaParser.TypeArgumentsContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#typeArguments}.
* @param ctx the parse tree
*/
void exitTypeArguments(@NotNull JavaParser.TypeArgumentsContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#annotationName}.
* @param ctx the parse tree
*/
void enterAnnotationName(@NotNull JavaParser.AnnotationNameContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#annotationName}.
* @param ctx the parse tree
*/
void exitAnnotationName(@NotNull JavaParser.AnnotationNameContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#finallyBlock}.
* @param ctx the parse tree
*/
void enterFinallyBlock(@NotNull JavaParser.FinallyBlockContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#finallyBlock}.
* @param ctx the parse tree
*/
void exitFinallyBlock(@NotNull JavaParser.FinallyBlockContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#typeParameters}.
* @param ctx the parse tree
*/
void enterTypeParameters(@NotNull JavaParser.TypeParametersContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#typeParameters}.
* @param ctx the parse tree
*/
void exitTypeParameters(@NotNull JavaParser.TypeParametersContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#lastFormalParameter}.
* @param ctx the parse tree
*/
void enterLastFormalParameter(@NotNull JavaParser.LastFormalParameterContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#lastFormalParameter}.
* @param ctx the parse tree
*/
void exitLastFormalParameter(@NotNull JavaParser.LastFormalParameterContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#constructorBody}.
* @param ctx the parse tree
*/
void enterConstructorBody(@NotNull JavaParser.ConstructorBodyContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#constructorBody}.
* @param ctx the parse tree
*/
void exitConstructorBody(@NotNull JavaParser.ConstructorBodyContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#literal}.
* @param ctx the parse tree
*/
void enterLiteral(@NotNull JavaParser.LiteralContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#literal}.
* @param ctx the parse tree
*/
void exitLiteral(@NotNull JavaParser.LiteralContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#annotationMethodOrConstantRest}.
* @param ctx the parse tree
*/
void enterAnnotationMethodOrConstantRest(@NotNull JavaParser.AnnotationMethodOrConstantRestContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#annotationMethodOrConstantRest}.
* @param ctx the parse tree
*/
void exitAnnotationMethodOrConstantRest(@NotNull JavaParser.AnnotationMethodOrConstantRestContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#catchClause}.
* @param ctx the parse tree
*/
void enterCatchClause(@NotNull JavaParser.CatchClauseContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#catchClause}.
* @param ctx the parse tree
*/
void exitCatchClause(@NotNull JavaParser.CatchClauseContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#variableDeclarator}.
* @param ctx the parse tree
*/
void enterVariableDeclarator(@NotNull JavaParser.VariableDeclaratorContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#variableDeclarator}.
* @param ctx the parse tree
*/
void exitVariableDeclarator(@NotNull JavaParser.VariableDeclaratorContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#typeList}.
* @param ctx the parse tree
*/
void enterTypeList(@NotNull JavaParser.TypeListContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#typeList}.
* @param ctx the parse tree
*/
void exitTypeList(@NotNull JavaParser.TypeListContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#enumConstants}.
* @param ctx the parse tree
*/
void enterEnumConstants(@NotNull JavaParser.EnumConstantsContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#enumConstants}.
* @param ctx the parse tree
*/
void exitEnumConstants(@NotNull JavaParser.EnumConstantsContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#classBody}.
* @param ctx the parse tree
*/
void enterClassBody(@NotNull JavaParser.ClassBodyContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#classBody}.
* @param ctx the parse tree
*/
void exitClassBody(@NotNull JavaParser.ClassBodyContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#createdName}.
* @param ctx the parse tree
*/
void enterCreatedName(@NotNull JavaParser.CreatedNameContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#createdName}.
* @param ctx the parse tree
*/
void exitCreatedName(@NotNull JavaParser.CreatedNameContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#enumDeclaration}.
* @param ctx the parse tree
*/
void enterEnumDeclaration(@NotNull JavaParser.EnumDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#enumDeclaration}.
* @param ctx the parse tree
*/
void exitEnumDeclaration(@NotNull JavaParser.EnumDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#formalParameter}.
* @param ctx the parse tree
*/
void enterFormalParameter(@NotNull JavaParser.FormalParameterContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#formalParameter}.
* @param ctx the parse tree
*/
void exitFormalParameter(@NotNull JavaParser.FormalParameterContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#parExpression}.
* @param ctx the parse tree
*/
void enterParExpression(@NotNull JavaParser.ParExpressionContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#parExpression}.
* @param ctx the parse tree
*/
void exitParExpression(@NotNull JavaParser.ParExpressionContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#annotation}.
* @param ctx the parse tree
*/
void enterAnnotation(@NotNull JavaParser.AnnotationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#annotation}.
* @param ctx the parse tree
*/
void exitAnnotation(@NotNull JavaParser.AnnotationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#variableInitializer}.
* @param ctx the parse tree
*/
void enterVariableInitializer(@NotNull JavaParser.VariableInitializerContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#variableInitializer}.
* @param ctx the parse tree
*/
void exitVariableInitializer(@NotNull JavaParser.VariableInitializerContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#elementValueArrayInitializer}.
* @param ctx the parse tree
*/
void enterElementValueArrayInitializer(@NotNull JavaParser.ElementValueArrayInitializerContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#elementValueArrayInitializer}.
* @param ctx the parse tree
*/
void exitElementValueArrayInitializer(@NotNull JavaParser.ElementValueArrayInitializerContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#creator}.
* @param ctx the parse tree
*/
void enterCreator(@NotNull JavaParser.CreatorContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#creator}.
* @param ctx the parse tree
*/
void exitCreator(@NotNull JavaParser.CreatorContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#arrayCreatorRest}.
* @param ctx the parse tree
*/
void enterArrayCreatorRest(@NotNull JavaParser.ArrayCreatorRestContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#arrayCreatorRest}.
* @param ctx the parse tree
*/
void exitArrayCreatorRest(@NotNull JavaParser.ArrayCreatorRestContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#expression}.
* @param ctx the parse tree
*/
void enterExpression(@NotNull JavaParser.ExpressionContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#expression}.
* @param ctx the parse tree
*/
void exitExpression(@NotNull JavaParser.ExpressionContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#constantExpression}.
* @param ctx the parse tree
*/
void enterConstantExpression(@NotNull JavaParser.ConstantExpressionContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#constantExpression}.
* @param ctx the parse tree
*/
void exitConstantExpression(@NotNull JavaParser.ConstantExpressionContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#qualifiedNameList}.
* @param ctx the parse tree
*/
void enterQualifiedNameList(@NotNull JavaParser.QualifiedNameListContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#qualifiedNameList}.
* @param ctx the parse tree
*/
void exitQualifiedNameList(@NotNull JavaParser.QualifiedNameListContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#constructorDeclaration}.
* @param ctx the parse tree
*/
void enterConstructorDeclaration(@NotNull JavaParser.ConstructorDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#constructorDeclaration}.
* @param ctx the parse tree
*/
void exitConstructorDeclaration(@NotNull JavaParser.ConstructorDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#forControl}.
* @param ctx the parse tree
*/
void enterForControl(@NotNull JavaParser.ForControlContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#forControl}.
* @param ctx the parse tree
*/
void exitForControl(@NotNull JavaParser.ForControlContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#superSuffix}.
* @param ctx the parse tree
*/
void enterSuperSuffix(@NotNull JavaParser.SuperSuffixContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#superSuffix}.
* @param ctx the parse tree
*/
void exitSuperSuffix(@NotNull JavaParser.SuperSuffixContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#variableDeclarators}.
* @param ctx the parse tree
*/
void enterVariableDeclarators(@NotNull JavaParser.VariableDeclaratorsContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#variableDeclarators}.
* @param ctx the parse tree
*/
void exitVariableDeclarators(@NotNull JavaParser.VariableDeclaratorsContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#catchType}.
* @param ctx the parse tree
*/
void enterCatchType(@NotNull JavaParser.CatchTypeContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#catchType}.
* @param ctx the parse tree
*/
void exitCatchType(@NotNull JavaParser.CatchTypeContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#classOrInterfaceModifier}.
* @param ctx the parse tree
*/
void enterClassOrInterfaceModifier(@NotNull JavaParser.ClassOrInterfaceModifierContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#classOrInterfaceModifier}.
* @param ctx the parse tree
*/
void exitClassOrInterfaceModifier(@NotNull JavaParser.ClassOrInterfaceModifierContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#enumConstantName}.
* @param ctx the parse tree
*/
void enterEnumConstantName(@NotNull JavaParser.EnumConstantNameContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#enumConstantName}.
* @param ctx the parse tree
*/
void exitEnumConstantName(@NotNull JavaParser.EnumConstantNameContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#modifier}.
* @param ctx the parse tree
*/
void enterModifier(@NotNull JavaParser.ModifierContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#modifier}.
* @param ctx the parse tree
*/
void exitModifier(@NotNull JavaParser.ModifierContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#innerCreator}.
* @param ctx the parse tree
*/
void enterInnerCreator(@NotNull JavaParser.InnerCreatorContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#innerCreator}.
* @param ctx the parse tree
*/
void exitInnerCreator(@NotNull JavaParser.InnerCreatorContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#explicitGenericInvocationSuffix}.
* @param ctx the parse tree
*/
void enterExplicitGenericInvocationSuffix(@NotNull JavaParser.ExplicitGenericInvocationSuffixContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#explicitGenericInvocationSuffix}.
* @param ctx the parse tree
*/
void exitExplicitGenericInvocationSuffix(@NotNull JavaParser.ExplicitGenericInvocationSuffixContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#variableModifier}.
* @param ctx the parse tree
*/
void enterVariableModifier(@NotNull JavaParser.VariableModifierContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#variableModifier}.
* @param ctx the parse tree
*/
void exitVariableModifier(@NotNull JavaParser.VariableModifierContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#elementValuePair}.
* @param ctx the parse tree
*/
void enterElementValuePair(@NotNull JavaParser.ElementValuePairContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#elementValuePair}.
* @param ctx the parse tree
*/
void exitElementValuePair(@NotNull JavaParser.ElementValuePairContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#arrayInitializer}.
* @param ctx the parse tree
*/
void enterArrayInitializer(@NotNull JavaParser.ArrayInitializerContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#arrayInitializer}.
* @param ctx the parse tree
*/
void exitArrayInitializer(@NotNull JavaParser.ArrayInitializerContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#elementValue}.
* @param ctx the parse tree
*/
void enterElementValue(@NotNull JavaParser.ElementValueContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#elementValue}.
* @param ctx the parse tree
*/
void exitElementValue(@NotNull JavaParser.ElementValueContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#constDeclaration}.
* @param ctx the parse tree
*/
void enterConstDeclaration(@NotNull JavaParser.ConstDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#constDeclaration}.
* @param ctx the parse tree
*/
void exitConstDeclaration(@NotNull JavaParser.ConstDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#resource}.
* @param ctx the parse tree
*/
void enterResource(@NotNull JavaParser.ResourceContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#resource}.
* @param ctx the parse tree
*/
void exitResource(@NotNull JavaParser.ResourceContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#qualifiedName}.
* @param ctx the parse tree
*/
void enterQualifiedName(@NotNull JavaParser.QualifiedNameContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#qualifiedName}.
* @param ctx the parse tree
*/
void exitQualifiedName(@NotNull JavaParser.QualifiedNameContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#resourceSpecification}.
* @param ctx the parse tree
*/
void enterResourceSpecification(@NotNull JavaParser.ResourceSpecificationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#resourceSpecification}.
* @param ctx the parse tree
*/
void exitResourceSpecification(@NotNull JavaParser.ResourceSpecificationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#formalParameterList}.
* @param ctx the parse tree
*/
void enterFormalParameterList(@NotNull JavaParser.FormalParameterListContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#formalParameterList}.
* @param ctx the parse tree
*/
void exitFormalParameterList(@NotNull JavaParser.FormalParameterListContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#annotationTypeDeclaration}.
* @param ctx the parse tree
*/
void enterAnnotationTypeDeclaration(@NotNull JavaParser.AnnotationTypeDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#annotationTypeDeclaration}.
* @param ctx the parse tree
*/
void exitAnnotationTypeDeclaration(@NotNull JavaParser.AnnotationTypeDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#compilationUnit}.
* @param ctx the parse tree
*/
void enterCompilationUnit(@NotNull JavaParser.CompilationUnitContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#compilationUnit}.
* @param ctx the parse tree
*/
void exitCompilationUnit(@NotNull JavaParser.CompilationUnitContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#annotationMethodRest}.
* @param ctx the parse tree
*/
void enterAnnotationMethodRest(@NotNull JavaParser.AnnotationMethodRestContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#annotationMethodRest}.
* @param ctx the parse tree
*/
void exitAnnotationMethodRest(@NotNull JavaParser.AnnotationMethodRestContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#switchBlockStatementGroup}.
* @param ctx the parse tree
*/
void enterSwitchBlockStatementGroup(@NotNull JavaParser.SwitchBlockStatementGroupContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#switchBlockStatementGroup}.
* @param ctx the parse tree
*/
void exitSwitchBlockStatementGroup(@NotNull JavaParser.SwitchBlockStatementGroupContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#typeParameter}.
* @param ctx the parse tree
*/
void enterTypeParameter(@NotNull JavaParser.TypeParameterContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#typeParameter}.
* @param ctx the parse tree
*/
void exitTypeParameter(@NotNull JavaParser.TypeParameterContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#interfaceBody}.
* @param ctx the parse tree
*/
void enterInterfaceBody(@NotNull JavaParser.InterfaceBodyContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#interfaceBody}.
* @param ctx the parse tree
*/
void exitInterfaceBody(@NotNull JavaParser.InterfaceBodyContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#methodDeclaration}.
* @param ctx the parse tree
*/
void enterMethodDeclaration(@NotNull JavaParser.MethodDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#methodDeclaration}.
* @param ctx the parse tree
*/
void exitMethodDeclaration(@NotNull JavaParser.MethodDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#methodBody}.
* @param ctx the parse tree
*/
void enterMethodBody(@NotNull JavaParser.MethodBodyContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#methodBody}.
* @param ctx the parse tree
*/
void exitMethodBody(@NotNull JavaParser.MethodBodyContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#typeArgument}.
* @param ctx the parse tree
*/
void enterTypeArgument(@NotNull JavaParser.TypeArgumentContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#typeArgument}.
* @param ctx the parse tree
*/
void exitTypeArgument(@NotNull JavaParser.TypeArgumentContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#typeDeclaration}.
* @param ctx the parse tree
*/
void enterTypeDeclaration(@NotNull JavaParser.TypeDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#typeDeclaration}.
* @param ctx the parse tree
*/
void exitTypeDeclaration(@NotNull JavaParser.TypeDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#genericConstructorDeclaration}.
* @param ctx the parse tree
*/
void enterGenericConstructorDeclaration(@NotNull JavaParser.GenericConstructorDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#genericConstructorDeclaration}.
* @param ctx the parse tree
*/
void exitGenericConstructorDeclaration(@NotNull JavaParser.GenericConstructorDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#classDeclaration}.
* @param ctx the parse tree
*/
void enterClassDeclaration(@NotNull JavaParser.ClassDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#classDeclaration}.
* @param ctx the parse tree
*/
void exitClassDeclaration(@NotNull JavaParser.ClassDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#enumConstant}.
* @param ctx the parse tree
*/
void enterEnumConstant(@NotNull JavaParser.EnumConstantContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#enumConstant}.
* @param ctx the parse tree
*/
void exitEnumConstant(@NotNull JavaParser.EnumConstantContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#statement}.
* @param ctx the parse tree
*/
void enterStatement(@NotNull JavaParser.StatementContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#statement}.
* @param ctx the parse tree
*/
void exitStatement(@NotNull JavaParser.StatementContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#importDeclaration}.
* @param ctx the parse tree
*/
void enterImportDeclaration(@NotNull JavaParser.ImportDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#importDeclaration}.
* @param ctx the parse tree
*/
void exitImportDeclaration(@NotNull JavaParser.ImportDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#primitiveType}.
* @param ctx the parse tree
*/
void enterPrimitiveType(@NotNull JavaParser.PrimitiveTypeContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#primitiveType}.
* @param ctx the parse tree
*/
void exitPrimitiveType(@NotNull JavaParser.PrimitiveTypeContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#interfaceDeclaration}.
* @param ctx the parse tree
*/
void enterInterfaceDeclaration(@NotNull JavaParser.InterfaceDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#interfaceDeclaration}.
* @param ctx the parse tree
*/
void exitInterfaceDeclaration(@NotNull JavaParser.InterfaceDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#localVariableDeclarationStatement}.
* @param ctx the parse tree
*/
void enterLocalVariableDeclarationStatement(@NotNull JavaParser.LocalVariableDeclarationStatementContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#localVariableDeclarationStatement}.
* @param ctx the parse tree
*/
void exitLocalVariableDeclarationStatement(@NotNull JavaParser.LocalVariableDeclarationStatementContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#blockStatement}.
* @param ctx the parse tree
*/
void enterBlockStatement(@NotNull JavaParser.BlockStatementContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#blockStatement}.
* @param ctx the parse tree
*/
void exitBlockStatement(@NotNull JavaParser.BlockStatementContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#fieldDeclaration}.
* @param ctx the parse tree
*/
void enterFieldDeclaration(@NotNull JavaParser.FieldDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#fieldDeclaration}.
* @param ctx the parse tree
*/
void exitFieldDeclaration(@NotNull JavaParser.FieldDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#constantDeclarator}.
* @param ctx the parse tree
*/
void enterConstantDeclarator(@NotNull JavaParser.ConstantDeclaratorContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#constantDeclarator}.
* @param ctx the parse tree
*/
void exitConstantDeclarator(@NotNull JavaParser.ConstantDeclaratorContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#resources}.
* @param ctx the parse tree
*/
void enterResources(@NotNull JavaParser.ResourcesContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#resources}.
* @param ctx the parse tree
*/
void exitResources(@NotNull JavaParser.ResourcesContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#statementExpression}.
* @param ctx the parse tree
*/
void enterStatementExpression(@NotNull JavaParser.StatementExpressionContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#statementExpression}.
* @param ctx the parse tree
*/
void exitStatementExpression(@NotNull JavaParser.StatementExpressionContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#interfaceMethodDeclaration}.
* @param ctx the parse tree
*/
void enterInterfaceMethodDeclaration(@NotNull JavaParser.InterfaceMethodDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#interfaceMethodDeclaration}.
* @param ctx the parse tree
*/
void exitInterfaceMethodDeclaration(@NotNull JavaParser.InterfaceMethodDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#packageDeclaration}.
* @param ctx the parse tree
*/
void enterPackageDeclaration(@NotNull JavaParser.PackageDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#packageDeclaration}.
* @param ctx the parse tree
*/
void exitPackageDeclaration(@NotNull JavaParser.PackageDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#elementValuePairs}.
* @param ctx the parse tree
*/
void enterElementValuePairs(@NotNull JavaParser.ElementValuePairsContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#elementValuePairs}.
* @param ctx the parse tree
*/
void exitElementValuePairs(@NotNull JavaParser.ElementValuePairsContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#localVariableDeclaration}.
* @param ctx the parse tree
*/
void enterLocalVariableDeclaration(@NotNull JavaParser.LocalVariableDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#localVariableDeclaration}.
* @param ctx the parse tree
*/
void exitLocalVariableDeclaration(@NotNull JavaParser.LocalVariableDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#nonWildcardTypeArguments}.
* @param ctx the parse tree
*/
void enterNonWildcardTypeArguments(@NotNull JavaParser.NonWildcardTypeArgumentsContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#nonWildcardTypeArguments}.
* @param ctx the parse tree
*/
void exitNonWildcardTypeArguments(@NotNull JavaParser.NonWildcardTypeArgumentsContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#interfaceMemberDeclaration}.
* @param ctx the parse tree
*/
void enterInterfaceMemberDeclaration(@NotNull JavaParser.InterfaceMemberDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#interfaceMemberDeclaration}.
* @param ctx the parse tree
*/
void exitInterfaceMemberDeclaration(@NotNull JavaParser.InterfaceMemberDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#switchLabel}.
* @param ctx the parse tree
*/
void enterSwitchLabel(@NotNull JavaParser.SwitchLabelContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#switchLabel}.
* @param ctx the parse tree
*/
void exitSwitchLabel(@NotNull JavaParser.SwitchLabelContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#forInit}.
* @param ctx the parse tree
*/
void enterForInit(@NotNull JavaParser.ForInitContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#forInit}.
* @param ctx the parse tree
*/
void exitForInit(@NotNull JavaParser.ForInitContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#formalParameters}.
* @param ctx the parse tree
*/
void enterFormalParameters(@NotNull JavaParser.FormalParametersContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#formalParameters}.
* @param ctx the parse tree
*/
void exitFormalParameters(@NotNull JavaParser.FormalParametersContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#arguments}.
* @param ctx the parse tree
*/
void enterArguments(@NotNull JavaParser.ArgumentsContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#arguments}.
* @param ctx the parse tree
*/
void exitArguments(@NotNull JavaParser.ArgumentsContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#genericMethodDeclaration}.
* @param ctx the parse tree
*/
void enterGenericMethodDeclaration(@NotNull JavaParser.GenericMethodDeclarationContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#genericMethodDeclaration}.
* @param ctx the parse tree
*/
void exitGenericMethodDeclaration(@NotNull JavaParser.GenericMethodDeclarationContext ctx);
/**
* Enter a parse tree produced by {@link JavaParser#typeArgumentsOrDiamond}.
* @param ctx the parse tree
*/
void enterTypeArgumentsOrDiamond(@NotNull JavaParser.TypeArgumentsOrDiamondContext ctx);
/**
* Exit a parse tree produced by {@link JavaParser#typeArgumentsOrDiamond}.
* @param ctx the parse tree
*/
void exitTypeArgumentsOrDiamond(@NotNull JavaParser.TypeArgumentsOrDiamondContext ctx);
}
| |
/**
* 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.examples.terasort;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Checksum;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableUtils;
import org.apache.hadoop.mapreduce.Cluster;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.PureJavaCrc32;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
* Generate the official GraySort input data set.
* The user specifies the number of rows and the output directory and this
* class runs a map/reduce program to generate the data.
* The format of the data is:
* <ul>
* <li>(10 bytes key) (constant 2 bytes) (32 bytes rowid)
* (constant 4 bytes) (48 bytes filler) (constant 4 bytes)
* <li>The rowid is the right justified row id as a hex number.
* </ul>
*
* <p>
* To run the program:
* <b>bin/hadoop jar hadoop-*-examples.jar teragen 10000000000 in-dir</b>
*/
public class TeraGen extends Configured implements Tool {
private static final Log LOG = LogFactory.getLog(TeraSort.class);
public static enum Counters {CHECKSUM}
public static final String NUM_ROWS = "mapreduce.terasort.num-rows";
/**
* An input format that assigns ranges of longs to each mapper.
*/
static class RangeInputFormat
extends InputFormat<LongWritable, NullWritable> {
/**
* An input split consisting of a range on numbers.
*/
static class RangeInputSplit extends InputSplit implements Writable {
long firstRow;
long rowCount;
public RangeInputSplit() { }
public RangeInputSplit(long offset, long length) {
firstRow = offset;
rowCount = length;
}
public long getLength() throws IOException {
return 0;
}
public String[] getLocations() throws IOException {
return new String[]{};
}
public void readFields(DataInput in) throws IOException {
firstRow = WritableUtils.readVLong(in);
rowCount = WritableUtils.readVLong(in);
}
public void write(DataOutput out) throws IOException {
WritableUtils.writeVLong(out, firstRow);
WritableUtils.writeVLong(out, rowCount);
}
}
/**
* A record reader that will generate a range of numbers.
*/
static class RangeRecordReader
extends RecordReader<LongWritable, NullWritable> {
long startRow;
long finishedRows;
long totalRows;
LongWritable key = null;
public RangeRecordReader() {
}
public void initialize(InputSplit split, TaskAttemptContext context)
throws IOException, InterruptedException {
startRow = ((RangeInputSplit)split).firstRow;
finishedRows = 0;
totalRows = ((RangeInputSplit)split).rowCount;
}
public void close() throws IOException {
// NOTHING
}
public LongWritable getCurrentKey() {
return key;
}
public NullWritable getCurrentValue() {
return NullWritable.get();
}
public float getProgress() throws IOException {
return finishedRows / (float) totalRows;
}
public boolean nextKeyValue() {
if (key == null) {
key = new LongWritable();
}
if (finishedRows < totalRows) {
key.set(startRow + finishedRows);
finishedRows += 1;
return true;
} else {
return false;
}
}
}
public RecordReader<LongWritable, NullWritable>
createRecordReader(InputSplit split, TaskAttemptContext context)
throws IOException {
return new RangeRecordReader();
}
/**
* Create the desired number of splits, dividing the number of rows
* between the mappers.
*/
public List<InputSplit> getSplits(JobContext job) {
long totalRows = getNumberOfRows(job);
int numSplits = job.getConfiguration().getInt(MRJobConfig.NUM_MAPS, 1);
LOG.info("Generating " + totalRows + " using " + numSplits);
List<InputSplit> splits = new ArrayList<InputSplit>();
long currentRow = 0;
for(int split = 0; split < numSplits; ++split) {
long goal =
(long) Math.ceil(totalRows * (double)(split + 1) / numSplits);
splits.add(new RangeInputSplit(currentRow, goal - currentRow));
currentRow = goal;
}
return splits;
}
}
static long getNumberOfRows(JobContext job) {
return job.getConfiguration().getLong(NUM_ROWS, 0);
}
static void setNumberOfRows(Job job, long numRows) {
job.getConfiguration().setLong(NUM_ROWS, numRows);
}
/**
* The Mapper class that given a row number, will generate the appropriate
* output line.
*/
public static class SortGenMapper
extends Mapper<LongWritable, NullWritable, Text, Text> {
private Text key = new Text();
private Text value = new Text();
private Unsigned16 rand = null;
private Unsigned16 rowId = null;
private Unsigned16 checksum = new Unsigned16();
private Checksum crc32 = new PureJavaCrc32();
private Unsigned16 total = new Unsigned16();
private static final Unsigned16 ONE = new Unsigned16(1);
private byte[] buffer = new byte[TeraInputFormat.KEY_LENGTH +
TeraInputFormat.VALUE_LENGTH];
private Counter checksumCounter;
public void map(LongWritable row, NullWritable ignored,
Context context) throws IOException, InterruptedException {
if (rand == null) {
rowId = new Unsigned16(row.get());
rand = Random16.skipAhead(rowId);
checksumCounter = context.getCounter(Counters.CHECKSUM);
}
Random16.nextRand(rand);
GenSort.generateRecord(buffer, rand, rowId);
key.set(buffer, 0, TeraInputFormat.KEY_LENGTH);
value.set(buffer, TeraInputFormat.KEY_LENGTH,
TeraInputFormat.VALUE_LENGTH);
context.write(key, value);
crc32.reset();
crc32.update(buffer, 0,
TeraInputFormat.KEY_LENGTH + TeraInputFormat.VALUE_LENGTH);
checksum.set(crc32.getValue());
total.add(checksum);
rowId.add(ONE);
}
@Override
public void cleanup(Context context) {
if (checksumCounter != null) {
checksumCounter.increment(total.getLow8());
}
}
}
private static void usage() throws IOException {
System.err.println("teragen <num rows> <output dir>");
}
/**
* Parse a number that optionally has a postfix that denotes a base.
* @param str an string integer with an option base {k,m,b,t}.
* @return the expanded value
*/
private static long parseHumanLong(String str) {
char tail = str.charAt(str.length() - 1);
long base = 1;
switch (tail) {
case 't':
base *= 1000 * 1000 * 1000 * 1000;
break;
case 'b':
base *= 1000 * 1000 * 1000;
break;
case 'm':
base *= 1000 * 1000;
break;
case 'k':
base *= 1000;
break;
default:
}
if (base != 1) {
str = str.substring(0, str.length() - 1);
}
return Long.parseLong(str) * base;
}
/**
* @param args the cli arguments
*/
public int run(String[] args)
throws IOException, InterruptedException, ClassNotFoundException {
Job job = Job.getInstance(getConf());
if (args.length != 2) {
usage();
return 2;
}
setNumberOfRows(job, parseHumanLong(args[0]));
Path outputDir = new Path(args[1]);
FileOutputFormat.setOutputPath(job, outputDir);
job.setJobName("TeraGen");
job.setJarByClass(TeraGen.class);
job.setMapperClass(SortGenMapper.class);
job.setNumReduceTasks(0);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.setInputFormatClass(RangeInputFormat.class);
job.setOutputFormatClass(TeraOutputFormat.class);
return job.waitForCompletion(true) ? 0 : 1;
}
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new TeraGen(), args);
System.exit(res);
}
}
| |
/*
Copyright 1996-2008 Ariba, 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.
$Id: //ariba/platform/util/core/ariba/util/log/StandardPatternParser.java#6 $
*/
package ariba.util.log;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.apache.log4j.helpers.FormattingInfo;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.helpers.PatternConverter;
import org.apache.log4j.helpers.PatternParser;
import ariba.util.core.Fmt;
/**
This class parses our standard conversion patterns
@aribaapi ariba
*/
public class StandardPatternParser extends PatternParser
{
static final char CUSTOMTAG_CHAR = 'T';
static final char MSGID_CHAR = 'i';
static final char DEBUGSTATE_CHAR = 's';
// Override PatternParser's handling of the date conversion option
static final char DATE_CHAR = 'd';
/**
Instantiates an instance of this class with the specific pattern
@param pattern the specified pattern
*/
public StandardPatternParser (String pattern)
{
super(pattern);
}
public void finalizeConverter (char formatChar)
{
PatternConverter pc = null;
switch(formatChar)
{
case CUSTOMTAG_CHAR:
pc = new CustomTagPatternConverter(formattingInfo);
currentLiteral.setLength(0);
addConverter(pc);
return;
case MSGID_CHAR:
pc = new MessageIdPatternConverter(formattingInfo);
currentLiteral.setLength(0);
addConverter(pc);
return;
case DEBUGSTATE_CHAR:
pc = new DebugStatePatternConverter(formattingInfo);
currentLiteral.setLength(0);
addConverter(pc);
return;
// Override PatternParser's handling of 'd' so we can force
// the date to be formatted in US English.
case DATE_CHAR:
DateFormat df;
String dOpt = extractOption();
if (dOpt != null) {
String dateFormatStr = dOpt;
try {
df = new SimpleDateFormat(dateFormatStr, Locale.US);
}
catch (IllegalArgumentException e) {
break;
}
pc = new DatePatternConverter(formattingInfo, df);
currentLiteral.setLength(0);
addConverter(pc);
return;
}
}
// Use PatternParser method if we had an error processing the case
// or if it is one of the cases we don't handle.
super.finalizeConverter(formatChar);
}
abstract private static class StandardPatternConverter
extends PatternConverter
{
StandardPatternConverter (FormattingInfo formattingInfo)
{
super(formattingInfo);
}
public String convert (org.apache.log4j.spi.LoggingEvent event)
{
String result = null;
LoggingEvent appEvent = null;
if (event instanceof LoggingEvent) {
appEvent = (LoggingEvent)event;
result = convert(appEvent);
}
else {
result = "unknown";
}
return result;
}
public abstract String convert (LoggingEvent event);
}
private static class DatePatternConverter extends StandardPatternConverter {
private DateFormat df;
private Date date;
DatePatternConverter (FormattingInfo formattingInfo, DateFormat df) {
super(formattingInfo);
date = new Date();
this.df = df;
}
public String convert (LoggingEvent event)
{
date.setTime(event.timeStamp);
String converted = null;
try {
converted = df.format(date);
}
catch (NullPointerException ex) {
LogLog.error("Error occurred while converting date--Date null.",
ex);
}
return converted;
}
}
private static class CustomTagPatternConverter
extends StandardPatternConverter
{
CustomTagPatternConverter (FormattingInfo formatInfo)
{
super(formatInfo);
}
public String convert (LoggingEvent event)
{
return event.getCustomTag();
}
}
private static class MessageIdPatternConverter
extends StandardPatternConverter
{
MessageIdPatternConverter (FormattingInfo formatInfo)
{
super(formatInfo);
}
public String convert (LoggingEvent event)
{
String id = event.getMessageId();
return (id != null) ? Fmt.S("[ID%s]", id) : null;
}
}
private static class DebugStatePatternConverter
extends StandardPatternConverter
{
DebugStatePatternConverter (FormattingInfo formatInfo)
{
super(formatInfo);
}
public String convert (LoggingEvent event)
{
String state = event.getCallerThreadDebugState();
return (state != null) ? Fmt.S("%s\n", state) : null;
}
}
}
| |
/*
* 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.drill.exec.physical.impl;
import static org.apache.drill.test.TestBuilder.listOf;
import static org.apache.drill.test.TestBuilder.mapOf;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.drill.categories.UnlikelyTest;
import org.apache.drill.exec.ExecConstants;
import org.apache.drill.exec.compile.ClassCompilerSelector;
import org.apache.drill.exec.compile.ClassTransformer;
import org.apache.drill.exec.compile.CodeCompiler;
import org.apache.drill.exec.expr.fn.impl.DateUtility;
import org.apache.drill.exec.proto.UserBitShared.QueryType;
import org.apache.drill.exec.record.RecordBatchLoader;
import org.apache.drill.exec.rpc.user.QueryDataBatch;
import org.apache.drill.exec.util.ByteBufUtil.HadoopWritables;
import org.apache.drill.exec.vector.ValueVector;
import org.apache.drill.exec.vector.VarCharVector;
import org.apache.drill.test.BaseTestQuery;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.drill.shaded.guava.com.google.common.base.Charsets;
import org.apache.drill.shaded.guava.com.google.common.io.Resources;
import io.netty.buffer.DrillBuf;
@Category(UnlikelyTest.class)
public class TestConvertFunctions extends BaseTestQuery {
private static final String CONVERSION_TEST_LOGICAL_PLAN = "functions/conv/conversionTestWithLogicalPlan.json";
private static final String CONVERSION_TEST_PHYSICAL_PLAN = "functions/conv/conversionTestWithPhysicalPlan.json";
private static final float DELTA = (float) 0.0001;
// "1980-01-01 01:23:45.678"
private static final String DATE_TIME_BE = "\\x00\\x00\\x00\\x49\\x77\\x85\\x1f\\x8e";
private static final String DATE_TIME_LE = "\\x8e\\x1f\\x85\\x77\\x49\\x00\\x00\\x00";
private static LocalTime time = LocalTime.parse("01:23:45.678", DateUtility.getTimeFormatter());
private static LocalDate date = LocalDate.parse("1980-01-01", DateUtility.getDateTimeFormatter());
private String textFileContent;
@BeforeClass
public static void setup() {
// Tests here rely on the byte-code merge approach to code
// generation and will fail if using plain-old Java.
// Actually, some queries succeed with plain-old Java that
// fail with scalar replacement, but the tests check for the
// scalar replacement failure and, not finding it, fail the
// test.
//
// The setting here forces byte-code merge even if the
// config file asks for plain-old Java.
//
// TODO: Fix the tests to handle both cases.
System.setProperty(CodeCompiler.PREFER_POJ_CONFIG, "false");
}
@Test // DRILL-3854
public void testConvertFromConvertToInt() throws Exception {
String newTblName = "testConvertFromConvertToInt_tbl";
try {
setSessionOption(ExecConstants.SLICE_TARGET, 1);
test("CREATE TABLE dfs.%s as \n" +
"SELECT convert_to(r_regionkey, 'INT') as ct \n" +
"FROM cp.`tpch/region.parquet`", newTblName);
testBuilder()
.sqlQuery("SELECT convert_from(ct, 'INT') as cf \n" +
"FROM dfs.%s \n" +
"ORDER BY ct", newTblName)
.unOrdered()
.baselineColumns("cf")
.baselineValuesForSingleColumn(0, 1, 2, 3, 4)
.build()
.run();
} finally {
resetSessionOption(ExecConstants.SLICE_TARGET);
test("drop table if exists dfs.%s", newTblName);
}
}
@Test
public void test_JSON_convertTo_empty_list_drill_1416() throws Exception {
String listStr = "[ 4, 6 ]";
testBuilder()
.sqlQuery("select cast(convert_to(rl[1], 'JSON') as varchar(100)) as json_str from cp.`store/json/input2.json`")
.unOrdered()
.baselineColumns("json_str")
.baselineValues(listStr)
.baselineValues("[ ]")
.baselineValues(listStr)
.baselineValues(listStr)
.go();
Object listVal = listOf(4l, 6l);
testBuilder()
.sqlQuery("select convert_from(convert_to(rl[1], 'JSON'), 'JSON') list_col from cp.`store/json/input2.json`")
.unOrdered()
.baselineColumns("list_col")
.baselineValues(listVal)
.baselineValues(listOf())
.baselineValues(listVal)
.baselineValues(listVal)
.go();
Object mapVal1 = mapOf("f1", 4l, "f2", 6l);
Object mapVal2 = mapOf("f1", 11l);
testBuilder()
.sqlQuery("select convert_from(convert_to(rl[1], 'JSON'), 'JSON') as map_col from cp.`store/json/json_project_null_object_from_list.json`")
.unOrdered()
.baselineColumns("map_col")
.baselineValues(mapVal1)
.baselineValues(mapOf())
.baselineValues(mapVal2)
.baselineValues(mapVal1)
.go();
}
@Test // DRILL-4679
public void testConvertFromJson_drill4679() throws Exception {
Object mapVal1 = mapOf("y", "kevin", "z", "paul");
Object mapVal2 = mapOf("y", "bill", "z", "peter");
// right side of union-all produces 0 rows due to FALSE filter, column t.x is a map
String query1 = String.format("select 'abc' as col1, convert_from(convert_to(t.x, 'JSON'), 'JSON') as col2, 'xyz' as col3 from cp.`store/json/input2.json` t "
+ " where t.`integer` = 2010 "
+ " union all "
+ " select 'abc' as col1, convert_from(convert_to(t.x, 'JSON'), 'JSON') as col2, 'xyz' as col3 from cp.`store/json/input2.json` t"
+ " where 1 = 0");
testBuilder()
.sqlQuery(query1)
.unOrdered()
.baselineColumns("col1", "col2", "col3")
.baselineValues("abc", mapVal1, "xyz")
.go();
// left side of union-all produces 0 rows due to FALSE filter, column t.x is a map
String query2 = String.format("select 'abc' as col1, convert_from(convert_to(t.x, 'JSON'), 'JSON') as col2, 'xyz' as col3 from cp.`store/json/input2.json` t "
+ " where 1 = 0 "
+ " union all "
+ " select 'abc' as col1, convert_from(convert_to(t.x, 'JSON'), 'JSON') as col2, 'xyz' as col3 from cp.`store/json/input2.json` t "
+ " where t.`integer` = 2010");
testBuilder()
.sqlQuery(query2)
.unOrdered()
.baselineColumns("col1", "col2", "col3")
.baselineValues("abc", mapVal1, "xyz")
.go();
// sanity test where neither side produces 0 rows
String query3 = String.format("select 'abc' as col1, convert_from(convert_to(t.x, 'JSON'), 'JSON') as col2, 'xyz' as col3 from cp.`store/json/input2.json` t "
+ " where t.`integer` = 2010 "
+ " union all "
+ " select 'abc' as col1, convert_from(convert_to(t.x, 'JSON'), 'JSON') as col2, 'xyz' as col3 from cp.`store/json/input2.json` t "
+ " where t.`integer` = 2001");
testBuilder()
.sqlQuery(query3)
.unOrdered()
.baselineColumns("col1", "col2", "col3")
.baselineValues("abc", mapVal1, "xyz")
.baselineValues("abc", mapVal2, "xyz")
.go();
// convert_from() on a list, column t.rl is a repeated list
Object listVal1 = listOf(listOf(2l, 1l), listOf(4l, 6l));
Object listVal2 = listOf(); // empty
String query4 = String.format("select 'abc' as col1, convert_from(convert_to(t.rl, 'JSON'), 'JSON') as col2, 'xyz' as col3 from cp.`store/json/input2.json` t "
+ " union all "
+ " select 'abc' as col1, convert_from(convert_to(t.rl, 'JSON'), 'JSON') as col2, 'xyz' as col3 from cp.`store/json/input2.json` t"
+ " where 1 = 0");
testBuilder()
.sqlQuery(query4)
.unOrdered()
.baselineColumns("col1", "col2", "col3")
.baselineValues("abc", listVal1, "xyz")
.baselineValues("abc", listVal2, "xyz")
.baselineValues("abc", listVal1, "xyz")
.baselineValues("abc", listVal1, "xyz")
.go();
}
@Test // DRILL-4693
public void testConvertFromJson_drill4693() throws Exception {
Object mapVal1 = mapOf("x", "y");
testBuilder()
.sqlQuery("select 'abc' as col1, convert_from('{\"x\" : \"y\"}', 'json') as col2, 'xyz' as col3 "
+ " from cp.`store/json/input2.json` t"
+ " where t.`integer` = 2001")
.unOrdered()
.baselineColumns("col1", "col2", "col3")
.baselineValues("abc", mapVal1, "xyz")
.go();
}
@Test
public void testConvertFromJsonNullableInput() throws Exception {
// Contents of the generated file:
/*
{"k": "{a: 1, b: 2}"}
{"k": null}
{"k": "{c: 3}"}
*/
try (BufferedWriter writer = new BufferedWriter(new FileWriter(
new File(dirTestWatcher.getRootDir(), "nullable_json_strings.json")))) {
String[] fieldValue = {"\"{a: 1, b: 2}\"", null, "\"{c: 3}\""};
for (String value : fieldValue) {
String entry = String.format("{\"k\": %s}\n", value);
writer.write(entry);
}
}
testBuilder()
.sqlQuery("select convert_from(k, 'json') as col from dfs.`nullable_json_strings.json`")
.unOrdered()
.baselineColumns("col")
.baselineValues(mapOf("a", 1L, "b", 2L))
.baselineValues(mapOf())
.baselineValues(mapOf("c", 3L))
.go();
}
@Test
public void testConvertToComplexJSON() throws Exception {
String result1 =
"[ {\n" +
" \"$numberLong\" : 4\n" +
"}, {\n" +
" \"$numberLong\" : 6\n" +
"} ]";
String result2 = "[ ]";
testBuilder()
.sqlQuery("select cast(convert_to(rl[1], 'EXTENDEDJSON') as varchar(100)) as json_str from cp.`store/json/input2.json`")
.unOrdered()
.baselineColumns("json_str")
.baselineValues(result1)
.baselineValues(result2)
.baselineValues(result1)
.baselineValues(result1)
.go();
}
@Test
public void testDateTime1() throws Throwable {
verifyPhysicalPlan("(convert_from(binary_string('" + DATE_TIME_BE + "'), 'TIME_EPOCH_BE'))", time);
}
@Test
public void testDateTime2() throws Throwable {
verifyPhysicalPlan("convert_from(binary_string('" + DATE_TIME_LE + "'), 'TIME_EPOCH')", time);
}
@Test
public void testDateTime3() throws Throwable {
verifyPhysicalPlan("convert_from(binary_string('" + DATE_TIME_BE + "'), 'DATE_EPOCH_BE')", date );
}
@Test
public void testDateTime4() throws Throwable {
verifyPhysicalPlan("convert_from(binary_string('" + DATE_TIME_LE + "'), 'DATE_EPOCH')", date);
}
@Test
public void testFixedInts1() throws Throwable {
verifyPhysicalPlan("convert_from(binary_string('\\xAD'), 'TINYINT')", (byte) 0xAD);
}
@Test
public void testFixedInts2() throws Throwable {
verifyPhysicalPlan("convert_from(binary_string('\\xFE\\xCA'), 'SMALLINT')", (short) 0xCAFE);
}
@Test
public void testFixedInts3() throws Throwable {
verifyPhysicalPlan("convert_from(binary_string('\\xCA\\xFE'), 'SMALLINT_BE')", (short) 0xCAFE);
}
@Test
public void testFixedInts4() throws Throwable {
verifyPhysicalPlan("convert_from(binary_string('\\xBE\\xBA\\xFE\\xCA'), 'INT')", 0xCAFEBABE);
}
@Test
public void testFixedInts4SQL_from() throws Throwable {
verifySQL("select"
+ " convert_from(binary_string('\\xBE\\xBA\\xFE\\xCA'), 'INT')"
+ " from"
+ " cp.`employee.json` LIMIT 1",
0xCAFEBABE);
}
@Test
public void testFixedInts4SQL_to() throws Throwable {
verifySQL("select"
+ " convert_to(-889275714, 'INT')"
+ " from"
+ " cp.`employee.json` LIMIT 1",
new byte[] {(byte) 0xBE, (byte) 0xBA, (byte) 0xFE, (byte) 0xCA});
}
@Test
public void testFixedInts5() throws Throwable {
verifyPhysicalPlan("convert_from(binary_string('\\xCA\\xFE\\xBA\\xBE'), 'INT_BE')", 0xCAFEBABE);
}
@Test
public void testFixedInts6() throws Throwable {
verifyPhysicalPlan("convert_from(binary_string('\\xEF\\xBE\\xAD\\xDE\\xBE\\xBA\\xFE\\xCA'), 'BIGINT')", 0xCAFEBABEDEADBEEFL);
}
@Test
public void testFixedInts7() throws Throwable {
verifyPhysicalPlan("convert_from(binary_string('\\xCA\\xFE\\xBA\\xBE\\xDE\\xAD\\xBE\\xEF'), 'BIGINT_BE')", 0xCAFEBABEDEADBEEFL);
}
@Test
public void testFixedInts8() throws Throwable {
verifyPhysicalPlan("convert_from(convert_to(cast(77 as varchar(2)), 'INT_BE'), 'INT_BE')", 77);
}
@Test
public void testFixedInts9() throws Throwable {
verifyPhysicalPlan("convert_to(cast(77 as varchar(2)), 'INT_BE')", new byte[] {0, 0, 0, 77});
}
@Test
public void testFixedInts10() throws Throwable {
verifyPhysicalPlan("convert_to(cast(77 as varchar(2)), 'INT')", new byte[] {77, 0, 0, 0});
}
@Test
public void testFixedInts11() throws Throwable {
verifyPhysicalPlan("convert_to(77, 'BIGINT_BE')", new byte[] {0, 0, 0, 0, 0, 0, 0, 77});
}
@Test
public void testFixedInts12() throws Throwable {
verifyPhysicalPlan("convert_to(9223372036854775807, 'BIGINT')", new byte[] {-1, -1, -1, -1, -1, -1, -1, 0x7f});
}
@Test
public void testFixedInts13() throws Throwable {
verifyPhysicalPlan("convert_to(-9223372036854775808, 'BIGINT')", new byte[] {0, 0, 0, 0, 0, 0, 0, (byte)0x80});
}
@Test
public void testVInts1() throws Throwable {
verifyPhysicalPlan("convert_to(cast(0 as int), 'INT_HADOOPV')", new byte[] {0});
}
@Test
public void testVInts2() throws Throwable {
verifyPhysicalPlan("convert_to(cast(128 as int), 'INT_HADOOPV')", new byte[] {-113, -128});
}
@Test
public void testVInts3() throws Throwable {
verifyPhysicalPlan("convert_to(cast(256 as int), 'INT_HADOOPV')", new byte[] {-114, 1, 0});
}
@Test
public void testVInts4() throws Throwable {
verifyPhysicalPlan("convert_to(cast(65536 as int), 'INT_HADOOPV')", new byte[] {-115, 1, 0, 0});
}
@Test
public void testVInts5() throws Throwable {
verifyPhysicalPlan("convert_to(cast(16777216 as int), 'INT_HADOOPV')", new byte[] {-116, 1, 0, 0, 0});
}
@Test
public void testVInts6() throws Throwable {
verifyPhysicalPlan("convert_to(4294967296, 'BIGINT_HADOOPV')", new byte[] {-117, 1, 0, 0, 0, 0});
}
@Test
public void testVInts7() throws Throwable {
verifyPhysicalPlan("convert_to(1099511627776, 'BIGINT_HADOOPV')", new byte[] {-118, 1, 0, 0, 0, 0, 0});
}
@Test
public void testVInts8() throws Throwable {
verifyPhysicalPlan("convert_to(281474976710656, 'BIGINT_HADOOPV')", new byte[] {-119, 1, 0, 0, 0, 0, 0, 0});
}
@Test
public void testVInts9() throws Throwable {
verifyPhysicalPlan("convert_to(72057594037927936, 'BIGINT_HADOOPV')", new byte[] {-120, 1, 0, 0, 0, 0, 0, 0, 0});
}
@Test
public void testVInts10() throws Throwable {
verifyPhysicalPlan("convert_to(9223372036854775807, 'BIGINT_HADOOPV')", new byte[] {-120, 127, -1, -1, -1, -1, -1, -1, -1});
}
@Test
public void testVInts11() throws Throwable {
verifyPhysicalPlan("convert_from(binary_string('\\x88\\x7f\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF'), 'BIGINT_HADOOPV')", 9223372036854775807L);
}
@Test
public void testVInts12() throws Throwable {
verifyPhysicalPlan("convert_to(-9223372036854775808, 'BIGINT_HADOOPV')", new byte[] {-128, 127, -1, -1, -1, -1, -1, -1, -1});
}
@Test
public void testVInts13() throws Throwable {
verifyPhysicalPlan("convert_from(binary_string('\\x80\\x7f\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF'), 'BIGINT_HADOOPV')", -9223372036854775808L);
}
@Test
public void testBool1() throws Throwable {
verifyPhysicalPlan("convert_from(binary_string('\\x01'), 'BOOLEAN_BYTE')", true);
}
@Test
public void testBool2() throws Throwable {
verifyPhysicalPlan("convert_from(binary_string('\\x00'), 'BOOLEAN_BYTE')", false);
}
@Test
public void testBool3() throws Throwable {
verifyPhysicalPlan("convert_to(true, 'BOOLEAN_BYTE')", new byte[] {1});
}
@Test
public void testBool4() throws Throwable {
verifyPhysicalPlan("convert_to(false, 'BOOLEAN_BYTE')", new byte[] {0});
}
@Test
public void testFloats1() throws Throwable {
}
@Test
public void testFloats2() throws Throwable {
verifyPhysicalPlan("convert_from(convert_to(cast(77 as float4), 'FLOAT'), 'FLOAT')", new Float(77.0));
}
@Test
public void testFloats2be() throws Throwable {
verifyPhysicalPlan("convert_from(convert_to(cast(77 as float4), 'FLOAT_BE'), 'FLOAT_BE')", new Float(77.0));
}
@Test
public void testFloats3() throws Throwable {
verifyPhysicalPlan("convert_to(cast(1.4e-45 as float4), 'FLOAT')", new byte[] {1, 0, 0, 0});
}
@Test
public void testFloats4() throws Throwable {
verifyPhysicalPlan("convert_to(cast(3.4028235e+38 as float4), 'FLOAT')", new byte[] {-1, -1, 127, 127});
}
@Test
public void testFloats5() throws Throwable {
verifyPhysicalPlan("convert_from(convert_to(cast(77 as float8), 'DOUBLE'), 'DOUBLE')", 77.0);
}
@Test
public void testFloats5be() throws Throwable {
verifyPhysicalPlan("convert_from(convert_to(cast(77 as float8), 'DOUBLE_BE'), 'DOUBLE_BE')", 77.0);
}
@Test
public void testFloats6() throws Throwable {
verifyPhysicalPlan("convert_to(cast(77 as float8), 'DOUBLE')", new byte[] {0, 0, 0, 0, 0, 64, 83, 64});
}
@Test
public void testFloats7() throws Throwable {
verifyPhysicalPlan("convert_to(4.9e-324, 'DOUBLE')", new byte[] {1, 0, 0, 0, 0, 0, 0, 0});
}
@Test
public void testFloats8() throws Throwable {
verifyPhysicalPlan("convert_to(1.7976931348623157e+308, 'DOUBLE')", new byte[] {-1, -1, -1, -1, -1, -1, -17, 127});
}
@Test
public void testUTF8() throws Throwable {
verifyPhysicalPlan("convert_from(binary_string('apache_drill'), 'UTF8')", "apache_drill");
verifyPhysicalPlan("convert_to('apache_drill', 'UTF8')", new byte[] {'a', 'p', 'a', 'c', 'h', 'e', '_', 'd', 'r', 'i', 'l', 'l'});
}
@Test // DRILL-2326
public void testBigIntVarCharReturnTripConvertLogical() throws Exception {
String logicalPlan = Resources.toString(
Resources.getResource(CONVERSION_TEST_LOGICAL_PLAN), Charsets.UTF_8);
List<String> compilers = Arrays.asList(ClassCompilerSelector.CompilerPolicy.JANINO.name(),
ClassCompilerSelector.CompilerPolicy.JDK.name());
try {
setSessionOption(ExecConstants.SCALAR_REPLACEMENT_OPTION, ClassTransformer.ScalarReplacementOption.ON.name());
for (String compilerName : compilers) {
setSessionOption(ClassCompilerSelector.JAVA_COMPILER_OPTION, compilerName);
int count = testRunAndPrint(QueryType.LOGICAL, logicalPlan);
assertEquals(10, count);
}
} finally {
resetSessionOption(ExecConstants.SCALAR_REPLACEMENT_OPTION);
resetSessionOption(ClassCompilerSelector.JAVA_COMPILER_OPTION);
}
}
@Test
public void testHadooopVInt() throws Exception {
final int _0 = 0;
final int _9 = 9;
final DrillBuf buffer = getAllocator().buffer(_9);
long longVal = 0;
buffer.clear();
HadoopWritables.writeVLong(buffer, _0, _9, 0);
longVal = HadoopWritables.readVLong(buffer, _0, _9);
assertEquals(longVal, 0);
buffer.clear();
HadoopWritables.writeVLong(buffer, _0, _9, Long.MAX_VALUE);
longVal = HadoopWritables.readVLong(buffer, _0, _9);
assertEquals(longVal, Long.MAX_VALUE);
buffer.clear();
HadoopWritables.writeVLong(buffer, _0, _9, Long.MIN_VALUE);
longVal = HadoopWritables.readVLong(buffer, _0, _9);
assertEquals(longVal, Long.MIN_VALUE);
int intVal = 0;
buffer.clear();
HadoopWritables.writeVInt(buffer, _0, _9, 0);
intVal = HadoopWritables.readVInt(buffer, _0, _9);
assertEquals(intVal, 0);
buffer.clear();
HadoopWritables.writeVInt(buffer, _0, _9, Integer.MAX_VALUE);
intVal = HadoopWritables.readVInt(buffer, _0, _9);
assertEquals(intVal, Integer.MAX_VALUE);
buffer.clear();
HadoopWritables.writeVInt(buffer, _0, _9, Integer.MIN_VALUE);
intVal = HadoopWritables.readVInt(buffer, _0, _9);
assertEquals(intVal, Integer.MIN_VALUE);
buffer.release();
}
@Test // DRILL-4862 & DRILL-2326
public void testBinaryString() throws Exception {
String query =
"SELECT convert_from(binary_string(key), 'INT_BE') as intkey \n" +
"FROM cp.`functions/conv/conv.json`";
List<String> compilers = Arrays.asList(ClassCompilerSelector.CompilerPolicy.JANINO.name(),
ClassCompilerSelector.CompilerPolicy.JDK.name());
try {
setSessionOption(ExecConstants.SCALAR_REPLACEMENT_OPTION, ClassTransformer.ScalarReplacementOption.ON.name());
for (String compilerName : compilers) {
setSessionOption(ClassCompilerSelector.JAVA_COMPILER_OPTION, compilerName);
testBuilder()
.sqlQuery(query)
.unOrdered()
.baselineColumns("intkey")
.baselineValuesForSingleColumn(1244739896, null, 1313814865, 1852782897)
.build()
.run();
}
} finally {
resetSessionOption(ExecConstants.SCALAR_REPLACEMENT_OPTION);
resetSessionOption(ClassCompilerSelector.JAVA_COMPILER_OPTION);
}
}
protected <T> void verifySQL(String sql, T expectedResults) throws Throwable {
verifyResults(sql, expectedResults, getRunResult(QueryType.SQL, sql));
}
protected <T> void verifyPhysicalPlan(String expression, T expectedResults) throws Throwable {
expression = expression.replace("\\", "\\\\\\\\"); // "\\\\\\\\" => Java => "\\\\" => JsonParser => "\\" => AntlrParser "\"
if (textFileContent == null) {
textFileContent = Resources.toString(Resources.getResource(CONVERSION_TEST_PHYSICAL_PLAN), Charsets.UTF_8);
}
String planString = textFileContent.replace("__CONVERT_EXPRESSION__", expression);
verifyResults(expression, expectedResults, getRunResult(QueryType.PHYSICAL, planString));
}
protected Object[] getRunResult(QueryType queryType, String planString) throws Exception {
List<QueryDataBatch> resultList = testRunAndReturn(queryType, planString);
List<Object> res = new ArrayList<Object>();
RecordBatchLoader loader = new RecordBatchLoader(getAllocator());
for(QueryDataBatch result : resultList) {
if (result.getData() != null) {
loader.load(result.getHeader().getDef(), result.getData());
ValueVector v = loader.iterator().next().getValueVector();
for (int j = 0; j < v.getAccessor().getValueCount(); j++) {
if (v instanceof VarCharVector) {
res.add(new String(((VarCharVector) v).getAccessor().get(j)));
} else {
res.add(v.getAccessor().getObject(j));
}
}
loader.clear();
result.release();
}
}
return res.toArray();
}
protected <T> void verifyResults(String expression, T expectedResults, Object[] actualResults) throws Throwable {
String testName = String.format("Expression: %s.", expression);
assertEquals(testName, 1, actualResults.length);
assertNotNull(testName, actualResults[0]);
if (expectedResults.getClass().isArray()) {
assertArraysEquals(testName, expectedResults, actualResults[0]);
} else {
assertEquals(testName, expectedResults, actualResults[0]);
}
}
protected void assertArraysEquals(Object expected, Object actual) {
assertArraysEquals(null, expected, actual);
}
protected void assertArraysEquals(String message, Object expected, Object actual) {
if (expected instanceof byte[] && actual instanceof byte[]) {
assertArrayEquals(message, (byte[]) expected, (byte[]) actual);
} else if (expected instanceof Object[] && actual instanceof Object[]) {
assertArrayEquals(message, (Object[]) expected, (Object[]) actual);
} else if (expected instanceof char[] && actual instanceof char[]) {
assertArrayEquals(message, (char[]) expected, (char[]) actual);
} else if (expected instanceof short[] && actual instanceof short[]) {
assertArrayEquals(message, (short[]) expected, (short[]) actual);
} else if (expected instanceof int[] && actual instanceof int[]) {
assertArrayEquals(message, (int[]) expected, (int[]) actual);
} else if (expected instanceof long[] && actual instanceof long[]) {
assertArrayEquals(message, (long[]) expected, (long[]) actual);
} else if (expected instanceof float[] && actual instanceof float[]) {
assertArrayEquals(message, (float[]) expected, (float[]) actual, DELTA);
} else if (expected instanceof double[] && actual instanceof double[]) {
assertArrayEquals(message, (double[]) expected, (double[]) actual, DELTA);
} else {
fail(String.format("%s: Error comparing arrays of type '%s' and '%s'",
expected.getClass().getName(), (actual == null ? "null" : actual.getClass().getName())));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.