gt
stringclasses
1 value
context
stringlengths
2.05k
161k
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.deeplearning4j.zoo.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.NoArgsConstructor; import org.deeplearning4j.common.resources.DL4JResources; import org.deeplearning4j.nn.api.Model; import org.deeplearning4j.nn.api.OptimizationAlgorithm; import org.deeplearning4j.nn.conf.*; import org.deeplearning4j.nn.conf.distribution.NormalDistribution; import org.deeplearning4j.nn.conf.graph.ElementWiseVertex; import org.deeplearning4j.nn.conf.inputs.InputType; import org.deeplearning4j.nn.conf.layers.*; import org.deeplearning4j.nn.graph.ComputationGraph; import org.deeplearning4j.nn.weights.WeightInit; import org.deeplearning4j.zoo.ModelMetaData; import org.deeplearning4j.zoo.PretrainedType; import org.deeplearning4j.zoo.ZooModel; import org.deeplearning4j.zoo.ZooType; import org.nd4j.linalg.activations.Activation; import org.nd4j.linalg.learning.config.AdaDelta; import org.nd4j.linalg.learning.config.AdaGrad; import org.nd4j.linalg.learning.config.IUpdater; import org.nd4j.linalg.lossfunctions.LossFunctions; /** * U-Net * * An implementation of Xception in Deeplearning4j. A novel deep convolutional neural network architecture inspired by * Inception, where Inception modules have been replaced with depthwise separable convolutions. * * <p>Paper: <a href="https://arxiv.org/abs/1610.02357">https://arxiv.org/abs/1610.02357</a></p> * <p>ImageNet weights for this model are available and have been converted from <a href="https://keras.io/applications/"> * https://keras.io/applications/</a>.</p> * * @author Justin Long (crockpotveggies) * */ @AllArgsConstructor @Builder public class Xception extends ZooModel { @Builder.Default private long seed = 1234; @Builder.Default private int[] inputShape = new int[] {3, 299, 299}; @Builder.Default private int numClasses = 0; @Builder.Default private WeightInit weightInit = WeightInit.RELU; @Builder.Default private IUpdater updater = new AdaDelta(); @Builder.Default private CacheMode cacheMode = CacheMode.NONE; @Builder.Default private WorkspaceMode workspaceMode = WorkspaceMode.ENABLED; @Builder.Default private ConvolutionLayer.AlgoMode cudnnAlgoMode = ConvolutionLayer.AlgoMode.PREFER_FASTEST; private Xception() {} @Override public String pretrainedUrl(PretrainedType pretrainedType) { if (pretrainedType == PretrainedType.IMAGENET) return DL4JResources.getURLString("models/xception_dl4j_inference.v2.zip"); else return null; } @Override public long pretrainedChecksum(PretrainedType pretrainedType) { if (pretrainedType == PretrainedType.IMAGENET) return 3277876097L; else return 0L; } @Override public Class<? extends Model> modelType() { return ComputationGraph.class; } @Override public ComputationGraph init() { ComputationGraphConfiguration.GraphBuilder graph = graphBuilder(); graph.addInputs("input").setInputTypes(InputType.convolutional(inputShape[2], inputShape[1], inputShape[0])); ComputationGraphConfiguration conf = graph.build(); ComputationGraph model = new ComputationGraph(conf); model.init(); return model; } public ComputationGraphConfiguration.GraphBuilder graphBuilder() { ComputationGraphConfiguration.GraphBuilder graph = new NeuralNetConfiguration.Builder().seed(seed) .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT) .updater(updater) .weightInit(weightInit) .l2(4e-5) .miniBatch(true) .cacheMode(cacheMode) .trainingWorkspaceMode(workspaceMode) .inferenceWorkspaceMode(workspaceMode) .convolutionMode(ConvolutionMode.Truncate) .graphBuilder(); graph // block1 .addLayer("block1_conv1", new ConvolutionLayer.Builder(3,3).stride(2,2).nOut(32).hasBias(false) .cudnnAlgoMode(cudnnAlgoMode).build(), "input") .addLayer("block1_conv1_bn", new BatchNormalization(), "block1_conv1") .addLayer("block1_conv1_act", new ActivationLayer(Activation.RELU), "block1_conv1_bn") .addLayer("block1_conv2", new ConvolutionLayer.Builder(3,3).stride(1,1).nOut(64).hasBias(false) .cudnnAlgoMode(cudnnAlgoMode).build(), "block1_conv1_act") .addLayer("block1_conv2_bn", new BatchNormalization(), "block1_conv2") .addLayer("block1_conv2_act", new ActivationLayer(Activation.RELU), "block1_conv2_bn") // residual1 .addLayer("residual1_conv", new ConvolutionLayer.Builder(1,1).stride(2,2).nOut(128).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), "block1_conv2_act") .addLayer("residual1", new BatchNormalization(), "residual1_conv") // block2 .addLayer("block2_sepconv1", new SeparableConvolution2D.Builder(3,3).nOut(128).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), "block1_conv2_act") .addLayer("block2_sepconv1_bn", new BatchNormalization(), "block2_sepconv1") .addLayer("block2_sepconv1_act",new ActivationLayer(Activation.RELU), "block2_sepconv1_bn") .addLayer("block2_sepconv2", new SeparableConvolution2D.Builder(3,3).nOut(128).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), "block2_sepconv1_act") .addLayer("block2_sepconv2_bn", new BatchNormalization(), "block2_sepconv2") .addLayer("block2_pool", new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX).kernelSize(3,3).stride(2,2) .convolutionMode(ConvolutionMode.Same).build(), "block2_sepconv2_bn") .addVertex("add1", new ElementWiseVertex(ElementWiseVertex.Op.Add), "block2_pool", "residual1") // residual2 .addLayer("residual2_conv", new ConvolutionLayer.Builder(1,1).stride(2,2).nOut(256).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), "add1") .addLayer("residual2", new BatchNormalization(), "residual2_conv") // block3 .addLayer("block3_sepconv1_act", new ActivationLayer(Activation.RELU), "add1") .addLayer("block3_sepconv1", new SeparableConvolution2D.Builder(3,3).nOut(256).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), "block3_sepconv1_act") .addLayer("block3_sepconv1_bn", new BatchNormalization(), "block3_sepconv1") .addLayer("block3_sepconv2_act", new ActivationLayer(Activation.RELU), "block3_sepconv1_bn") .addLayer("block3_sepconv2", new SeparableConvolution2D.Builder(3,3).nOut(256).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), "block3_sepconv2_act") .addLayer("block3_sepconv2_bn", new BatchNormalization(), "block3_sepconv2") .addLayer("block3_pool", new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX).kernelSize(3,3).stride(2,2) .convolutionMode(ConvolutionMode.Same).build(), "block3_sepconv2_bn") .addVertex("add2", new ElementWiseVertex(ElementWiseVertex.Op.Add), "block3_pool", "residual2") // residual3 .addLayer("residual3_conv", new ConvolutionLayer.Builder(1,1).stride(2,2).nOut(728).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), "add2") .addLayer("residual3", new BatchNormalization(), "residual3_conv") // block4 .addLayer("block4_sepconv1_act", new ActivationLayer(Activation.RELU), "add2") .addLayer("block4_sepconv1", new SeparableConvolution2D.Builder(3,3).nOut(728).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), "block4_sepconv1_act") .addLayer("block4_sepconv1_bn", new BatchNormalization(), "block4_sepconv1") .addLayer("block4_sepconv2_act", new ActivationLayer(Activation.RELU), "block4_sepconv1_bn") .addLayer("block4_sepconv2", new SeparableConvolution2D.Builder(3,3).nOut(728).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), "block4_sepconv2_act") .addLayer("block4_sepconv2_bn", new BatchNormalization(), "block4_sepconv2") .addLayer("block4_pool", new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX).kernelSize(3,3).stride(2,2) .convolutionMode(ConvolutionMode.Same).build(), "block4_sepconv2_bn") .addVertex("add3", new ElementWiseVertex(ElementWiseVertex.Op.Add), "block4_pool", "residual3"); // towers int residual = 3; int block = 5; for(int i = 0; i < 8; i++) { String previousInput = "add"+residual; String blockName = "block"+block; graph .addLayer(blockName+"_sepconv1_act", new ActivationLayer(Activation.RELU), previousInput) .addLayer(blockName+"_sepconv1", new SeparableConvolution2D.Builder(3,3).nOut(728).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), blockName+"_sepconv1_act") .addLayer(blockName+"_sepconv1_bn", new BatchNormalization(), blockName+"_sepconv1") .addLayer(blockName+"_sepconv2_act", new ActivationLayer(Activation.RELU), blockName+"_sepconv1_bn") .addLayer(blockName+"_sepconv2", new SeparableConvolution2D.Builder(3,3).nOut(728).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), blockName+"_sepconv2_act") .addLayer(blockName+"_sepconv2_bn", new BatchNormalization(), blockName+"_sepconv2") .addLayer(blockName+"_sepconv3_act", new ActivationLayer(Activation.RELU), blockName+"_sepconv2_bn") .addLayer(blockName+"_sepconv3", new SeparableConvolution2D.Builder(3,3).nOut(728).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), blockName+"_sepconv3_act") .addLayer(blockName+"_sepconv3_bn", new BatchNormalization(), blockName+"_sepconv3") .addVertex("add"+(residual+1), new ElementWiseVertex(ElementWiseVertex.Op.Add), blockName+"_sepconv3_bn", previousInput); residual++; block++; } // residual12 graph.addLayer("residual12_conv", new ConvolutionLayer.Builder(1,1).stride(2,2).nOut(1024).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), "add" + residual) .addLayer("residual12", new BatchNormalization(), "residual12_conv"); // block13 graph .addLayer("block13_sepconv1_act", new ActivationLayer(Activation.RELU), "add11" ) .addLayer("block13_sepconv1", new SeparableConvolution2D.Builder(3,3).nOut(728).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), "block13_sepconv1_act") .addLayer("block13_sepconv1_bn", new BatchNormalization(), "block13_sepconv1") .addLayer("block13_sepconv2_act", new ActivationLayer(Activation.RELU), "block13_sepconv1_bn") .addLayer("block13_sepconv2", new SeparableConvolution2D.Builder(3,3).nOut(1024).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), "block13_sepconv2_act") .addLayer("block13_sepconv2_bn", new BatchNormalization(), "block13_sepconv2") .addLayer("block13_pool", new SubsamplingLayer.Builder(SubsamplingLayer.PoolingType.MAX).kernelSize(3,3).stride(2,2) .convolutionMode(ConvolutionMode.Same).build(), "block13_sepconv2_bn") .addVertex("add12", new ElementWiseVertex(ElementWiseVertex.Op.Add), "block13_pool", "residual12"); // block14 graph .addLayer("block14_sepconv1", new SeparableConvolution2D.Builder(3,3).nOut(1536).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), "add12") .addLayer("block14_sepconv1_bn", new BatchNormalization(), "block14_sepconv1") .addLayer("block14_sepconv1_act", new ActivationLayer(Activation.RELU), "block14_sepconv1_bn") .addLayer("block14_sepconv2", new SeparableConvolution2D.Builder(3,3).nOut(2048).hasBias(false) .convolutionMode(ConvolutionMode.Same).cudnnAlgoMode(cudnnAlgoMode).build(), "block14_sepconv1_act") .addLayer("block14_sepconv2_bn", new BatchNormalization(), "block14_sepconv2") .addLayer("block14_sepconv2_act", new ActivationLayer(Activation.RELU), "block14_sepconv2_bn") .addLayer("avg_pool", new GlobalPoolingLayer.Builder(PoolingType.AVG).build(), "block14_sepconv2_act") .addLayer("predictions", new OutputLayer.Builder(LossFunctions.LossFunction.MCXENT) .nOut(numClasses) .activation(Activation.SOFTMAX).build(), "avg_pool") .setOutputs("predictions") ; return graph; } @Override public ModelMetaData metaData() { return new ModelMetaData(new int[][] {inputShape}, 1, ZooType.CNN); } @Override public void setInputShape(int[][] inputShape) { this.inputShape = inputShape[0]; } }
package com.box.restclientv2.requests; import java.lang.ref.WeakReference; import java.net.URISyntaxException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpOptions; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import com.box.boxjavalibv2.exceptions.AuthFatalFailureException; import com.box.boxjavalibv2.interfaces.IBoxJSONParser; import com.box.boxjavalibv2.requests.requestobjects.BoxDefaultRequestObject; import com.box.restclientv2.RestMethod; import com.box.restclientv2.exceptions.BoxRestException; import com.box.restclientv2.httpclientsupport.HttpClientURIBuilder; import com.box.restclientv2.interfaces.IBoxConfig; import com.box.restclientv2.interfaces.IBoxRequest; import com.box.restclientv2.interfaces.IBoxRequestAuth; import com.box.restclientv2.interfaces.ICookie; /** * Default implementation for IBoxRequest interface. This implementaion utilizes HttpRequestBase as underlying http request. */ public class DefaultBoxRequest implements IBoxRequest { private static final String FIELDS = "fields"; private static final String DELIMITER = ","; /** Auth. */ private WeakReference<IBoxRequestAuth> mAuth; /** Config */ private final IBoxConfig mConfig; /** Http entity. */ private HttpEntity mEntity; /** Cookie. */ private ICookie mCookie; /** REST method. */ private final RestMethod mRestMethod; /** Endpoint uri. */ private final String uriPath; /** Query parameters. */ private final HashMap<String, String> queryParams = new HashMap<String, String>(); /** Headers. */ private final HashMap<String, String> headers = new HashMap<String, String>(); /** Raw request. */ private HttpRequestBase rawRequest; /** HttpParams. */ private final HttpParams httpParams = new BasicHttpParams(); /** Expected response code. */ private int expectedResponseCode = HttpStatus.SC_OK; /** * Constructor. * * @param config * config * @param parser * json parser * @param uriPath * e.g. /folders/93285/items * @param restMethod * REST method * @param requestObject * request object * @throws BoxRestException * exception */ public DefaultBoxRequest(final IBoxConfig config, final IBoxJSONParser parser, final String uriPath, final RestMethod restMethod, final BoxDefaultRequestObject requestObject) throws BoxRestException { this.mConfig = config; this.mRestMethod = restMethod; this.uriPath = uriPath; getHeaders().put("User-Agent", getConfig().getUserAgent()); if (requestObject != null) { requestObject.setJSONParser(parser); setEntity(requestObject.getEntity()); setRequestFields(requestObject.getFields()); getQueryParams().putAll(requestObject.getQueryParams()); getHeaders().putAll(requestObject.getHeaders()); } } @Override public int getExpectedResponseCode() { return expectedResponseCode; } /** * Set the expected returned http response status code. * * @param code * code */ protected void setExpectedResponseCode(final int code) { this.expectedResponseCode = code; } @Override public HttpParams getHttpParams() { return httpParams; } @Override public IBoxRequestAuth getAuth() { return mAuth != null ? mAuth.get() : null; } @Override public ICookie getCookie() { return mCookie; } @Override public HttpEntity getRequestEntity() { return mEntity; } @Override public RestMethod getRestMethod() { return mRestMethod; } /** * Get raw request underlying this DefaultBoxRequest. Note this object is not constructed until prepareRequest method is called. * * @return raw request. */ public HttpRequestBase getRawRequest() { return rawRequest; } @Override public void setAuth(final IBoxRequestAuth auth) { this.mAuth = new WeakReference<IBoxRequestAuth>(auth); } @Override public void setCookie(final ICookie cookie) { this.mCookie = cookie; } /** * Set entity for the request. * * @param entity * entity. */ public void setEntity(final HttpEntity entity) { this.mEntity = entity; } @Override public void addQueryParam(final String name, final String value) { queryParams.put(name, value); } @Override public void addHeader(final String name, final String value) { headers.put(name, value); } /** * Set If-Match header. * * @param ifMatch * the If-Match header value */ public void setIfMatch(final String ifMatch) { addHeader("If-Match", ifMatch); } /** * Set fields on the request. By default, each box object has a complete and a mini format. The complete format is returned when you request a specific * object. The mini is returned when the object is part of a collection of items. In either case, you can set the fields here to specify which specific * fields you'd like returned. They can be any fields that are a part of the complete object for that particular type. * * @param fields * fields */ public void setRequestFields(final List<String> fields) { StringBuilder sbr = new StringBuilder(); if (fields != null && !fields.isEmpty()) { int size = fields.size(); for (int i = 0; i < size - 1; i++) { sbr.append(fields.get(i)).append(DELIMITER); } sbr.append(fields.get(size - 1)); addQueryParam(FIELDS, sbr.toString()); } } /** * Get the headers. * * @return headers */ public Map<String, String> getHeaders() { return headers; } /** * Add http param. * * @param name * name * @param value * value */ public void addHttpParam(final String name, final String value) { httpParams.setParameter(name, value); } /** * Get query parameters. * * @return query parameters */ public Map<String, String> getQueryParams() { return queryParams; } @Override public HttpRequestBase prepareRequest() throws BoxRestException, AuthFatalFailureException { rawRequest = constructHttpUriRequest(); HttpClientURIBuilder ub; try { ub = new HttpClientURIBuilder(); ub.setHost(getAuthority()); ub.setScheme(getScheme()); ub.setPath(getApiUrlPath().concat(uriPath).replaceAll("/{2,}", "/")); for (Map.Entry<String, String> entry : getQueryParams().entrySet()) { ub.addParameter(entry.getKey(), StringUtils.defaultIfEmpty(entry.getValue(), "")); } rawRequest.setURI(ub.build()); } catch (URISyntaxException e) { throw new BoxRestException("URISyntaxException:" + e.getMessage()); } if (getAuth() != null) { getAuth().setAuth(this); } if (getCookie() != null) { getCookie().setCookie(this); } if (getRequestEntity() != null && rawRequest instanceof HttpEntityEnclosingRequestBase) { ((HttpEntityEnclosingRequestBase) rawRequest).setEntity(getRequestEntity()); } for (Map.Entry<String, String> entry : getHeaders().entrySet()) { rawRequest.addHeader(entry.getKey(), entry.getValue()); } rawRequest.setParams(getHttpParams()); return rawRequest; } public IBoxConfig getConfig() { return mConfig; } @Override public String getScheme() { return mConfig.getApiUrlScheme(); } @Override public String getAuthority() { return mConfig.getApiUrlAuthority(); } @Override public String getApiUrlPath() { return mConfig.getApiUrlPath(); } /** * Construct raw request. Currently only support GET/PUT/POST/DELETE. * * @return raw request * @throws BoxRestException * exception */ HttpRequestBase constructHttpUriRequest() throws BoxRestException { switch (getRestMethod()) { case GET: return new HttpGet(); case PUT: return new HttpPut(); case POST: return new HttpPost(); case DELETE: return new HttpDelete(); case OPTIONS: return new HttpOptions(); default: throw new BoxRestException("Method Not Implemented"); } } }
/* * 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.streams.integration; import kafka.log.LogConfig; import kafka.utils.MockTime; import kafka.zk.AdminZkClient; import kafka.zk.KafkaZkClient; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.common.serialization.StringSerializer; import org.apache.kafka.common.utils.Time; import org.apache.kafka.streams.KafkaStreams; import org.apache.kafka.streams.StreamsBuilder; import org.apache.kafka.streams.StreamsConfig; import org.apache.kafka.streams.integration.utils.EmbeddedKafkaCluster; import org.apache.kafka.streams.integration.utils.IntegrationTestUtils; import org.apache.kafka.streams.kstream.KStream; import org.apache.kafka.streams.kstream.Materialized; import org.apache.kafka.streams.kstream.TimeWindows; import org.apache.kafka.streams.kstream.ValueMapper; import org.apache.kafka.streams.processor.internals.ProcessorStateManager; import org.apache.kafka.streams.state.KeyValueStore; import org.apache.kafka.streams.state.WindowStore; import org.apache.kafka.test.IntegrationTest; import org.apache.kafka.test.MockMapper; import org.apache.kafka.test.TestUtils; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import scala.collection.JavaConverters; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit; import static org.apache.kafka.streams.integration.utils.IntegrationTestUtils.waitForCompletion; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Tests related to internal topics in streams */ @Category({IntegrationTest.class}) public class InternalTopicIntegrationTest { @ClassRule public static final EmbeddedKafkaCluster CLUSTER = new EmbeddedKafkaCluster(1); private static final String APP_ID = "internal-topics-integration-test"; private static final String DEFAULT_INPUT_TOPIC = "inputTopic"; private static final int DEFAULT_ZK_SESSION_TIMEOUT_MS = 10 * 1000; private static final int DEFAULT_ZK_CONNECTION_TIMEOUT_MS = 8 * 1000; private final MockTime mockTime = CLUSTER.time; private Properties streamsProp; @BeforeClass public static void startKafkaCluster() throws InterruptedException { CLUSTER.createTopics(DEFAULT_INPUT_TOPIC); } @Before public void before() { streamsProp = new Properties(); streamsProp.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, CLUSTER.bootstrapServers()); streamsProp.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); streamsProp.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); streamsProp.put(StreamsConfig.STATE_DIR_CONFIG, TestUtils.tempDirectory().getPath()); streamsProp.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); streamsProp.put(IntegrationTestUtils.INTERNAL_LEAVE_GROUP_ON_CLOSE, true); streamsProp.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 100); streamsProp.put(StreamsConfig.CACHE_MAX_BYTES_BUFFERING_CONFIG, 0); } @After public void after() throws IOException { // Remove any state from previous test runs IntegrationTestUtils.purgeLocalStreamsState(streamsProp); } private void produceData(final List<String> inputValues) throws Exception { final Properties producerProp = new Properties(); producerProp.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, CLUSTER.bootstrapServers()); producerProp.put(ProducerConfig.ACKS_CONFIG, "all"); producerProp.put(ProducerConfig.RETRIES_CONFIG, 0); producerProp.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); producerProp.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class); IntegrationTestUtils.produceValuesSynchronously(DEFAULT_INPUT_TOPIC, inputValues, producerProp, mockTime); } private Properties getTopicProperties(final String changelog) { try (KafkaZkClient kafkaZkClient = KafkaZkClient.apply(CLUSTER.zKConnectString(), false, DEFAULT_ZK_SESSION_TIMEOUT_MS, DEFAULT_ZK_CONNECTION_TIMEOUT_MS, Integer.MAX_VALUE, Time.SYSTEM, "testMetricGroup", "testMetricType")) { final AdminZkClient adminZkClient = new AdminZkClient(kafkaZkClient); final Map<String, Properties> topicConfigs = JavaConverters.mapAsJavaMapConverter(adminZkClient.getAllTopicConfigs()).asJava(); for (Map.Entry<String, Properties> topicConfig : topicConfigs.entrySet()) { if (topicConfig.getKey().equals(changelog)) { return topicConfig.getValue(); } } return new Properties(); } } @Test public void shouldCompactTopicsForKeyValueStoreChangelogs() throws Exception { final String appID = APP_ID + "-compact"; streamsProp.put(StreamsConfig.APPLICATION_ID_CONFIG, appID); // // Step 1: Configure and start a simple word count topology // final StreamsBuilder builder = new StreamsBuilder(); final KStream<String, String> textLines = builder.stream(DEFAULT_INPUT_TOPIC); textLines.flatMapValues(new ValueMapper<String, Iterable<String>>() { @Override public Iterable<String> apply(final String value) { return Arrays.asList(value.toLowerCase(Locale.getDefault()).split("\\W+")); } }) .groupBy(MockMapper.<String, String>selectValueMapper()) .count(Materialized.<String, Long, KeyValueStore<org.apache.kafka.common.utils.Bytes, byte[]>>as("Counts")); final KafkaStreams streams = new KafkaStreams(builder.build(), streamsProp); streams.start(); // // Step 2: Produce some input data to the input topic. // produceData(Arrays.asList("hello", "world", "world", "hello world")); // // Step 3: Verify the state changelog topics are compact // waitForCompletion(streams, 2, 5000); streams.close(); final Properties changelogProps = getTopicProperties(ProcessorStateManager.storeChangelogTopic(appID, "Counts")); assertEquals(LogConfig.Compact(), changelogProps.getProperty(LogConfig.CleanupPolicyProp())); final Properties repartitionProps = getTopicProperties(appID + "-Counts-repartition"); assertEquals(LogConfig.Delete(), repartitionProps.getProperty(LogConfig.CleanupPolicyProp())); assertEquals(5, repartitionProps.size()); } @Test public void shouldCompactAndDeleteTopicsForWindowStoreChangelogs() throws Exception { final String appID = APP_ID + "-compact-delete"; streamsProp.put(StreamsConfig.APPLICATION_ID_CONFIG, appID); // // Step 1: Configure and start a simple word count topology // StreamsBuilder builder = new StreamsBuilder(); KStream<String, String> textLines = builder.stream(DEFAULT_INPUT_TOPIC); final int durationMs = 2000; textLines.flatMapValues(new ValueMapper<String, Iterable<String>>() { @Override public Iterable<String> apply(final String value) { return Arrays.asList(value.toLowerCase(Locale.getDefault()).split("\\W+")); } }) .groupBy(MockMapper.<String, String>selectValueMapper()) .windowedBy(TimeWindows.of(1000).until(2000)) .count(Materialized.<String, Long, WindowStore<org.apache.kafka.common.utils.Bytes, byte[]>>as("CountWindows")); KafkaStreams streams = new KafkaStreams(builder.build(), streamsProp); streams.start(); // // Step 2: Produce some input data to the input topic. // produceData(Arrays.asList("hello", "world", "world", "hello world")); // // Step 3: Verify the state changelog topics are compact // waitForCompletion(streams, 2, 5000); streams.close(); final Properties properties = getTopicProperties(ProcessorStateManager.storeChangelogTopic(appID, "CountWindows")); final List<String> policies = Arrays.asList(properties.getProperty(LogConfig.CleanupPolicyProp()).split(",")); assertEquals(2, policies.size()); assertTrue(policies.contains(LogConfig.Compact())); assertTrue(policies.contains(LogConfig.Delete())); // retention should be 1 day + the window duration final long retention = TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS) + durationMs; assertEquals(retention, Long.parseLong(properties.getProperty(LogConfig.RetentionMsProp()))); final Properties repartitionProps = getTopicProperties(appID + "-CountWindows-repartition"); assertEquals(LogConfig.Delete(), repartitionProps.getProperty(LogConfig.CleanupPolicyProp())); assertEquals(5, repartitionProps.size()); } }
/* * 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.testing.compile; import static com.google.common.base.Preconditions.checkArgument; import static javax.tools.JavaFileObject.Kind.CLASS; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.ByteSource; import com.google.common.truth.FailureStrategy; import com.google.common.truth.Subject; import com.google.testing.compile.Compilation.Result; import com.sun.source.tree.CompilationUnitTree; import java.io.IOException; import java.util.Arrays; import java.util.Map; import java.util.Set; import javax.annotation.processing.Processor; import javax.tools.Diagnostic; import javax.tools.Diagnostic.Kind; import javax.tools.FileObject; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; /** * A <a href="https://github.com/truth0/truth">Truth</a> {@link Subject} that evaluates the result * of a {@code javac} compilation. See {@link com.google.testing.compile} for usage examples * * @author Gregory Kick */ @SuppressWarnings("restriction") // Sun APIs usage intended public final class JavaSourcesSubject extends Subject<JavaSourcesSubject, Iterable<? extends JavaFileObject>> implements CompileTester, ProcessedCompileTesterFactory { private final Set<String> options = Sets.newHashSet(); JavaSourcesSubject(FailureStrategy failureStrategy, Iterable<? extends JavaFileObject> subject) { super(failureStrategy, subject); } @Override public ProcessedCompileTesterFactory withCompilerOptions(Iterable<String> options) { Iterables.addAll(this.options, options); return this; } @Override public ProcessedCompileTesterFactory withCompilerOptions(String... options) { this.options.addAll(Arrays.asList(options)); return this; } @Override public CompileTester processedWith(Processor first, Processor... rest) { return processedWith(Lists.asList(first, rest)); } @Override public CompileTester processedWith(Iterable<? extends Processor> processors) { return new CompilationClause(processors); } @Override public void parsesAs(JavaFileObject first, JavaFileObject... rest) { new CompilationClause().parsesAs(first, rest); } @Override public SuccessfulCompilationClause compilesWithoutError() { return new CompilationClause().compilesWithoutError(); } @Override public UnsuccessfulCompilationClause failsToCompile() { return new CompilationClause().failsToCompile(); } /** The clause in the fluent API for testing compilations. */ private final class CompilationClause implements CompileTester { private final ImmutableSet<Processor> processors; private CompilationClause() { this(ImmutableSet.<Processor>of()); } private CompilationClause(Iterable<? extends Processor> processors) { this.processors = ImmutableSet.copyOf(processors); } /** Returns a {@code String} report describing the contents of a given generated file. */ private String reportFileGenerated(JavaFileObject generatedFile) { try { StringBuilder entry = new StringBuilder().append(String.format("\n%s:\n", generatedFile.toUri().getPath())); if (generatedFile.getKind().equals(CLASS)) { entry.append(String.format("[generated class file (%s bytes)]", JavaFileObjects.asByteSource(generatedFile).size())); } else { entry.append(generatedFile.getCharContent(true)); } return entry.append("\n").toString(); } catch (IOException e) { throw new IllegalStateException("Couldn't read from JavaFileObject when it was " + "already in memory.", e); } } /** * Returns a {@code String} report describing what files were generated in the given * {@link Compilation.Result} */ private String reportFilesGenerated(Compilation.Result result) { FluentIterable<JavaFileObject> generatedFiles = FluentIterable.from(result.generatedSources()); StringBuilder message = new StringBuilder("\n\n"); if (generatedFiles.isEmpty()) { return message.append("(No files were generated.)\n").toString(); } else { message.append("Generated Files\n") .append("===============\n"); for (JavaFileObject generatedFile : generatedFiles) { message.append(reportFileGenerated(generatedFile)); } return message.toString(); } } @Override public void parsesAs(JavaFileObject first, JavaFileObject... rest) { Compilation.ParseResult actualResult = Compilation.parse(getSubject()); ImmutableList<Diagnostic<? extends JavaFileObject>> errors = actualResult.diagnosticsByKind().get(Kind.ERROR); if (!errors.isEmpty()) { StringBuilder message = new StringBuilder("Parsing produced the following errors:\n"); for (Diagnostic<? extends JavaFileObject> error : errors) { message.append('\n'); message.append(error); } failureStrategy.fail(message.toString()); } final Compilation.ParseResult expectedResult = Compilation.parse(Lists.asList(first, rest)); final FluentIterable<? extends CompilationUnitTree> actualTrees = FluentIterable.from( actualResult.compilationUnits()); final FluentIterable<? extends CompilationUnitTree> expectedTrees = FluentIterable.from( expectedResult.compilationUnits()); Function<? super CompilationUnitTree, ImmutableSet<String>> getTypesFunction = new Function<CompilationUnitTree, ImmutableSet<String>>() { @Override public ImmutableSet<String> apply(CompilationUnitTree compilationUnit) { return TypeEnumerator.getTopLevelTypes(compilationUnit); } }; final ImmutableMap<? extends CompilationUnitTree, ImmutableSet<String>> expectedTreeTypes = Maps.toMap(expectedTrees, getTypesFunction); final ImmutableMap<? extends CompilationUnitTree, ImmutableSet<String>> actualTreeTypes = Maps.toMap(actualTrees, getTypesFunction); final ImmutableMap<? extends CompilationUnitTree, Optional<? extends CompilationUnitTree>> matchedTrees = Maps.toMap(expectedTrees, new Function<CompilationUnitTree, Optional<? extends CompilationUnitTree>>() { @Override public Optional<? extends CompilationUnitTree> apply( final CompilationUnitTree expectedTree) { return Iterables.tryFind(actualTrees, new Predicate<CompilationUnitTree>() { @Override public boolean apply(CompilationUnitTree actualTree) { return expectedTreeTypes.get(expectedTree).equals( actualTreeTypes.get(actualTree)); } }); } }); for (Map.Entry<? extends CompilationUnitTree, Optional<? extends CompilationUnitTree>> matchedTreePair : matchedTrees.entrySet()) { final CompilationUnitTree expectedTree = matchedTreePair.getKey(); if (!matchedTreePair.getValue().isPresent()) { failNoCandidates(expectedTreeTypes.get(expectedTree), expectedTree, actualTreeTypes, actualTrees); } else { CompilationUnitTree actualTree = matchedTreePair.getValue().get(); TreeDifference treeDifference = TreeDiffer.diffCompilationUnits(expectedTree, actualTree); if (!treeDifference.isEmpty()) { String diffReport = treeDifference.getDiffReport( new TreeContext(expectedTree, expectedResult.trees()), new TreeContext(actualTree, actualResult.trees())); failWithCandidate(expectedTree.getSourceFile(), actualTree.getSourceFile(), diffReport); } } } } /** Called when the {@code generatesSources()} verb fails with no diff candidates. */ private void failNoCandidates(ImmutableSet<String> expectedTypes, CompilationUnitTree expectedTree, final ImmutableMap<? extends CompilationUnitTree, ImmutableSet<String>> actualTypes, FluentIterable<? extends CompilationUnitTree> actualTrees) { String generatedTypesReport = Joiner.on('\n').join( actualTrees.transform(new Function<CompilationUnitTree, String>() { @Override public String apply(CompilationUnitTree generated) { return String.format("- %s in <%s>", actualTypes.get(generated), generated.getSourceFile().toUri().getPath()); } }) .toList()); failureStrategy.fail(Joiner.on('\n').join( "", "An expected source declared one or more top-level types that were not present.", "", String.format("Expected top-level types: <%s>", expectedTypes), String.format("Declared by expected file: <%s>", expectedTree.getSourceFile().toUri().getPath()), "", "The top-level types that were present are as follows: ", "", generatedTypesReport, "")); } /** Called when the {@code generatesSources()} verb fails with a diff candidate. */ private void failWithCandidate(JavaFileObject expectedSource, JavaFileObject actualSource, String diffReport) { try { failureStrategy.fail(Joiner.on('\n').join( "", "Source declared the same top-level types of an expected source, but", "didn't match exactly.", "", String.format("Expected file: <%s>", expectedSource.toUri().getPath()), String.format("Actual file: <%s>", actualSource.toUri().getPath()), "", "Diffs:", "======", "", diffReport, "", "Expected Source: ", "================", "", expectedSource.getCharContent(false).toString(), "", "Actual Source:", "=================", "", actualSource.getCharContent(false).toString())); } catch (IOException e) { throw new IllegalStateException("Couldn't read from JavaFileObject when it was already " + "in memory.", e); } } @Override public SuccessfulCompilationClause compilesWithoutError() { Compilation.Result result = Compilation.compile(processors, ImmutableSet.copyOf(options), getSubject()); if (!result.successful()) { ImmutableList<Diagnostic<? extends JavaFileObject>> errors = result.diagnosticsByKind().get(Kind.ERROR); StringBuilder message = new StringBuilder("Compilation produced the following errors:\n"); for (Diagnostic<? extends JavaFileObject> error : errors) { message.append('\n'); message.append(error); } message.append('\n'); message.append(reportFilesGenerated(result)); failureStrategy.fail(message.toString()); } return new SuccessfulCompilationBuilder(result); } @Override public UnsuccessfulCompilationClause failsToCompile() { Result result = Compilation.compile(processors, ImmutableSet.copyOf(options), getSubject()); if (result.successful()) { String message = Joiner.on('\n').join( "Compilation was expected to fail, but contained no errors.", "", reportFilesGenerated(result)); failureStrategy.fail(message); } return new UnsuccessfulCompilationBuilder(result); } } /** * A helper method for {@link SingleSourceAdapter} to ensure that the inner class is created * correctly. */ private CompilationClause newCompilationClause(Iterable<? extends Processor> processors) { return new CompilationClause(processors); } private final class UnsuccessfulCompilationBuilder implements UnsuccessfulCompilationClause { private final Compilation.Result result; UnsuccessfulCompilationBuilder(Compilation.Result result) { checkArgument(!result.successful()); this.result = result; } @Override public FileClause withErrorContaining(final String messageFragment) { FluentIterable<Diagnostic<? extends JavaFileObject>> diagnostics = FluentIterable.from(result.diagnosticsByKind().get(Kind.ERROR)); final FluentIterable<Diagnostic<? extends JavaFileObject>> diagnosticsWithMessage = diagnostics.filter(new Predicate<Diagnostic<?>>() { @Override public boolean apply(Diagnostic<?> input) { return input.getMessage(null).contains(messageFragment); } }); if (diagnosticsWithMessage.isEmpty()) { failureStrategy.fail(String.format( "Expected an error containing \"%s\", but only found %s", messageFragment, diagnostics.transform( new Function<Diagnostic<?>, String>() { @Override public String apply(Diagnostic<?> input) { return "\"" + input.getMessage(null) + "\""; } }))); } return new FileClause() { @Override public UnsuccessfulCompilationClause and() { return UnsuccessfulCompilationBuilder.this; } @Override public LineClause in(final JavaFileObject file) { final FluentIterable<Diagnostic<? extends JavaFileObject>> diagnosticsInFile = diagnosticsWithMessage.filter(new Predicate<Diagnostic<? extends FileObject>>() { @Override public boolean apply(Diagnostic<? extends FileObject> input) { return ((input.getSource() != null) && file.toUri().getPath().equals(input.getSource().toUri().getPath())); } }); if (diagnosticsInFile.isEmpty()) { failureStrategy.fail(String.format( "Expected an error in %s, but only found errors in %s", file.getName(), diagnosticsWithMessage.transform( new Function<Diagnostic<? extends FileObject>, String>() { @Override public String apply(Diagnostic<? extends FileObject> input) { return (input.getSource() != null) ? input.getSource().getName() : "(no associated file)"; } }) .toSet())); } return new LineClause() { @Override public UnsuccessfulCompilationClause and() { return UnsuccessfulCompilationBuilder.this; } @Override public ColumnClause onLine(final long lineNumber) { final FluentIterable<Diagnostic<? extends JavaFileObject>> diagnosticsOnLine = diagnosticsWithMessage.filter(new Predicate<Diagnostic<?>>() { @Override public boolean apply(Diagnostic<?> input) { return lineNumber == input.getLineNumber(); } }); if (diagnosticsOnLine.isEmpty()) { failureStrategy.fail(String.format( "Expected an error on line %d of %s, but only found errors on line(s) %s", lineNumber, file.getName(), diagnosticsInFile.transform( new Function<Diagnostic<?>, String>() { @Override public String apply(Diagnostic<?> input) { long errLine = input.getLineNumber(); return (errLine != Diagnostic.NOPOS) ? errLine + "" : "(no associated position)"; } }) .toSet())); } return new ColumnClause() { @Override public UnsuccessfulCompilationClause and() { return UnsuccessfulCompilationBuilder.this; } @Override public ChainingClause<UnsuccessfulCompilationClause> atColumn( final long columnNumber) { FluentIterable<Diagnostic<? extends JavaFileObject>> diagnosticsAtColumn = diagnosticsOnLine.filter(new Predicate<Diagnostic<?>>() { @Override public boolean apply(Diagnostic<?> input) { return columnNumber == input.getColumnNumber(); } }); if (diagnosticsAtColumn.isEmpty()) { failureStrategy.fail(String.format( "Expected an error at %d:%d of %s, but only found errors at column(s) %s", lineNumber, columnNumber, file.getName(), diagnosticsOnLine.transform( new Function<Diagnostic<?>, String>() { @Override public String apply(Diagnostic<?> input) { long errCol = input.getColumnNumber(); return (errCol != Diagnostic.NOPOS) ? errCol + "" : "(no associated position)"; } }) .toSet())); } return new ChainingClause<UnsuccessfulCompilationClause>() { @Override public UnsuccessfulCompilationClause and() { return UnsuccessfulCompilationBuilder.this; } }; } }; } }; } }; } } private final class SuccessfulCompilationBuilder implements SuccessfulCompilationClause, GeneratedPredicateClause { private final Compilation.Result result; SuccessfulCompilationBuilder(Compilation.Result result) { checkArgument(result.successful()); this.result = result; } @Override public GeneratedPredicateClause and() { return this; } @Override public SuccessfulCompilationClause generatesSources(JavaFileObject first, JavaFileObject... rest) { new JavaSourcesSubject(failureStrategy, result.generatedSources()) .parsesAs(first, rest); return this; } @Override public SuccessfulCompilationClause generatesFiles(JavaFileObject first, JavaFileObject... rest) { for (JavaFileObject expected : Lists.asList(first, rest)) { if (!wasGenerated(result, expected)) { failureStrategy.fail("Did not find a generated file corresponding to " + expected.getName()); } } return this; } boolean wasGenerated(Compilation.Result result, JavaFileObject expected) { ByteSource expectedByteSource = JavaFileObjects.asByteSource(expected); for (JavaFileObject generated : result.generatedFilesByKind().get(expected.getKind())) { try { ByteSource generatedByteSource = JavaFileObjects.asByteSource(generated); if (expectedByteSource.contentEquals(generatedByteSource)) { return true; } } catch (IOException e) { throw new RuntimeException(e); } } return false; } @Override public SuccessfulFileClause generatesFileNamed( JavaFileManager.Location location, String packageName, String relativeName) { // TODO(gak): Validate that these inputs aren't null, location is an output location, and // packageName is a valid package name. // We're relying on the implementation of location.getName() to be equivalent to the path of // the location. String expectedFilename = new StringBuilder(location.getName()).append('/') .append(packageName.replace('.', '/')).append('/').append(relativeName).toString(); for (JavaFileObject generated : result.generatedFilesByKind().values()) { if (generated.toUri().getPath().endsWith(expectedFilename)) { return new SuccessfulFileBuilder(this, generated.toUri().getPath(), JavaFileObjects.asByteSource(generated)); } } StringBuilder encounteredFiles = new StringBuilder(); for (JavaFileObject generated : result.generatedFilesByKind().values()) { if (generated.toUri().getPath().contains(location.getName())) { encounteredFiles.append(" ").append(generated.toUri().getPath()).append('\n'); } } failureStrategy.fail("Did not find a generated file corresponding to " + relativeName + " in package " + packageName + "; Found: " + encounteredFiles.toString()); return new SuccessfulFileBuilder(this, null, null); } } private final class SuccessfulFileBuilder implements SuccessfulFileClause { private final SuccessfulCompilationBuilder compilationClause; private final String generatedFilePath; private final ByteSource generatedByteSource; SuccessfulFileBuilder(SuccessfulCompilationBuilder compilationClause, String generatedFilePath, ByteSource generatedByteSource) { this.compilationClause = compilationClause; this.generatedFilePath = generatedFilePath; this.generatedByteSource = generatedByteSource; } @Override public GeneratedPredicateClause and() { return compilationClause; } @Override public SuccessfulFileClause withContents(ByteSource expectedByteSource) { try { if (!expectedByteSource.contentEquals(generatedByteSource)) { failureStrategy.fail("The contents in " + generatedFilePath + " did not match the expected contents"); } } catch (IOException e) { throw new RuntimeException(e); } return this; } } public static final class SingleSourceAdapter extends Subject<SingleSourceAdapter, JavaFileObject> implements CompileTester, ProcessedCompileTesterFactory { private final JavaSourcesSubject delegate; SingleSourceAdapter(FailureStrategy failureStrategy, JavaFileObject subject) { super(failureStrategy, subject); this.delegate = new JavaSourcesSubject(failureStrategy, ImmutableList.of(subject)); } @Override public ProcessedCompileTesterFactory withCompilerOptions(Iterable<String> options) { return delegate.withCompilerOptions(options); } @Override public ProcessedCompileTesterFactory withCompilerOptions(String... options) { return delegate.withCompilerOptions(options); } @Override public CompileTester processedWith(Processor first, Processor... rest) { return delegate.newCompilationClause(Lists.asList(first, rest)); } @Override public CompileTester processedWith(Iterable<? extends Processor> processors) { return delegate.newCompilationClause(processors); } @Override public SuccessfulCompilationClause compilesWithoutError() { return delegate.compilesWithoutError(); } @Override public UnsuccessfulCompilationClause failsToCompile() { return delegate.failsToCompile(); } @Override public void parsesAs(JavaFileObject first, JavaFileObject... rest) { delegate.parsesAs(first, rest); } } }
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.annotations.id.sequences; import org.junit.Test; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.mapping.Column; import org.hibernate.test.annotations.id.generationmappings.DedicatedSequenceEntity1; import org.hibernate.test.annotations.id.generationmappings.DedicatedSequenceEntity2; import org.hibernate.test.annotations.id.sequences.entities.Ball; import org.hibernate.test.annotations.id.sequences.entities.BreakDance; import org.hibernate.test.annotations.id.sequences.entities.Computer; import org.hibernate.test.annotations.id.sequences.entities.Department; import org.hibernate.test.annotations.id.sequences.entities.Dog; import org.hibernate.test.annotations.id.sequences.entities.FirTree; import org.hibernate.test.annotations.id.sequences.entities.Footballer; import org.hibernate.test.annotations.id.sequences.entities.FootballerPk; import org.hibernate.test.annotations.id.sequences.entities.Furniture; import org.hibernate.test.annotations.id.sequences.entities.GoalKeeper; import org.hibernate.test.annotations.id.sequences.entities.Home; import org.hibernate.test.annotations.id.sequences.entities.Monkey; import org.hibernate.test.annotations.id.sequences.entities.Phone; import org.hibernate.test.annotations.id.sequences.entities.Shoe; import org.hibernate.test.annotations.id.sequences.entities.SoundSystem; import org.hibernate.test.annotations.id.sequences.entities.Store; import org.hibernate.test.annotations.id.sequences.entities.Tree; import org.hibernate.testing.DialectChecks; import org.hibernate.testing.RequiresDialectFeature; import org.hibernate.testing.TestForIssue; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; /** * @author Emmanuel Bernard * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @SuppressWarnings("unchecked") @RequiresDialectFeature(DialectChecks.SupportsSequences.class) public class IdTest extends BaseCoreFunctionalTestCase { @Test public void testGenericGenerator() throws Exception { Session s = openSession(); Transaction tx = s.beginTransaction(); SoundSystem system = new SoundSystem(); system.setBrand( "Genelec" ); system.setModel( "T234" ); Furniture fur = new Furniture(); s.persist( system ); s.persist( fur ); tx.commit(); s.close(); s = openSession(); tx = s.beginTransaction(); system = ( SoundSystem ) s.get( SoundSystem.class, system.getId() ); fur = ( Furniture ) s.get( Furniture.class, fur.getId() ); assertNotNull( system ); assertNotNull( fur ); s.delete( system ); s.delete( fur ); tx.commit(); s.close(); } @Test public void testGenericGenerators() throws Exception { // Ensures that GenericGenerator annotations wrapped inside a GenericGenerators holder are bound correctly Session s = openSession(); Transaction tx = s.beginTransaction(); Monkey monkey = new Monkey(); s.persist( monkey ); s.flush(); assertNotNull( monkey.getId() ); tx.rollback(); s.close(); } @Test public void testTableGenerator() throws Exception { Session s = openSession(); Transaction tx = s.beginTransaction(); Ball b = new Ball(); Dog d = new Dog(); Computer c = new Computer(); s.persist( b ); s.persist( d ); s.persist( c ); tx.commit(); s.close(); assertEquals( "table id not generated", new Integer( 1 ), b.getId() ); assertEquals( "generator should not be shared", new Integer( 1 ), d .getId() ); assertEquals( "default value should work", new Long( 1 ), c.getId() ); s = openSession(); tx = s.beginTransaction(); s.delete( s.get( Ball.class, new Integer( 1 ) ) ); s.delete( s.get( Dog.class, new Integer( 1 ) ) ); s.delete( s.get( Computer.class, new Long( 1 ) ) ); tx.commit(); s.close(); } @Test public void testSequenceGenerator() throws Exception { Session s = openSession(); Transaction tx = s.beginTransaction(); Shoe b = new Shoe(); s.persist( b ); tx.commit(); s.close(); assertNotNull( b.getId() ); s = openSession(); tx = s.beginTransaction(); s.delete( s.get( Shoe.class, b.getId() ) ); tx.commit(); s.close(); } @Test public void testClassLevelGenerator() throws Exception { Session s = openSession(); Transaction tx = s.beginTransaction(); Store b = new Store(); s.persist( b ); tx.commit(); s.close(); assertNotNull( b.getId() ); s = openSession(); tx = s.beginTransaction(); s.delete( s.get( Store.class, b.getId() ) ); tx.commit(); s.close(); } @Test public void testMethodLevelGenerator() throws Exception { Session s = openSession(); Transaction tx = s.beginTransaction(); Department b = new Department(); s.persist( b ); tx.commit(); s.close(); assertNotNull( b.getId() ); s = openSession(); tx = s.beginTransaction(); s.delete( s.get( Department.class, b.getId() ) ); tx.commit(); s.close(); } @Test public void testDefaultSequence() throws Exception { Session s; Transaction tx; s = openSession(); tx = s.beginTransaction(); Home h = new Home(); s.persist( h ); tx.commit(); s.close(); assertNotNull( h.getId() ); s = openSession(); tx = s.beginTransaction(); Home reloadedHome = ( Home ) s.get( Home.class, h.getId() ); assertEquals( h.getId(), reloadedHome.getId() ); s.delete( reloadedHome ); tx.commit(); s.close(); } @Test public void testParameterizedAuto() throws Exception { Session s; Transaction tx; s = openSession(); tx = s.beginTransaction(); Home h = new Home(); s.persist( h ); tx.commit(); s.close(); assertNotNull( h.getId() ); s = openSession(); tx = s.beginTransaction(); Home reloadedHome = ( Home ) s.get( Home.class, h.getId() ); assertEquals( h.getId(), reloadedHome.getId() ); s.delete( reloadedHome ); tx.commit(); s.close(); } @Test public void testIdInEmbeddableSuperclass() throws Exception { Session s; Transaction tx; s = openSession(); tx = s.beginTransaction(); FirTree chrismasTree = new FirTree(); s.persist( chrismasTree ); tx.commit(); s.clear(); tx = s.beginTransaction(); chrismasTree = ( FirTree ) s.get( FirTree.class, chrismasTree.getId() ); assertNotNull( chrismasTree ); s.delete( chrismasTree ); tx.commit(); s.close(); } @Test public void testIdClass() throws Exception { Session s; Transaction tx; s = openSession(); tx = s.beginTransaction(); Footballer fb = new Footballer( "David", "Beckam", "Arsenal" ); GoalKeeper keeper = new GoalKeeper( "Fabien", "Bartez", "OM" ); s.persist( fb ); s.persist( keeper ); tx.commit(); s.clear(); // lookup by id tx = s.beginTransaction(); FootballerPk fpk = new FootballerPk( "David", "Beckam" ); fb = ( Footballer ) s.get( Footballer.class, fpk ); FootballerPk fpk2 = new FootballerPk( "Fabien", "Bartez" ); keeper = ( GoalKeeper ) s.get( GoalKeeper.class, fpk2 ); assertNotNull( fb ); assertNotNull( keeper ); assertEquals( "Beckam", fb.getLastname() ); assertEquals( "Arsenal", fb.getClub() ); assertEquals( 1, s.createQuery( "from Footballer f where f.firstname = 'David'" ).list().size() ); tx.commit(); // reattach by merge tx = s.beginTransaction(); fb.setClub( "Bimbo FC" ); s.merge( fb ); tx.commit(); // reattach by saveOrUpdate tx = s.beginTransaction(); fb.setClub( "Bimbo FC SA" ); s.saveOrUpdate( fb ); tx.commit(); // clean up s.clear(); tx = s.beginTransaction(); fpk = new FootballerPk( "David", "Beckam" ); fb = ( Footballer ) s.get( Footballer.class, fpk ); assertEquals( "Bimbo FC SA", fb.getClub() ); s.delete( fb ); s.delete( keeper ); tx.commit(); s.close(); } @Test @TestForIssue(jiraKey = "HHH-6790") public void testSequencePerEntity() { Session session = openSession(); session.beginTransaction(); DedicatedSequenceEntity1 entity1 = new DedicatedSequenceEntity1(); DedicatedSequenceEntity2 entity2 = new DedicatedSequenceEntity2(); session.persist( entity1 ); session.persist( entity2 ); session.getTransaction().commit(); assertEquals( 1, entity1.getId().intValue() ); assertEquals( 1, entity2.getId().intValue() ); session.close(); } @Test public void testColumnDefinition() { Column idCol = ( Column ) configuration().getClassMapping( Ball.class.getName() ) .getIdentifierProperty().getValue().getColumnIterator().next(); assertEquals( "ball_id", idCol.getName() ); } @Test public void testLowAllocationSize() throws Exception { Session s; Transaction tx; s = openSession(); tx = s.beginTransaction(); int size = 4; BreakDance[] bds = new BreakDance[size]; for ( int i = 0; i < size; i++ ) { bds[i] = new BreakDance(); s.persist( bds[i] ); } s.flush(); for ( int i = 0; i < size; i++ ) { assertEquals( i + 1, bds[i].id.intValue() ); } tx.rollback(); s.close(); } @Override protected Class[] getAnnotatedClasses() { return new Class[] { Ball.class, Shoe.class, Store.class, Department.class, Dog.class, Computer.class, Home.class, Phone.class, Tree.class, FirTree.class, Footballer.class, SoundSystem.class, Furniture.class, GoalKeeper.class, BreakDance.class, Monkey.class, DedicatedSequenceEntity1.class, DedicatedSequenceEntity2.class }; } @Override protected String[] getAnnotatedPackages() { return new String[] { "org.hibernate.test.annotations", "org.hibernate.test.annotations.id", "org.hibernate.test.annotations.id.generationmappings" }; } @Override protected String[] getXmlFiles() { return new String[] { "org/hibernate/test/annotations/orm.xml" }; } }
/* * Druid - a distributed column store. * Copyright 2012 - 2015 Metamarkets Group 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 io.druid.segment.incremental; import com.carrotsearch.junitbenchmarks.AbstractBenchmark; import com.carrotsearch.junitbenchmarks.BenchmarkOptions; import com.carrotsearch.junitbenchmarks.Clock; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.metamx.common.guava.Sequences; import io.druid.data.input.InputRow; import io.druid.data.input.MapBasedInputRow; import io.druid.granularity.QueryGranularity; import io.druid.query.Druids; import io.druid.query.FinalizeResultsQueryRunner; import io.druid.query.QueryRunner; import io.druid.query.QueryRunnerFactory; import io.druid.query.QueryRunnerTestHelper; import io.druid.query.Result; import io.druid.query.aggregation.Aggregator; import io.druid.query.aggregation.AggregatorFactory; import io.druid.query.aggregation.CountAggregatorFactory; import io.druid.query.aggregation.DoubleSumAggregatorFactory; import io.druid.query.aggregation.LongSumAggregatorFactory; import io.druid.query.timeseries.TimeseriesQuery; import io.druid.query.timeseries.TimeseriesQueryEngine; import io.druid.query.timeseries.TimeseriesQueryQueryToolChest; import io.druid.query.timeseries.TimeseriesQueryRunnerFactory; import io.druid.query.timeseries.TimeseriesResultValue; import io.druid.segment.IncrementalIndexSegment; import io.druid.segment.Segment; import org.joda.time.Interval; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * Extending AbstractBenchmark means only runs if explicitly called */ @RunWith(Parameterized.class) public class OnheapIncrementalIndexBenchmark extends AbstractBenchmark { private static AggregatorFactory[] factories; static final int dimensionCount = 5; static { final ArrayList<AggregatorFactory> ingestAggregatorFactories = new ArrayList<>(dimensionCount + 1); ingestAggregatorFactories.add(new CountAggregatorFactory("rows")); for (int i = 0; i < dimensionCount; ++i) { ingestAggregatorFactories.add( new LongSumAggregatorFactory( String.format("sumResult%s", i), String.format("Dim_%s", i) ) ); ingestAggregatorFactories.add( new DoubleSumAggregatorFactory( String.format("doubleSumResult%s", i), String.format("Dim_%s", i) ) ); } factories = ingestAggregatorFactories.toArray(new AggregatorFactory[0]); } private static final class MapIncrementalIndex extends OnheapIncrementalIndex { private final AtomicInteger indexIncrement = new AtomicInteger(0); ConcurrentHashMap<Integer, Aggregator[]> indexedMap = new ConcurrentHashMap<Integer, Aggregator[]>(); public MapIncrementalIndex( long minTimestamp, QueryGranularity gran, AggregatorFactory[] metrics, int maxRowCount ) { super(minTimestamp, gran, metrics, maxRowCount); } @Override protected Aggregator[] concurrentGet(int offset) { // All get operations should be fine return indexedMap.get(offset); } @Override protected void concurrentSet(int offset, Aggregator[] value) { indexedMap.put(offset, value); } @Override protected Integer addToFacts( AggregatorFactory[] metrics, boolean deserializeComplexMetrics, InputRow row, AtomicInteger numEntries, TimeAndDims key, ThreadLocal<InputRow> in ) throws IndexSizeExceededException { final Integer priorIdex = getFacts().get(key); Aggregator[] aggs; if (null != priorIdex) { aggs = indexedMap.get(priorIdex); } else { aggs = new Aggregator[metrics.length]; for (int i = 0; i < metrics.length; i++) { final AggregatorFactory agg = metrics[i]; aggs[i] = agg.factorize( makeColumnSelectorFactory(agg, in, deserializeComplexMetrics) ); } Integer rowIndex; do { rowIndex = indexIncrement.incrementAndGet(); } while (null != indexedMap.putIfAbsent(rowIndex, aggs)); // Last ditch sanity checks if (numEntries.get() >= maxRowCount && !getFacts().containsKey(key)) { throw new IndexSizeExceededException("Maximum number of rows reached"); } final Integer prev = getFacts().putIfAbsent(key, rowIndex); if (null == prev) { numEntries.incrementAndGet(); } else { // We lost a race aggs = indexedMap.get(prev); // Free up the misfire indexedMap.remove(rowIndex); // This is expected to occur ~80% of the time in the worst scenarios } } in.set(row); for (Aggregator agg : aggs) { synchronized (agg) { agg.aggregate(); } } in.set(null); return numEntries.get(); } } @Parameterized.Parameters public static Collection<Object[]> getParameters() { return ImmutableList.<Object[]>of( new Object[]{OnheapIncrementalIndex.class}, new Object[]{MapIncrementalIndex.class} ); } private final Class<? extends OnheapIncrementalIndex> incrementalIndex; public OnheapIncrementalIndexBenchmark(Class<? extends OnheapIncrementalIndex> incrementalIndex) { this.incrementalIndex = incrementalIndex; } private static MapBasedInputRow getLongRow(long timestamp, int rowID, int dimensionCount) { List<String> dimensionList = new ArrayList<String>(dimensionCount); ImmutableMap.Builder<String, Object> builder = ImmutableMap.builder(); for (int i = 0; i < dimensionCount; i++) { String dimName = String.format("Dim_%d", i); dimensionList.add(dimName); builder.put(dimName, new Integer(rowID).longValue()); } return new MapBasedInputRow(timestamp, dimensionList, builder.build()); } @Ignore @Test @BenchmarkOptions(callgc = true, clock = Clock.REAL_TIME, warmupRounds = 10, benchmarkRounds = 20) public void testConcurrentAddRead() throws InterruptedException, ExecutionException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { final int taskCount = 30; final int concurrentThreads = 3; final int elementsPerThread = 1 << 15; final OnheapIncrementalIndex incrementalIndex = this.incrementalIndex.getConstructor( Long.TYPE, QueryGranularity.class, AggregatorFactory[].class, Integer.TYPE ).newInstance(0, QueryGranularity.NONE, factories, elementsPerThread * taskCount); final ArrayList<AggregatorFactory> queryAggregatorFactories = new ArrayList<>(dimensionCount + 1); queryAggregatorFactories.add(new CountAggregatorFactory("rows")); for (int i = 0; i < dimensionCount; ++i) { queryAggregatorFactories.add( new LongSumAggregatorFactory( String.format("sumResult%s", i), String.format("sumResult%s", i) ) ); queryAggregatorFactories.add( new DoubleSumAggregatorFactory( String.format("doubleSumResult%s", i), String.format("doubleSumResult%s", i) ) ); } final ListeningExecutorService indexExecutor = MoreExecutors.listeningDecorator( Executors.newFixedThreadPool( concurrentThreads, new ThreadFactoryBuilder() .setDaemon(false) .setNameFormat("index-executor-%d") .setPriority(Thread.MIN_PRIORITY) .build() ) ); final ListeningExecutorService queryExecutor = MoreExecutors.listeningDecorator( Executors.newFixedThreadPool( concurrentThreads, new ThreadFactoryBuilder() .setDaemon(false) .setNameFormat("query-executor-%d") .build() ) ); final long timestamp = System.currentTimeMillis(); final Interval queryInterval = new Interval("1900-01-01T00:00:00Z/2900-01-01T00:00:00Z"); final List<ListenableFuture<?>> indexFutures = new LinkedList<>(); final List<ListenableFuture<?>> queryFutures = new LinkedList<>(); final Segment incrementalIndexSegment = new IncrementalIndexSegment(incrementalIndex, null); final QueryRunnerFactory factory = new TimeseriesQueryRunnerFactory( new TimeseriesQueryQueryToolChest(QueryRunnerTestHelper.NoopIntervalChunkingQueryRunnerDecorator()), new TimeseriesQueryEngine(), QueryRunnerTestHelper.NOOP_QUERYWATCHER ); final AtomicInteger currentlyRunning = new AtomicInteger(0); final AtomicBoolean concurrentlyRan = new AtomicBoolean(false); final AtomicBoolean someoneRan = new AtomicBoolean(false); for (int j = 0; j < taskCount; j++) { indexFutures.add( indexExecutor.submit( new Runnable() { @Override public void run() { currentlyRunning.incrementAndGet(); try { for (int i = 0; i < elementsPerThread; i++) { incrementalIndex.add(getLongRow(timestamp + i, 1, dimensionCount)); } } catch (IndexSizeExceededException e) { throw Throwables.propagate(e); } currentlyRunning.decrementAndGet(); someoneRan.set(true); } } ) ); queryFutures.add( queryExecutor.submit( new Runnable() { @Override public void run() { QueryRunner<Result<TimeseriesResultValue>> runner = new FinalizeResultsQueryRunner<Result<TimeseriesResultValue>>( factory.createRunner(incrementalIndexSegment), factory.getToolchest() ); TimeseriesQuery query = Druids.newTimeseriesQueryBuilder() .dataSource("xxx") .granularity(QueryGranularity.ALL) .intervals(ImmutableList.of(queryInterval)) .aggregators(queryAggregatorFactories) .build(); Map<String, Object> context = new HashMap<String, Object>(); for (Result<TimeseriesResultValue> result : Sequences.toList( runner.run(query, context), new LinkedList<Result<TimeseriesResultValue>>() ) ) { if (someoneRan.get()) { Assert.assertTrue(result.getValue().getDoubleMetric("doubleSumResult0") > 0); } } if (currentlyRunning.get() > 0) { concurrentlyRan.set(true); } } } ) ); } List<ListenableFuture<?>> allFutures = new ArrayList<>(queryFutures.size() + indexFutures.size()); allFutures.addAll(queryFutures); allFutures.addAll(indexFutures); Futures.allAsList(allFutures).get(); //Assert.assertTrue("Did not hit concurrency, please try again", concurrentlyRan.get()); queryExecutor.shutdown(); indexExecutor.shutdown(); QueryRunner<Result<TimeseriesResultValue>> runner = new FinalizeResultsQueryRunner<Result<TimeseriesResultValue>>( factory.createRunner(incrementalIndexSegment), factory.getToolchest() ); TimeseriesQuery query = Druids.newTimeseriesQueryBuilder() .dataSource("xxx") .granularity(QueryGranularity.ALL) .intervals(ImmutableList.of(queryInterval)) .aggregators(queryAggregatorFactories) .build(); Map<String, Object> context = new HashMap<String, Object>(); List<Result<TimeseriesResultValue>> results = Sequences.toList( runner.run(query, context), new LinkedList<Result<TimeseriesResultValue>>() ); final int expectedVal = elementsPerThread * taskCount; for (Result<TimeseriesResultValue> result : results) { Assert.assertEquals(elementsPerThread, result.getValue().getLongMetric("rows").intValue()); for (int i = 0; i < dimensionCount; ++i) { Assert.assertEquals( String.format("Failed long sum on dimension %d", i), expectedVal, result.getValue().getLongMetric(String.format("sumResult%s", i)).intValue() ); Assert.assertEquals( String.format("Failed double sum on dimension %d", i), expectedVal, result.getValue().getDoubleMetric(String.format("doubleSumResult%s", i)).intValue() ); } } } }
public class PrivateNoArgsConstructor { private static class Base { private Base() { super(); } } public static @lombok.Data class PrivateNoArgsConstructorNotOnExtends extends Base { private final int a; public @java.lang.SuppressWarnings("all") int getA() { return this.a; } public @java.lang.Override @java.lang.SuppressWarnings("all") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof PrivateNoArgsConstructor.PrivateNoArgsConstructorNotOnExtends))) return false; final PrivateNoArgsConstructor.PrivateNoArgsConstructorNotOnExtends other = (PrivateNoArgsConstructor.PrivateNoArgsConstructorNotOnExtends) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((! super.equals(o))) return false; if ((this.getA() != other.getA())) return false; return true; } protected @java.lang.SuppressWarnings("all") boolean canEqual(final java.lang.Object other) { return (other instanceof PrivateNoArgsConstructor.PrivateNoArgsConstructorNotOnExtends); } public @java.lang.Override @java.lang.SuppressWarnings("all") int hashCode() { final int PRIME = 59; int result = super.hashCode(); result = ((result * PRIME) + this.getA()); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") java.lang.String toString() { return (("PrivateNoArgsConstructor.PrivateNoArgsConstructorNotOnExtends(a=" + this.getA()) + ")"); } public @java.lang.SuppressWarnings("all") PrivateNoArgsConstructorNotOnExtends(final int a) { super(); this.a = a; } } public static @lombok.Data class PrivateNoArgsConstructorOnExtendsObject extends Object { private final int b; public @java.lang.SuppressWarnings("all") int getB() { return this.b; } public @java.lang.Override @java.lang.SuppressWarnings("all") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof PrivateNoArgsConstructor.PrivateNoArgsConstructorOnExtendsObject))) return false; final PrivateNoArgsConstructor.PrivateNoArgsConstructorOnExtendsObject other = (PrivateNoArgsConstructor.PrivateNoArgsConstructorOnExtendsObject) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.getB() != other.getB())) return false; return true; } protected @java.lang.SuppressWarnings("all") boolean canEqual(final java.lang.Object other) { return (other instanceof PrivateNoArgsConstructor.PrivateNoArgsConstructorOnExtendsObject); } public @java.lang.Override @java.lang.SuppressWarnings("all") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getB()); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") java.lang.String toString() { return (("PrivateNoArgsConstructor.PrivateNoArgsConstructorOnExtendsObject(b=" + this.getB()) + ")"); } public @java.lang.SuppressWarnings("all") PrivateNoArgsConstructorOnExtendsObject(final int b) { super(); this.b = b; } private @java.lang.SuppressWarnings("all") PrivateNoArgsConstructorOnExtendsObject() { super(); this.b = 0; } } public static @lombok.NoArgsConstructor(force = true) @lombok.Data @lombok.RequiredArgsConstructor class PrivateNoArgsConstructorExplicitBefore { private final int c; public @java.lang.SuppressWarnings("all") PrivateNoArgsConstructorExplicitBefore() { super(); this.c = 0; } public @java.lang.SuppressWarnings("all") int getC() { return this.c; } public @java.lang.Override @java.lang.SuppressWarnings("all") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof PrivateNoArgsConstructor.PrivateNoArgsConstructorExplicitBefore))) return false; final PrivateNoArgsConstructor.PrivateNoArgsConstructorExplicitBefore other = (PrivateNoArgsConstructor.PrivateNoArgsConstructorExplicitBefore) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.getC() != other.getC())) return false; return true; } protected @java.lang.SuppressWarnings("all") boolean canEqual(final java.lang.Object other) { return (other instanceof PrivateNoArgsConstructor.PrivateNoArgsConstructorExplicitBefore); } public @java.lang.Override @java.lang.SuppressWarnings("all") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getC()); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") java.lang.String toString() { return (("PrivateNoArgsConstructor.PrivateNoArgsConstructorExplicitBefore(c=" + this.getC()) + ")"); } public @java.lang.SuppressWarnings("all") PrivateNoArgsConstructorExplicitBefore(final int c) { super(); this.c = c; } } public static @lombok.Data @lombok.NoArgsConstructor(force = true) @lombok.RequiredArgsConstructor class PrivateNoArgsConstructorExplicitAfter { private final int d; public @java.lang.SuppressWarnings("all") int getD() { return this.d; } public @java.lang.Override @java.lang.SuppressWarnings("all") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof PrivateNoArgsConstructor.PrivateNoArgsConstructorExplicitAfter))) return false; final PrivateNoArgsConstructor.PrivateNoArgsConstructorExplicitAfter other = (PrivateNoArgsConstructor.PrivateNoArgsConstructorExplicitAfter) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.getD() != other.getD())) return false; return true; } protected @java.lang.SuppressWarnings("all") boolean canEqual(final java.lang.Object other) { return (other instanceof PrivateNoArgsConstructor.PrivateNoArgsConstructorExplicitAfter); } public @java.lang.Override @java.lang.SuppressWarnings("all") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getD()); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") java.lang.String toString() { return (("PrivateNoArgsConstructor.PrivateNoArgsConstructorExplicitAfter(d=" + this.getD()) + ")"); } public @java.lang.SuppressWarnings("all") PrivateNoArgsConstructorExplicitAfter() { super(); this.d = 0; } public @java.lang.SuppressWarnings("all") PrivateNoArgsConstructorExplicitAfter(final int d) { super(); this.d = d; } } public static @lombok.Data @lombok.NoArgsConstructor(access = lombok.AccessLevel.NONE) @lombok.RequiredArgsConstructor class PrivateNoArgsConstructorExplicitNone { private final int e; public @java.lang.SuppressWarnings("all") int getE() { return this.e; } public @java.lang.Override @java.lang.SuppressWarnings("all") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof PrivateNoArgsConstructor.PrivateNoArgsConstructorExplicitNone))) return false; final PrivateNoArgsConstructor.PrivateNoArgsConstructorExplicitNone other = (PrivateNoArgsConstructor.PrivateNoArgsConstructorExplicitNone) o; if ((! other.canEqual((java.lang.Object) this))) return false; if ((this.getE() != other.getE())) return false; return true; } protected @java.lang.SuppressWarnings("all") boolean canEqual(final java.lang.Object other) { return (other instanceof PrivateNoArgsConstructor.PrivateNoArgsConstructorExplicitNone); } public @java.lang.Override @java.lang.SuppressWarnings("all") int hashCode() { final int PRIME = 59; int result = 1; result = ((result * PRIME) + this.getE()); return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") java.lang.String toString() { return (("PrivateNoArgsConstructor.PrivateNoArgsConstructorExplicitNone(e=" + this.getE()) + ")"); } public @java.lang.SuppressWarnings("all") PrivateNoArgsConstructorExplicitNone(final int e) { super(); this.e = e; } } public static @lombok.Data class PrivateNoArgsConstructorNoFields { public @java.lang.Override @java.lang.SuppressWarnings("all") boolean equals(final java.lang.Object o) { if ((o == this)) return true; if ((! (o instanceof PrivateNoArgsConstructor.PrivateNoArgsConstructorNoFields))) return false; final PrivateNoArgsConstructor.PrivateNoArgsConstructorNoFields other = (PrivateNoArgsConstructor.PrivateNoArgsConstructorNoFields) o; if ((! other.canEqual((java.lang.Object) this))) return false; return true; } protected @java.lang.SuppressWarnings("all") boolean canEqual(final java.lang.Object other) { return (other instanceof PrivateNoArgsConstructor.PrivateNoArgsConstructorNoFields); } public @java.lang.Override @java.lang.SuppressWarnings("all") int hashCode() { final int result = 1; return result; } public @java.lang.Override @java.lang.SuppressWarnings("all") java.lang.String toString() { return "PrivateNoArgsConstructor.PrivateNoArgsConstructorNoFields()"; } public @java.lang.SuppressWarnings("all") PrivateNoArgsConstructorNoFields() { super(); } } public PrivateNoArgsConstructor() { super(); } }
/****************************************************************************** * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ package org.allseen.timeservice.client; import java.lang.reflect.Method; import java.util.Collections; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.alljoyn.bus.BusAttachment; import org.alljoyn.bus.Status; import org.allseen.timeservice.ajinterfaces.TimeAuthority; import android.util.Log; /** * Singleton class that is responsible to receive {@link TimeAuthority#timeSync()} signals */ class TimeSyncHandler { private static final String TAG = "ajts" + TimeSyncHandler.class.getSimpleName(); /** * Self reference for the {@link TimeSyncHandler} singleton */ private static final TimeSyncHandler SELF = new TimeSyncHandler(); /** * The rule to be used in the {@link BusAttachment#addMatch(String)} */ private static final String MATCH_RULE = "interface='" + TimeAuthority.IFNAME + "',type='signal',sessionless='t'"; /** * {@link BusAttachment} */ private BusAttachment bus; /** * Clocks to be notified when Time Sync event arrives. * This Set internally uses {@link ConcurrentHashMap} that makes it thread safe. * @see ConcurrentHashMap * @see Collections#newSetFromMap(java.util.Map) */ private final Set<Clock> clocks; /** * Signal handler method */ private Method sigHandlerMethod; /** * Constructor */ private TimeSyncHandler() { // Creates thread safe set clocks = Collections.newSetFromMap(new ConcurrentHashMap<Clock, Boolean>()); try { sigHandlerMethod = this.getClass().getDeclaredMethod("timeSync"); } catch (NoSuchMethodException nse) { Log.e(TAG, "Not found TimeSync signal handler method", nse); } } /** * Returns {@link TimeSyncHandler} * @return {@link TimeSyncHandler} */ static TimeSyncHandler getInstance() { return SELF; } /** * Adds {@link Clock} event listener * @param bus * @param clock */ void registerClock(BusAttachment bus, Clock clock) { if ( bus == null ) { Log.e(TAG, "Failed to register Clock, BusAttachment is undefined"); return; } Log.i(TAG, "Registering to receive 'TimeSync' events from the Clock: '" + clock.getObjectPath() + "'"); if ( clocks.size() == 0 ) { registerSignalHandler(bus); } //Add the clock listener to the clocks list clocks.add(clock); } /** * Remove {@link Clock} event listener * @param clock */ void unregisterClock(Clock clock) { Log.i(TAG, "Stop receiving 'TimeSync' events from the Clock: '" + clock.getObjectPath() + "'"); //Remove the clock listener from the clocks list clocks.remove(clock); if ( clocks.size() == 0 ) { unregisterSignalHandler(); } } /** * Signal Handler * @see TimeAuthority#timeSync() */ public void timeSync() { if ( bus == null ) { Log.wtf(TAG, "Received TimeSync signal, but BusAttachment is undefined, returning"); return; } bus.enableConcurrentCallbacks(); String sender = bus.getMessageContext().sender; String objPath = bus.getMessageContext().objectPath; Log.d(TAG, "Received TimeSync signal from object: '" + objPath + "', sender: '" + sender + "', searching for a Clock"); notifyClock(objPath, sender); } /** * Find the Time Authority Clock by the given senderObjPath and senderName * @param senderObjPath * @param senderName */ private void notifyClock(String senderObjPath, String senderName) { Iterator<Clock> iterator = clocks.iterator(); while ( iterator.hasNext() ) { Clock clock = iterator.next(); if ( clock.getObjectPath().equals(senderObjPath) && clock.tsClient.getServerBusName().equals(senderName) ) { Log.i(TAG, "Received 'TimeSync' event from Clock: '" + senderObjPath + "', sender: '" + senderName + "', delegating to a listener"); clock.getTimeAuthorityHandler().handleTimeSync(clock); return; } } Log.d(TAG, "Not found any signal listener for the Clock: '" + senderObjPath + "', sender: '" + senderName + "'"); } /** * Register signal handler */ private synchronized void registerSignalHandler(BusAttachment bus) { Log.d(TAG, "Starting TimeSync signal handler"); this.bus = bus; if ( sigHandlerMethod == null ) { return; } String timeAuthorityIfaceLocalName = TimeAuthority.class.getName(); Status status = bus.registerSignalHandler(timeAuthorityIfaceLocalName, "timeSync", this, sigHandlerMethod); if ( status != Status.OK ) { Log.e(TAG, "Failed to call 'bus.registerSignalHandler()', Status: '" + status + "'"); return; } status = bus.addMatch(MATCH_RULE); if ( status != Status.OK ) { Log.e(TAG, "Failed to call bus.addMatch(" + MATCH_RULE + "), Status: '" + status + "'"); return; } } /** * Unregister signal handler * @param clock */ private synchronized void unregisterSignalHandler() { Log.d(TAG, "Stopping TimeSync signal handler"); bus.unregisterSignalHandler(this, sigHandlerMethod); Status status = bus.removeMatch(MATCH_RULE); if ( status == Status.OK ) { Log.d(TAG, "Succeeded to call bus.removeMatch(" + MATCH_RULE + "), Status: '" + status + "'"); } else { Log.e(TAG, "Failed to call bus.removeMatch(" + MATCH_RULE + "), Status: '" + status + "'"); } //Removing BusAttachment reference bus = null; } }
/* Copyright (C) 2013-2014 Computer Sciences Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Autogenerated by Thrift Compiler (0.9.1) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ package ezbake.query.intents.base; import org.apache.thrift.scheme.IScheme; import org.apache.thrift.scheme.SchemeFactory; import org.apache.thrift.scheme.StandardScheme; import org.apache.thrift.scheme.TupleScheme; import org.apache.thrift.protocol.TTupleProtocol; import org.apache.thrift.protocol.TProtocolException; import org.apache.thrift.EncodingUtils; import org.apache.thrift.TException; import org.apache.thrift.async.AsyncMethodCallback; import org.apache.thrift.server.AbstractNonblockingServer.*; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.EnumMap; import java.util.Set; import java.util.HashSet; import java.util.EnumSet; import java.util.Collections; import java.util.BitSet; import java.nio.ByteBuffer; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SecurityLabel implements org.apache.thrift.TBase<SecurityLabel, SecurityLabel._Fields>, java.io.Serializable, Cloneable, Comparable<SecurityLabel> { private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("SecurityLabel"); private static final org.apache.thrift.protocol.TField CLASSIFICATION_FIELD_DESC = new org.apache.thrift.protocol.TField("classification", org.apache.thrift.protocol.TType.STRUCT, (short)1); private static final org.apache.thrift.protocol.TField DISCOVERY_CLASSIFICATION_FIELD_DESC = new org.apache.thrift.protocol.TField("discoveryClassification", org.apache.thrift.protocol.TType.STRUCT, (short)2); private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>(); static { schemes.put(StandardScheme.class, new SecurityLabelStandardSchemeFactory()); schemes.put(TupleScheme.class, new SecurityLabelTupleSchemeFactory()); } public ezbake.base.thrift.Classification classification; // required public ezbake.base.thrift.Classification discoveryClassification; // optional /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */ public enum _Fields implements org.apache.thrift.TFieldIdEnum { CLASSIFICATION((short)1, "classification"), DISCOVERY_CLASSIFICATION((short)2, "discoveryClassification"); private static final Map<String, _Fields> byName = new HashMap<String, _Fields>(); static { for (_Fields field : EnumSet.allOf(_Fields.class)) { byName.put(field.getFieldName(), field); } } /** * Find the _Fields constant that matches fieldId, or null if its not found. */ public static _Fields findByThriftId(int fieldId) { switch(fieldId) { case 1: // CLASSIFICATION return CLASSIFICATION; case 2: // DISCOVERY_CLASSIFICATION return DISCOVERY_CLASSIFICATION; default: return null; } } /** * Find the _Fields constant that matches fieldId, throwing an exception * if it is not found. */ public static _Fields findByThriftIdOrThrow(int fieldId) { _Fields fields = findByThriftId(fieldId); if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!"); return fields; } /** * Find the _Fields constant that matches name, or null if its not found. */ public static _Fields findByName(String name) { return byName.get(name); } private final short _thriftId; private final String _fieldName; _Fields(short thriftId, String fieldName) { _thriftId = thriftId; _fieldName = fieldName; } public short getThriftFieldId() { return _thriftId; } public String getFieldName() { return _fieldName; } } // isset id assignments private _Fields optionals[] = {_Fields.DISCOVERY_CLASSIFICATION}; public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap; static { Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class); tmpMap.put(_Fields.CLASSIFICATION, new org.apache.thrift.meta_data.FieldMetaData("classification", org.apache.thrift.TFieldRequirementType.REQUIRED, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT , "Classification"))); tmpMap.put(_Fields.DISCOVERY_CLASSIFICATION, new org.apache.thrift.meta_data.FieldMetaData("discoveryClassification", org.apache.thrift.TFieldRequirementType.OPTIONAL, new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRUCT , "Classification"))); metaDataMap = Collections.unmodifiableMap(tmpMap); org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(SecurityLabel.class, metaDataMap); } public SecurityLabel() { } public SecurityLabel( ezbake.base.thrift.Classification classification) { this(); this.classification = classification; } /** * Performs a deep copy on <i>other</i>. */ public SecurityLabel(SecurityLabel other) { if (other.isSetClassification()) { this.classification = other.classification; } if (other.isSetDiscoveryClassification()) { this.discoveryClassification = other.discoveryClassification; } } public SecurityLabel deepCopy() { return new SecurityLabel(this); } @Override public void clear() { this.classification = null; this.discoveryClassification = null; } public ezbake.base.thrift.Classification getClassification() { return this.classification; } public SecurityLabel setClassification(ezbake.base.thrift.Classification classification) { this.classification = classification; return this; } public void unsetClassification() { this.classification = null; } /** Returns true if field classification is set (has been assigned a value) and false otherwise */ public boolean isSetClassification() { return this.classification != null; } public void setClassificationIsSet(boolean value) { if (!value) { this.classification = null; } } public ezbake.base.thrift.Classification getDiscoveryClassification() { return this.discoveryClassification; } public SecurityLabel setDiscoveryClassification(ezbake.base.thrift.Classification discoveryClassification) { this.discoveryClassification = discoveryClassification; return this; } public void unsetDiscoveryClassification() { this.discoveryClassification = null; } /** Returns true if field discoveryClassification is set (has been assigned a value) and false otherwise */ public boolean isSetDiscoveryClassification() { return this.discoveryClassification != null; } public void setDiscoveryClassificationIsSet(boolean value) { if (!value) { this.discoveryClassification = null; } } public void setFieldValue(_Fields field, Object value) { switch (field) { case CLASSIFICATION: if (value == null) { unsetClassification(); } else { setClassification((ezbake.base.thrift.Classification)value); } break; case DISCOVERY_CLASSIFICATION: if (value == null) { unsetDiscoveryClassification(); } else { setDiscoveryClassification((ezbake.base.thrift.Classification)value); } break; } } public Object getFieldValue(_Fields field) { switch (field) { case CLASSIFICATION: return getClassification(); case DISCOVERY_CLASSIFICATION: return getDiscoveryClassification(); } throw new IllegalStateException(); } /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */ public boolean isSet(_Fields field) { if (field == null) { throw new IllegalArgumentException(); } switch (field) { case CLASSIFICATION: return isSetClassification(); case DISCOVERY_CLASSIFICATION: return isSetDiscoveryClassification(); } throw new IllegalStateException(); } @Override public boolean equals(Object that) { if (that == null) return false; if (that instanceof SecurityLabel) return this.equals((SecurityLabel)that); return false; } public boolean equals(SecurityLabel that) { if (that == null) return false; boolean this_present_classification = true && this.isSetClassification(); boolean that_present_classification = true && that.isSetClassification(); if (this_present_classification || that_present_classification) { if (!(this_present_classification && that_present_classification)) return false; if (!this.classification.equals(that.classification)) return false; } boolean this_present_discoveryClassification = true && this.isSetDiscoveryClassification(); boolean that_present_discoveryClassification = true && that.isSetDiscoveryClassification(); if (this_present_discoveryClassification || that_present_discoveryClassification) { if (!(this_present_discoveryClassification && that_present_discoveryClassification)) return false; if (!this.discoveryClassification.equals(that.discoveryClassification)) return false; } return true; } @Override public int hashCode() { return 0; } @Override public int compareTo(SecurityLabel other) { if (!getClass().equals(other.getClass())) { return getClass().getName().compareTo(other.getClass().getName()); } int lastComparison = 0; lastComparison = Boolean.valueOf(isSetClassification()).compareTo(other.isSetClassification()); if (lastComparison != 0) { return lastComparison; } if (isSetClassification()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.classification, other.classification); if (lastComparison != 0) { return lastComparison; } } lastComparison = Boolean.valueOf(isSetDiscoveryClassification()).compareTo(other.isSetDiscoveryClassification()); if (lastComparison != 0) { return lastComparison; } if (isSetDiscoveryClassification()) { lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.discoveryClassification, other.discoveryClassification); if (lastComparison != 0) { return lastComparison; } } return 0; } public _Fields fieldForId(int fieldId) { return _Fields.findByThriftId(fieldId); } public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException { schemes.get(iprot.getScheme()).getScheme().read(iprot, this); } public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException { schemes.get(oprot.getScheme()).getScheme().write(oprot, this); } @Override public String toString() { StringBuilder sb = new StringBuilder("SecurityLabel("); boolean first = true; sb.append("classification:"); if (this.classification == null) { sb.append("null"); } else { sb.append(this.classification); } first = false; if (isSetDiscoveryClassification()) { if (!first) sb.append(", "); sb.append("discoveryClassification:"); if (this.discoveryClassification == null) { sb.append("null"); } else { sb.append(this.discoveryClassification); } first = false; } sb.append(")"); return sb.toString(); } public void validate() throws org.apache.thrift.TException { // check for required fields if (classification == null) { throw new org.apache.thrift.protocol.TProtocolException("Required field 'classification' was not present! Struct: " + toString()); } // check for sub-struct validity } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { try { write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { try { read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in))); } catch (org.apache.thrift.TException te) { throw new java.io.IOException(te); } } private static class SecurityLabelStandardSchemeFactory implements SchemeFactory { public SecurityLabelStandardScheme getScheme() { return new SecurityLabelStandardScheme(); } } private static class SecurityLabelStandardScheme extends StandardScheme<SecurityLabel> { public void read(org.apache.thrift.protocol.TProtocol iprot, SecurityLabel struct) throws org.apache.thrift.TException { org.apache.thrift.protocol.TField schemeField; iprot.readStructBegin(); while (true) { schemeField = iprot.readFieldBegin(); if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { break; } switch (schemeField.id) { case 1: // CLASSIFICATION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.classification = new ezbake.base.thrift.Classification(); struct.classification.read(iprot); struct.setClassificationIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; case 2: // DISCOVERY_CLASSIFICATION if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) { struct.discoveryClassification = new ezbake.base.thrift.Classification(); struct.discoveryClassification.read(iprot); struct.setDiscoveryClassificationIsSet(true); } else { org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } break; default: org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type); } iprot.readFieldEnd(); } iprot.readStructEnd(); // check for required fields of primitive type, which can't be checked in the validate method struct.validate(); } public void write(org.apache.thrift.protocol.TProtocol oprot, SecurityLabel struct) throws org.apache.thrift.TException { struct.validate(); oprot.writeStructBegin(STRUCT_DESC); if (struct.classification != null) { oprot.writeFieldBegin(CLASSIFICATION_FIELD_DESC); struct.classification.write(oprot); oprot.writeFieldEnd(); } if (struct.discoveryClassification != null) { if (struct.isSetDiscoveryClassification()) { oprot.writeFieldBegin(DISCOVERY_CLASSIFICATION_FIELD_DESC); struct.discoveryClassification.write(oprot); oprot.writeFieldEnd(); } } oprot.writeFieldStop(); oprot.writeStructEnd(); } } private static class SecurityLabelTupleSchemeFactory implements SchemeFactory { public SecurityLabelTupleScheme getScheme() { return new SecurityLabelTupleScheme(); } } private static class SecurityLabelTupleScheme extends TupleScheme<SecurityLabel> { @Override public void write(org.apache.thrift.protocol.TProtocol prot, SecurityLabel struct) throws org.apache.thrift.TException { TTupleProtocol oprot = (TTupleProtocol) prot; struct.classification.write(oprot); BitSet optionals = new BitSet(); if (struct.isSetDiscoveryClassification()) { optionals.set(0); } oprot.writeBitSet(optionals, 1); if (struct.isSetDiscoveryClassification()) { struct.discoveryClassification.write(oprot); } } @Override public void read(org.apache.thrift.protocol.TProtocol prot, SecurityLabel struct) throws org.apache.thrift.TException { TTupleProtocol iprot = (TTupleProtocol) prot; struct.classification = new ezbake.base.thrift.Classification(); struct.classification.read(iprot); struct.setClassificationIsSet(true); BitSet incoming = iprot.readBitSet(1); if (incoming.get(0)) { struct.discoveryClassification = new ezbake.base.thrift.Classification(); struct.discoveryClassification.read(iprot); struct.setDiscoveryClassificationIsSet(true); } } } }
/* * Copyright (C) 2015 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.android.launcher3.widget; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView.State; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.android.launcher3.BaseContainerView; import com.android.launcher3.CellLayout; import com.android.launcher3.DeleteDropTarget; import com.android.launcher3.DragSource; import com.android.launcher3.DropTarget.DragObject; import com.android.launcher3.dragndrop.DragOptions; import com.android.launcher3.folder.Folder; import com.android.launcher3.IconCache; import com.android.launcher3.ItemInfo; import com.android.launcher3.Launcher; import com.android.launcher3.LauncherAppState; import com.android.launcher3.PendingAddItemInfo; import com.android.launcher3.R; import com.android.launcher3.Utilities; import com.android.launcher3.WidgetPreviewLoader; import com.android.launcher3.Workspace; import com.android.launcher3.dragndrop.DragController; import com.android.launcher3.model.WidgetsModel; import com.android.launcher3.userevent.nano.LauncherLogProto; import com.android.launcher3.userevent.nano.LauncherLogProto.Target; import com.android.launcher3.util.Thunk; import com.android.launcher3.util.TransformingTouchDelegate; /** * The widgets list view container. */ public class WidgetsContainerView extends BaseContainerView implements View.OnLongClickListener, View.OnClickListener, DragSource { private static final String TAG = "WidgetsContainerView"; private static final boolean LOGD = false; /* Global instances that are used inside this container. */ @Thunk Launcher mLauncher; private DragController mDragController; private IconCache mIconCache; private final Rect mTmpBgPaddingRect = new Rect(); /* Recycler view related member variables */ private WidgetsRecyclerView mRecyclerView; private WidgetsListAdapter mAdapter; private TransformingTouchDelegate mRecyclerViewTouchDelegate; /* Touch handling related member variables. */ private Toast mWidgetInstructionToast; /* Rendering related. */ private WidgetPreviewLoader mWidgetPreviewLoader; public WidgetsContainerView(Context context) { this(context, null); } public WidgetsContainerView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public WidgetsContainerView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mLauncher = Launcher.getLauncher(context); mDragController = mLauncher.getDragController(); mAdapter = new WidgetsListAdapter(this, this, context); mIconCache = (LauncherAppState.getInstance()).getIconCache(); if (LOGD) { Log.d(TAG, "WidgetsContainerView constructor"); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); getRevealView().getBackground().getPadding(mTmpBgPaddingRect); mRecyclerViewTouchDelegate.setBounds( mRecyclerView.getLeft() - mTmpBgPaddingRect.left, mRecyclerView.getTop() - mTmpBgPaddingRect.top, mRecyclerView.getRight() + mTmpBgPaddingRect.right, mRecyclerView.getBottom() + mTmpBgPaddingRect.bottom); } @Override protected void onFinishInflate() { super.onFinishInflate(); mRecyclerView = (WidgetsRecyclerView) getContentView().findViewById(R.id.widgets_list_view); mRecyclerView.setAdapter(mAdapter); mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); mRecyclerViewTouchDelegate = new TransformingTouchDelegate(mRecyclerView); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); ((View) mRecyclerView.getParent()).setTouchDelegate(mRecyclerViewTouchDelegate); } // // Returns views used for launcher transitions. // public void scrollToTop() { mRecyclerView.scrollToPosition(0); } // // Touch related handling. // @Override public void onClick(View v) { // When we have exited widget tray or are in transition, disregard clicks if (!mLauncher.isWidgetsViewVisible() || mLauncher.getWorkspace().isSwitchingState() || !(v instanceof WidgetCell)) return; // Let the user know that they have to long press to add a widget if (mWidgetInstructionToast != null) { mWidgetInstructionToast.cancel(); } CharSequence msg = Utilities.wrapForTts( getContext().getText(R.string.long_press_widget_to_add), getContext().getString(R.string.long_accessible_way_to_add)); mWidgetInstructionToast = Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT); mWidgetInstructionToast.show(); } @Override public boolean onLongClick(View v) { if (LOGD) { Log.d(TAG, String.format("onLonglick [v=%s]", v)); } // Return early if this is not initiated from a touch if (!v.isInTouchMode()) return false; // When we have exited all apps or are in transition, disregard long clicks if (!mLauncher.isWidgetsViewVisible() || mLauncher.getWorkspace().isSwitchingState()) return false; // Return if global dragging is not enabled if (!mLauncher.isDraggingEnabled()) return false; boolean status = beginDragging(v); if (status && v.getTag() instanceof PendingAddWidgetInfo) { WidgetHostViewLoader hostLoader = new WidgetHostViewLoader(mLauncher, v); boolean preloadStatus = hostLoader.preloadWidget(); if (LOGD) { Log.d(TAG, String.format("preloading widget [status=%s]", preloadStatus)); } mLauncher.getDragController().addDragListener(hostLoader); } return status; } private boolean beginDragging(View v) { if (v instanceof WidgetCell) { if (!beginDraggingWidget((WidgetCell) v)) { return false; } } else { Log.e(TAG, "Unexpected dragging view: " + v); } // We don't enter spring-loaded mode if the drag has been cancelled if (mLauncher.getDragController().isDragging()) { // Go into spring loaded mode (must happen before we startDrag()) mLauncher.enterSpringLoadedDragMode(); } return true; } private boolean beginDraggingWidget(WidgetCell v) { // Get the widget preview as the drag representation WidgetImageView image = (WidgetImageView) v.findViewById(R.id.widget_preview); PendingAddItemInfo createItemInfo = (PendingAddItemInfo) v.getTag(); // If the ImageView doesn't have a drawable yet, the widget preview hasn't been loaded and // we abort the drag. if (image.getBitmap() == null) { return false; } // Compose the drag image Bitmap preview; final float scale; final Rect bounds = image.getBitmapBounds(); if (createItemInfo instanceof PendingAddWidgetInfo) { // This can happen in some weird cases involving multi-touch. We can't start dragging // the widget if this is null, so we break out. PendingAddWidgetInfo createWidgetInfo = (PendingAddWidgetInfo) createItemInfo; int[] size = mLauncher.getWorkspace().estimateItemSize(createWidgetInfo, true); Bitmap icon = image.getBitmap(); float minScale = 1.25f; int maxWidth = Math.min((int) (icon.getWidth() * minScale), size[0]); int[] previewSizeBeforeScale = new int[1]; preview = getWidgetPreviewLoader().generateWidgetPreview(mLauncher, createWidgetInfo.info, maxWidth, null, previewSizeBeforeScale); if (previewSizeBeforeScale[0] < icon.getWidth()) { // The icon has extra padding around it. int padding = (icon.getWidth() - previewSizeBeforeScale[0]) / 2; if (icon.getWidth() > image.getWidth()) { padding = padding * image.getWidth() / icon.getWidth(); } bounds.left += padding; bounds.right -= padding; } scale = bounds.width() / (float) preview.getWidth(); } else { PendingAddShortcutInfo createShortcutInfo = (PendingAddShortcutInfo) v.getTag(); Drawable icon = mIconCache.getFullResIcon(createShortcutInfo.activityInfo); preview = Utilities.createIconBitmap(icon, mLauncher); createItemInfo.spanX = createItemInfo.spanY = 1; scale = ((float) mLauncher.getDeviceProfile().iconSizePx) / preview.getWidth(); } // Since we are not going through the workspace for starting the drag, set drag related // information on the workspace before starting the drag. mLauncher.getWorkspace().prepareDragWithProvider( new PendingItemPreviewProvider(v, createItemInfo, preview)); // Start the drag mDragController.startDrag(image, preview, this, createItemInfo, bounds, scale, new DragOptions()); return true; } // // Drag related handling methods that implement {@link DragSource} interface. // @Override public boolean supportsFlingToDelete() { return true; } @Override public boolean supportsAppInfoDropTarget() { return true; } /* * Both this method and {@link #supportsFlingToDelete} has to return {@code false} for the * {@link DeleteDropTarget} to be invisible.) */ @Override public boolean supportsDeleteDropTarget() { return false; } @Override public float getIntrinsicIconScaleFactor() { return 0; } @Override public void onFlingToDeleteCompleted() { // We just dismiss the drag when we fling, so cleanup here mLauncher.exitSpringLoadedDragModeDelayed(true, Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null); mLauncher.unlockScreenOrientation(false); } @Override public void onDropCompleted(View target, DragObject d, boolean isFlingToDelete, boolean success) { if (LOGD) { Log.d(TAG, "onDropCompleted"); } if (isFlingToDelete || !success || (target != mLauncher.getWorkspace() && !(target instanceof DeleteDropTarget) && !(target instanceof Folder))) { // Exit spring loaded mode if we have not successfully dropped or have not handled the // drop in Workspace mLauncher.exitSpringLoadedDragModeDelayed(true, Launcher.EXIT_SPRINGLOADED_MODE_SHORT_TIMEOUT, null); } mLauncher.unlockScreenOrientation(false); // Display an error message if the drag failed due to there not being enough space on the // target layout we were dropping on. if (!success) { boolean showOutOfSpaceMessage = false; if (target instanceof Workspace) { int currentScreen = mLauncher.getCurrentWorkspaceScreen(); Workspace workspace = (Workspace) target; CellLayout layout = (CellLayout) workspace.getChildAt(currentScreen); ItemInfo itemInfo = d.dragInfo; if (layout != null) { showOutOfSpaceMessage = !layout.findCellForSpan(null, itemInfo.spanX, itemInfo.spanY); } } if (showOutOfSpaceMessage) { mLauncher.showOutOfSpaceMessage(false); } d.deferDragViewCleanupPostAnimation = false; } } /** * Initialize the widget data model. */ public void addWidgets(WidgetsModel model) { mRecyclerView.setWidgets(model); mAdapter.setWidgetsModel(model); mAdapter.notifyDataSetChanged(); View loader = getContentView().findViewById(R.id.loader); if (loader != null) { ((ViewGroup) getContentView()).removeView(loader); } } public boolean isEmpty() { return mAdapter.getItemCount() == 0; } private WidgetPreviewLoader getWidgetPreviewLoader() { if (mWidgetPreviewLoader == null) { mWidgetPreviewLoader = LauncherAppState.getInstance().getWidgetCache(); } return mWidgetPreviewLoader; } @Override public void fillInLaunchSourceData(View v, ItemInfo info, Target target, Target targetParent) { targetParent.containerType = LauncherLogProto.WIDGETS; } }
package org.bouncycastle.jce; import java.io.IOException; import java.security.AlgorithmParameters; import java.security.GeneralSecurityException; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.spec.InvalidKeySpecException; import java.security.spec.PSSParameterSpec; import java.security.spec.X509EncodedKeySpec; import java.util.HashSet; import java.util.Hashtable; import java.util.Set; import javax.security.auth.x500.X500Principal; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.ASN1Encoding; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.DERNull; import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers; import org.bouncycastle.asn1.pkcs.CertificationRequest; import org.bouncycastle.asn1.pkcs.CertificationRequestInfo; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.pkcs.RSASSAPSSparams; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x509.X509Name; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.Strings; /** * A class for verifying and creating PKCS10 Certification requests. * <pre> * CertificationRequest ::= SEQUENCE { * certificationRequestInfo CertificationRequestInfo, * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }}, * signature BIT STRING * } * * CertificationRequestInfo ::= SEQUENCE { * version INTEGER { v1(0) } (v1,...), * subject Name, * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }}, * attributes [0] Attributes{{ CRIAttributes }} * } * * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }} * * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE { * type ATTRIBUTE.&id({IOSet}), * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type}) * } * </pre> * @deprecated use classes in org.bouncycastle.pkcs. */ public class PKCS10CertificationRequest extends CertificationRequest { private static Hashtable algorithms = new Hashtable(); private static Hashtable params = new Hashtable(); private static Hashtable keyAlgorithms = new Hashtable(); private static Hashtable oids = new Hashtable(); private static Set noParams = new HashSet(); static { algorithms.put("MD2WITHRSAENCRYPTION", new ASN1ObjectIdentifier("1.2.840.113549.1.1.2")); algorithms.put("MD2WITHRSA", new ASN1ObjectIdentifier("1.2.840.113549.1.1.2")); algorithms.put("MD5WITHRSAENCRYPTION", new ASN1ObjectIdentifier("1.2.840.113549.1.1.4")); algorithms.put("MD5WITHRSA", new ASN1ObjectIdentifier("1.2.840.113549.1.1.4")); algorithms.put("RSAWITHMD5", new ASN1ObjectIdentifier("1.2.840.113549.1.1.4")); algorithms.put("SHA1WITHRSAENCRYPTION", new ASN1ObjectIdentifier("1.2.840.113549.1.1.5")); algorithms.put("SHA1WITHRSA", new ASN1ObjectIdentifier("1.2.840.113549.1.1.5")); algorithms.put("SHA224WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha224WithRSAEncryption); algorithms.put("SHA224WITHRSA", PKCSObjectIdentifiers.sha224WithRSAEncryption); algorithms.put("SHA256WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha256WithRSAEncryption); algorithms.put("SHA256WITHRSA", PKCSObjectIdentifiers.sha256WithRSAEncryption); algorithms.put("SHA384WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha384WithRSAEncryption); algorithms.put("SHA384WITHRSA", PKCSObjectIdentifiers.sha384WithRSAEncryption); algorithms.put("SHA512WITHRSAENCRYPTION", PKCSObjectIdentifiers.sha512WithRSAEncryption); algorithms.put("SHA512WITHRSA", PKCSObjectIdentifiers.sha512WithRSAEncryption); algorithms.put("SHA1WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); algorithms.put("SHA224WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); algorithms.put("SHA256WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); algorithms.put("SHA384WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); algorithms.put("SHA512WITHRSAANDMGF1", PKCSObjectIdentifiers.id_RSASSA_PSS); algorithms.put("RSAWITHSHA1", new ASN1ObjectIdentifier("1.2.840.113549.1.1.5")); algorithms.put("RIPEMD128WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); algorithms.put("RIPEMD128WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd128); algorithms.put("RIPEMD160WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); algorithms.put("RIPEMD160WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd160); algorithms.put("RIPEMD256WITHRSAENCRYPTION", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); algorithms.put("RIPEMD256WITHRSA", TeleTrusTObjectIdentifiers.rsaSignatureWithripemd256); algorithms.put("SHA1WITHDSA", new ASN1ObjectIdentifier("1.2.840.10040.4.3")); algorithms.put("DSAWITHSHA1", new ASN1ObjectIdentifier("1.2.840.10040.4.3")); algorithms.put("SHA224WITHDSA", NISTObjectIdentifiers.dsa_with_sha224); algorithms.put("SHA256WITHDSA", NISTObjectIdentifiers.dsa_with_sha256); algorithms.put("SHA384WITHDSA", NISTObjectIdentifiers.dsa_with_sha384); algorithms.put("SHA512WITHDSA", NISTObjectIdentifiers.dsa_with_sha512); algorithms.put("SHA1WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1); algorithms.put("SHA224WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); algorithms.put("SHA256WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); algorithms.put("SHA384WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); algorithms.put("SHA512WITHECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); algorithms.put("ECDSAWITHSHA1", X9ObjectIdentifiers.ecdsa_with_SHA1); algorithms.put("GOST3411WITHGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); algorithms.put("GOST3410WITHGOST3411", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); algorithms.put("GOST3411WITHECGOST3410", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); algorithms.put("GOST3411WITHECGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); algorithms.put("GOST3411WITHGOST3410-2001", CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); // // reverse mappings // oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.5"), "SHA1WITHRSA"); oids.put(PKCSObjectIdentifiers.sha224WithRSAEncryption, "SHA224WITHRSA"); oids.put(PKCSObjectIdentifiers.sha256WithRSAEncryption, "SHA256WITHRSA"); oids.put(PKCSObjectIdentifiers.sha384WithRSAEncryption, "SHA384WITHRSA"); oids.put(PKCSObjectIdentifiers.sha512WithRSAEncryption, "SHA512WITHRSA"); oids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94, "GOST3411WITHGOST3410"); oids.put(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001, "GOST3411WITHECGOST3410"); oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.4"), "MD5WITHRSA"); oids.put(new ASN1ObjectIdentifier("1.2.840.113549.1.1.2"), "MD2WITHRSA"); oids.put(new ASN1ObjectIdentifier("1.2.840.10040.4.3"), "SHA1WITHDSA"); oids.put(X9ObjectIdentifiers.ecdsa_with_SHA1, "SHA1WITHECDSA"); oids.put(X9ObjectIdentifiers.ecdsa_with_SHA224, "SHA224WITHECDSA"); oids.put(X9ObjectIdentifiers.ecdsa_with_SHA256, "SHA256WITHECDSA"); oids.put(X9ObjectIdentifiers.ecdsa_with_SHA384, "SHA384WITHECDSA"); oids.put(X9ObjectIdentifiers.ecdsa_with_SHA512, "SHA512WITHECDSA"); oids.put(OIWObjectIdentifiers.sha1WithRSA, "SHA1WITHRSA"); oids.put(OIWObjectIdentifiers.dsaWithSHA1, "SHA1WITHDSA"); oids.put(NISTObjectIdentifiers.dsa_with_sha224, "SHA224WITHDSA"); oids.put(NISTObjectIdentifiers.dsa_with_sha256, "SHA256WITHDSA"); // // key types // keyAlgorithms.put(PKCSObjectIdentifiers.rsaEncryption, "RSA"); keyAlgorithms.put(X9ObjectIdentifiers.id_dsa, "DSA"); // // According to RFC 3279, the ASN.1 encoding SHALL (id-dsa-with-sha1) or MUST (ecdsa-with-SHA*) omit the parameters field. // The parameters field SHALL be NULL for RSA based signature algorithms. // noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA1); noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA224); noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA256); noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA384); noParams.add(X9ObjectIdentifiers.ecdsa_with_SHA512); noParams.add(X9ObjectIdentifiers.id_dsa_with_sha1); noParams.add(NISTObjectIdentifiers.dsa_with_sha224); noParams.add(NISTObjectIdentifiers.dsa_with_sha256); // // RFC 4491 // noParams.add(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_94); noParams.add(CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001); // // explicit params // AlgorithmIdentifier sha1AlgId = new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE); params.put("SHA1WITHRSAANDMGF1", creatPSSParams(sha1AlgId, 20)); AlgorithmIdentifier sha224AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224, DERNull.INSTANCE); params.put("SHA224WITHRSAANDMGF1", creatPSSParams(sha224AlgId, 28)); AlgorithmIdentifier sha256AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, DERNull.INSTANCE); params.put("SHA256WITHRSAANDMGF1", creatPSSParams(sha256AlgId, 32)); AlgorithmIdentifier sha384AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha384, DERNull.INSTANCE); params.put("SHA384WITHRSAANDMGF1", creatPSSParams(sha384AlgId, 48)); AlgorithmIdentifier sha512AlgId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512, DERNull.INSTANCE); params.put("SHA512WITHRSAANDMGF1", creatPSSParams(sha512AlgId, 64)); } private static RSASSAPSSparams creatPSSParams(AlgorithmIdentifier hashAlgId, int saltSize) { return new RSASSAPSSparams( hashAlgId, new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, hashAlgId), new ASN1Integer(saltSize), new ASN1Integer(1)); } private static ASN1Sequence toDERSequence( byte[] bytes) { try { ASN1InputStream dIn = new ASN1InputStream(bytes); return (ASN1Sequence)dIn.readObject(); } catch (Exception e) { throw new IllegalArgumentException("badly encoded request"); } } /** * construct a PKCS10 certification request from a DER encoded * byte stream. */ public PKCS10CertificationRequest( byte[] bytes) { super(toDERSequence(bytes)); } public PKCS10CertificationRequest( ASN1Sequence sequence) { super(sequence); } /** * create a PKCS10 certfication request using the BC provider. */ public PKCS10CertificationRequest( String signatureAlgorithm, X509Name subject, PublicKey key, ASN1Set attributes, PrivateKey signingKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException { this(signatureAlgorithm, subject, key, attributes, signingKey, BouncyCastleProvider.PROVIDER_NAME); } private static X509Name convertName( X500Principal name) { try { return new X509Principal(name.getEncoded()); } catch (IOException e) { throw new IllegalArgumentException("can't convert name"); } } /** * create a PKCS10 certfication request using the BC provider. */ public PKCS10CertificationRequest( String signatureAlgorithm, X500Principal subject, PublicKey key, ASN1Set attributes, PrivateKey signingKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException { this(signatureAlgorithm, convertName(subject), key, attributes, signingKey, BouncyCastleProvider.PROVIDER_NAME); } /** * create a PKCS10 certfication request using the named provider. */ public PKCS10CertificationRequest( String signatureAlgorithm, X500Principal subject, PublicKey key, ASN1Set attributes, PrivateKey signingKey, String provider) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException { this(signatureAlgorithm, convertName(subject), key, attributes, signingKey, provider); } /** * create a PKCS10 certfication request using the named provider. */ public PKCS10CertificationRequest( String signatureAlgorithm, X509Name subject, PublicKey key, ASN1Set attributes, PrivateKey signingKey, String provider) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException { String algorithmName = Strings.toUpperCase(signatureAlgorithm); ASN1ObjectIdentifier sigOID = (ASN1ObjectIdentifier)algorithms.get(algorithmName); if (sigOID == null) { try { sigOID = new ASN1ObjectIdentifier(algorithmName); } catch (Exception e) { throw new IllegalArgumentException("Unknown signature type requested"); } } if (subject == null) { throw new IllegalArgumentException("subject must not be null"); } if (key == null) { throw new IllegalArgumentException("public key must not be null"); } if (noParams.contains(sigOID)) { this.sigAlgId = new AlgorithmIdentifier(sigOID); } else if (params.containsKey(algorithmName)) { this.sigAlgId = new AlgorithmIdentifier(sigOID, (ASN1Encodable)params.get(algorithmName)); } else { this.sigAlgId = new AlgorithmIdentifier(sigOID, DERNull.INSTANCE); } try { ASN1Sequence seq = (ASN1Sequence)ASN1Primitive.fromByteArray(key.getEncoded()); this.reqInfo = new CertificationRequestInfo(subject, new SubjectPublicKeyInfo(seq), attributes); } catch (IOException e) { throw new IllegalArgumentException("can't encode public key"); } Signature sig; if (provider == null) { sig = Signature.getInstance(signatureAlgorithm); } else { sig = Signature.getInstance(signatureAlgorithm, provider); } sig.initSign(signingKey); try { sig.update(reqInfo.getEncoded(ASN1Encoding.DER)); } catch (Exception e) { throw new IllegalArgumentException("exception encoding TBS cert request - " + e); } this.sigBits = new DERBitString(sig.sign()); } /** * return the public key associated with the certification request - * the public key is created using the BC provider. */ public PublicKey getPublicKey() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException { return getPublicKey(BouncyCastleProvider.PROVIDER_NAME); } public PublicKey getPublicKey( String provider) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException { SubjectPublicKeyInfo subjectPKInfo = reqInfo.getSubjectPublicKeyInfo(); try { X509EncodedKeySpec xspec = new X509EncodedKeySpec(new DERBitString(subjectPKInfo).getBytes()); AlgorithmIdentifier keyAlg = subjectPKInfo.getAlgorithm(); try { if (provider == null) { return KeyFactory.getInstance(keyAlg.getAlgorithm().getId()).generatePublic(xspec); } else { return KeyFactory.getInstance(keyAlg.getAlgorithm().getId(), provider).generatePublic(xspec); } } catch (NoSuchAlgorithmException e) { // // try an alternate // if (keyAlgorithms.get(keyAlg.getObjectId()) != null) { String keyAlgorithm = (String)keyAlgorithms.get(keyAlg.getObjectId()); if (provider == null) { return KeyFactory.getInstance(keyAlgorithm).generatePublic(xspec); } else { return KeyFactory.getInstance(keyAlgorithm, provider).generatePublic(xspec); } } throw e; } } catch (InvalidKeySpecException e) { throw new InvalidKeyException("error decoding public key"); } catch (IOException e) { throw new InvalidKeyException("error decoding public key"); } } /** * verify the request using the BC provider. */ public boolean verify() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException { return verify(BouncyCastleProvider.PROVIDER_NAME); } /** * verify the request using the passed in provider. */ public boolean verify( String provider) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException { return verify(this.getPublicKey(provider), provider); } /** * verify the request using the passed in public key and the provider.. */ public boolean verify( PublicKey pubKey, String provider) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException { Signature sig; try { if (provider == null) { sig = Signature.getInstance(getSignatureName(sigAlgId)); } else { sig = Signature.getInstance(getSignatureName(sigAlgId), provider); } } catch (NoSuchAlgorithmException e) { // // try an alternate // if (oids.get(sigAlgId.getObjectId()) != null) { String signatureAlgorithm = (String)oids.get(sigAlgId.getObjectId()); if (provider == null) { sig = Signature.getInstance(signatureAlgorithm); } else { sig = Signature.getInstance(signatureAlgorithm, provider); } } else { throw e; } } setSignatureParameters(sig, sigAlgId.getParameters()); sig.initVerify(pubKey); try { sig.update(reqInfo.getEncoded(ASN1Encoding.DER)); } catch (Exception e) { throw new SignatureException("exception encoding TBS cert request - " + e); } return sig.verify(sigBits.getBytes()); } /** * return a DER encoded byte array representing this object */ public byte[] getEncoded() { try { return this.getEncoded(ASN1Encoding.DER); } catch (IOException e) { throw new RuntimeException(e.toString()); } } private void setSignatureParameters( Signature signature, ASN1Encodable params) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException { if (params != null && !DERNull.INSTANCE.equals(params)) { AlgorithmParameters sigParams = AlgorithmParameters.getInstance(signature.getAlgorithm(), signature.getProvider()); try { sigParams.init(params.toASN1Primitive().getEncoded(ASN1Encoding.DER)); } catch (IOException e) { throw new SignatureException("IOException decoding parameters: " + e.getMessage()); } if (signature.getAlgorithm().endsWith("MGF1")) { try { signature.setParameter(sigParams.getParameterSpec(PSSParameterSpec.class)); } catch (GeneralSecurityException e) { throw new SignatureException("Exception extracting parameters: " + e.getMessage()); } } } } static String getSignatureName( AlgorithmIdentifier sigAlgId) { ASN1Encodable params = sigAlgId.getParameters(); if (params != null && !DERNull.INSTANCE.equals(params)) { if (sigAlgId.getObjectId().equals(PKCSObjectIdentifiers.id_RSASSA_PSS)) { RSASSAPSSparams rsaParams = RSASSAPSSparams.getInstance(params); return getDigestAlgName(rsaParams.getHashAlgorithm().getObjectId()) + "withRSAandMGF1"; } } return sigAlgId.getObjectId().getId(); } private static String getDigestAlgName( ASN1ObjectIdentifier digestAlgOID) { if (PKCSObjectIdentifiers.md5.equals(digestAlgOID)) { return "MD5"; } else if (OIWObjectIdentifiers.idSHA1.equals(digestAlgOID)) { return "SHA1"; } else if (NISTObjectIdentifiers.id_sha224.equals(digestAlgOID)) { return "SHA224"; } else if (NISTObjectIdentifiers.id_sha256.equals(digestAlgOID)) { return "SHA256"; } else if (NISTObjectIdentifiers.id_sha384.equals(digestAlgOID)) { return "SHA384"; } else if (NISTObjectIdentifiers.id_sha512.equals(digestAlgOID)) { return "SHA512"; } else if (TeleTrusTObjectIdentifiers.ripemd128.equals(digestAlgOID)) { return "RIPEMD128"; } else if (TeleTrusTObjectIdentifiers.ripemd160.equals(digestAlgOID)) { return "RIPEMD160"; } else if (TeleTrusTObjectIdentifiers.ripemd256.equals(digestAlgOID)) { return "RIPEMD256"; } else if (CryptoProObjectIdentifiers.gostR3411.equals(digestAlgOID)) { return "GOST3411"; } else { return digestAlgOID.getId(); } } }
/** * Copyright (c) 2013 Cangol. * * 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 mobi.cangol.mobile.onetv; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import mobi.cangol.mobile.onetv.adapter.StationAdapter; import mobi.cangol.mobile.onetv.adapter.StationAdapter.OnActionClickListener; import mobi.cangol.mobile.onetv.api.ApiHttpResult; import mobi.cangol.mobile.onetv.base.BaseContentFragment; import mobi.cangol.mobile.onetv.db.StationService; import mobi.cangol.mobile.onetv.db.model.Station; import mobi.cangol.mobile.onetv.utils.Contants; import mobi.cangol.mobile.onetv.view.LoadMoreAdapter; import mobi.cangol.mobile.onetv.view.LoadMoreAdapter.OnLoadCallback; import mobi.cangol.mobile.onetv.view.PromptView; import org.json.JSONException; import org.json.JSONObject; import com.google.analytics.tracking.android.MapBuilder; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources.NotFoundException; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; /** * @Description StationFragment.java * @author Cangol * @date 2013-9-8 */ public class StationListFragment extends BaseContentFragment { private ListView listView; private PromptView promptView; private ArrayList<Station> mItemList; private LoadMoreAdapter<Station> loadMoreAdapter; private StationAdapter dataAdapter; private int page=1; private int pageSize=10; private StationService stationService; private String position; private int tvJsonVersion; private SharedPreferences sp ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); stationService=new StationService(this.getActivity()); position=this.getArguments().getString("position"); sp = this.getActivity().getSharedPreferences("OneTv", Context.MODE_PRIVATE); tvJsonVersion=sp.getInt("tvJsonVersion",0); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //View v = inflater.inflate("left".equals(position)?R.layout.fragment_list:R.layout.fragment_list_ad, container,false); View v = inflater.inflate(R.layout.fragment_list, container,false); findViews(v); initViews(savedInstanceState); return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initData(savedInstanceState); } @Override protected void findViews(View view) { listView= (ListView) view.findViewById(R.id.listview); promptView=(PromptView) view.findViewById(R.id.promptView); } @Override protected void initViews(Bundle savedInstanceState) { this.setTitle(R.string.menu_station); LayoutInflater mInflater=(LayoutInflater) this.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); dataAdapter = new StationAdapter(this.getActivity()); if("left".equals(position)){ dataAdapter.setLeft(true); } loadMoreAdapter = new LoadMoreAdapter<Station>(dataAdapter,mInflater.inflate(R.layout.common_view_footer,null)); loadMoreAdapter.setAbsListView(listView); listView.setAdapter(loadMoreAdapter); listView.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Station item=dataAdapter.getItem(position); if("left".equals(StationListFragment.this.position)){ playStationF(item); }else{ toStationProgram(item); } tracker.send(MapBuilder.createEvent("ui_action", "Click", "item", null).build()); } }); dataAdapter.setOnActionClickListener(new OnActionClickListener(){ @Override public void onClick(View v, int position) { Station item=dataAdapter.getItem(position); if("left".equals(StationListFragment.this.position)){ playStationF(item); }else{ playStationA(item); } tracker.send(MapBuilder.createEvent("ui_action", "Click", "item action", null).build()); } }); loadMoreAdapter.setOnLoadCallback(new OnLoadCallback(){ @Override public boolean hasNext(int count) { return count>=page*pageSize; } @Override public void loadMoreData() { page++; getStationList((page-1)*pageSize,pageSize); tracker.send(MapBuilder.createEvent("ui_action", "scroll", "list", null).build()); } }); } private void toStationProgram(Station station){ Bundle bundle=new Bundle(); bundle.putSerializable("station", station); this.setContentFragment(StationProgramFragment.class, "StationProgramFragment", bundle); } private void playStationF(Station station){ Bundle bundle=new Bundle(); bundle.putSerializable("station", station); this.setContentFragment(PlayVideoFragment.class, "PlayVideoFragment", bundle); } private void playStationA(Station station){ Intent intent=new Intent(this.getActivity(),PlayerActivity.class); intent.putExtra("station", station); this.startActivity(intent); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("items", mItemList); } @Override protected void initData(Bundle savedInstanceState) { if(tvJsonVersion!=Contants.TVJSON_VERSION){ initTvData(); return; } if(savedInstanceState!=null) mItemList=(ArrayList<Station>) savedInstanceState.getSerializable("items"); if(mItemList==null){ getStationList((page-1)*pageSize,pageSize); }else{ updateView(mItemList); } } private void updateView(List<Station> list){ if(page==1){ dataAdapter.clear(); } loadMoreAdapter.addMoreData(list); if(loadMoreAdapter.getCount()>0){ promptView.showContent(); }else{ promptView.showEmpty(); } loadMoreAdapter.addMoreComplete(); mItemList=dataAdapter.getItems(); } public String inputStream2String(InputStream is) throws IOException{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i=-1; while((i=is.read())!=-1){ baos.write(i); } return baos.toString(); } private void parserTvData(){ String response =null; ApiHttpResult<Station> result = null; try { response =inputStream2String(this.getResources().openRawResource(R.raw.tv)); result = ApiHttpResult.parserObject(Station.class, new JSONObject(response)); } catch (JSONException e) { e.printStackTrace(); } catch (NotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } List<Station> list=result.getList(); stationService.deleteAll(); for(Station station:list){ stationService.save(station); } sp.edit().putInt("tvJsonVersion", Contants.TVJSON_VERSION).commit(); } protected void initTvData() { new AsyncTask<Void,Void,Void>(){ @Override protected void onPreExecute() { super.onPreExecute(); promptView.showLoading(); } @Override protected Void doInBackground(Void... params) { parserTvData(); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); getStationList((page-1)*pageSize,pageSize); } }.execute(); // AsyncHttpClient client=new AsyncHttpClient(); // RequestParams params=new RequestParams(ApiContants.stationSync("")); // client.get(ApiContants.URL_STATION_SYNC, params, new JsonHttpResponseHandler(){ // // @Override // public void onSuccess(JSONObject response) { // super.onSuccess(response); // Log.d(response.toString()); // ApiHttpResult<Station> result=ApiHttpResult.parserObject(Station.class, response); // List<Station> list=result.getList(); // for(Station station:list){ // stationService.save(station); // } // } // // @Override // public void onFailure(Throwable error, String content) { // super.onFailure(error, content); // } // // @Override // public void onFinish() { // super.onFinish(); // } // // @Override // public void onStart() { // super.onStart(); // } // // }); } private void getStationList(final long from,final long max){ new AsyncTask<Void,Void,List<Station>>(){ @Override protected void onPreExecute() { super.onPreExecute(); if(from==0) promptView.showLoading(); } @Override protected List<Station> doInBackground(Void... params) { return stationService.findList(from, max); } @Override protected void onPostExecute(List<Station> result) { super.onPostExecute(result); updateView(result); } }.execute(); } public boolean isCleanStack(){ return true; } }
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. package org.rocksdb; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.nio.ByteBuffer; import java.util.ArrayDeque; import java.util.Deque; import static org.assertj.core.api.Assertions.assertThat; public class WriteBatchWithIndexTest { @ClassRule public static final RocksMemoryResource rocksMemoryResource = new RocksMemoryResource(); @Rule public TemporaryFolder dbFolder = new TemporaryFolder(); @Test public void readYourOwnWrites() throws RocksDBException { try (final Options options = new Options().setCreateIfMissing(true); final RocksDB db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath())) { final byte[] k1 = "key1".getBytes(); final byte[] v1 = "value1".getBytes(); final byte[] k2 = "key2".getBytes(); final byte[] v2 = "value2".getBytes(); db.put(k1, v1); db.put(k2, v2); try (final WriteBatchWithIndex wbwi = new WriteBatchWithIndex(true); final RocksIterator base = db.newIterator(); final RocksIterator it = wbwi.newIteratorWithBase(base)) { it.seek(k1); assertThat(it.isValid()).isTrue(); assertThat(it.key()).isEqualTo(k1); assertThat(it.value()).isEqualTo(v1); it.seek(k2); assertThat(it.isValid()).isTrue(); assertThat(it.key()).isEqualTo(k2); assertThat(it.value()).isEqualTo(v2); //put data to the write batch and make sure we can read it. final byte[] k3 = "key3".getBytes(); final byte[] v3 = "value3".getBytes(); wbwi.put(k3, v3); it.seek(k3); assertThat(it.isValid()).isTrue(); assertThat(it.key()).isEqualTo(k3); assertThat(it.value()).isEqualTo(v3); //update k2 in the write batch and check the value final byte[] v2Other = "otherValue2".getBytes(); wbwi.put(k2, v2Other); it.seek(k2); assertThat(it.isValid()).isTrue(); assertThat(it.key()).isEqualTo(k2); assertThat(it.value()).isEqualTo(v2Other); //remove k1 and make sure we can read back the write wbwi.remove(k1); it.seek(k1); assertThat(it.key()).isNotEqualTo(k1); //reinsert k1 and make sure we see the new value final byte[] v1Other = "otherValue1".getBytes(); wbwi.put(k1, v1Other); it.seek(k1); assertThat(it.isValid()).isTrue(); assertThat(it.key()).isEqualTo(k1); assertThat(it.value()).isEqualTo(v1Other); } } } @Test public void write_writeBatchWithIndex() throws RocksDBException { try (final Options options = new Options().setCreateIfMissing(true); final RocksDB db = RocksDB.open(options, dbFolder.getRoot().getAbsolutePath())) { final byte[] k1 = "key1".getBytes(); final byte[] v1 = "value1".getBytes(); final byte[] k2 = "key2".getBytes(); final byte[] v2 = "value2".getBytes(); try (final WriteBatchWithIndex wbwi = new WriteBatchWithIndex()) { wbwi.put(k1, v1); wbwi.put(k2, v2); db.write(new WriteOptions(), wbwi); } assertThat(db.get(k1)).isEqualTo(v1); assertThat(db.get(k2)).isEqualTo(v2); } } @Test public void iterator() throws RocksDBException { try (final WriteBatchWithIndex wbwi = new WriteBatchWithIndex(true)) { final String k1 = "key1"; final String v1 = "value1"; final String k2 = "key2"; final String v2 = "value2"; final String k3 = "key3"; final String v3 = "value3"; final byte[] k1b = k1.getBytes(); final byte[] v1b = v1.getBytes(); final byte[] k2b = k2.getBytes(); final byte[] v2b = v2.getBytes(); final byte[] k3b = k3.getBytes(); final byte[] v3b = v3.getBytes(); //add put records wbwi.put(k1b, v1b); wbwi.put(k2b, v2b); wbwi.put(k3b, v3b); //add a deletion record final String k4 = "key4"; final byte[] k4b = k4.getBytes(); wbwi.remove(k4b); final WBWIRocksIterator.WriteEntry[] expected = { new WBWIRocksIterator.WriteEntry(WBWIRocksIterator.WriteType.PUT, new DirectSlice(k1), new DirectSlice(v1)), new WBWIRocksIterator.WriteEntry(WBWIRocksIterator.WriteType.PUT, new DirectSlice(k2), new DirectSlice(v2)), new WBWIRocksIterator.WriteEntry(WBWIRocksIterator.WriteType.PUT, new DirectSlice(k3), new DirectSlice(v3)), new WBWIRocksIterator.WriteEntry(WBWIRocksIterator.WriteType.DELETE, new DirectSlice(k4), DirectSlice.NONE) }; try (final WBWIRocksIterator it = wbwi.newIterator()) { //direct access - seek to key offsets final int[] testOffsets = {2, 0, 1, 3}; for (int i = 0; i < testOffsets.length; i++) { final int testOffset = testOffsets[i]; final byte[] key = toArray(expected[testOffset].getKey().data()); it.seek(key); assertThat(it.isValid()).isTrue(); final WBWIRocksIterator.WriteEntry entry = it.entry(); assertThat(entry.equals(expected[testOffset])).isTrue(); } //forward iterative access int i = 0; for (it.seekToFirst(); it.isValid(); it.next()) { assertThat(it.entry().equals(expected[i++])).isTrue(); } //reverse iterative access i = expected.length - 1; for (it.seekToLast(); it.isValid(); it.prev()) { assertThat(it.entry().equals(expected[i--])).isTrue(); } } } } @Test public void zeroByteTests() { try (final WriteBatchWithIndex wbwi = new WriteBatchWithIndex(true)) { final byte[] zeroByteValue = new byte[]{0, 0}; //add zero byte value wbwi.put(zeroByteValue, zeroByteValue); final ByteBuffer buffer = ByteBuffer.allocateDirect(zeroByteValue.length); buffer.put(zeroByteValue); WBWIRocksIterator.WriteEntry[] expected = { new WBWIRocksIterator.WriteEntry(WBWIRocksIterator.WriteType.PUT, new DirectSlice(buffer, zeroByteValue.length), new DirectSlice(buffer, zeroByteValue.length)) }; try (final WBWIRocksIterator it = wbwi.newIterator()) { it.seekToFirst(); assertThat(it.entry().equals(expected[0])).isTrue(); assertThat(it.entry().hashCode() == expected[0].hashCode()).isTrue(); } } } private byte[] toArray(final ByteBuffer buf) { final byte[] ary = new byte[buf.remaining()]; buf.get(ary); return ary; } }
package eu.dzim.shared.fx.ui; import eu.dzim.shared.fx.util.ProgressTranistion; import eu.dzim.shared.fx.util.UIComponentType; import eu.dzim.shared.util.SingleAcceptor; import javafx.animation.FadeTransition; import javafx.animation.ParallelTransition; import javafx.animation.TranslateTransition; import javafx.beans.binding.Bindings; import javafx.beans.binding.DoubleBinding; import javafx.beans.property.*; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.css.PseudoClass; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.geometry.Orientation; import javafx.scene.CacheHint; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.ProgressBar; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.input.TouchEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.Region; import javafx.scene.layout.StackPane; import javafx.scene.shape.Rectangle; import javafx.util.Duration; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.util.*; public class SwipePane extends StackPane { private static final Logger LOG = LogManager.getLogger(SwipePane.class); private final Set<Node> nodeList = new HashSet<>(); private final PseudoClass selected = PseudoClass.getPseudoClass("selected"); private final ObservableList<SwipePanePlaceholder<?>> panes = FXCollections.observableArrayList(); private final ObservableList<SwipePaneCircleButton> circles = FXCollections.observableArrayList(); private final IntegerProperty index = new SimpleIntegerProperty(this, "index", -1); private final ObjectProperty<Duration> duration = new SimpleObjectProperty<>(this, "duration", Duration.millis(250.0)); private final BooleanProperty useControlOpacity = new SimpleBooleanProperty(this, "useControlOpacity", true); private final BooleanProperty usePanelOpacity = new SimpleBooleanProperty(this, "usePanelOpacity", false); private final BooleanProperty usePanelClipping = new SimpleBooleanProperty(this, "usePanelClipping", true); private final ObjectProperty<Orientation> orientation = new SimpleObjectProperty<>(this, "orientation", Orientation.HORIZONTAL); private final DoubleProperty scrollRestriction = new SimpleDoubleProperty(this, "scrollRestriction", 0.0); @FXML private ProgressBar progress; @FXML private HBox circleBox; @FXML private Button back; @FXML private Button close; private LoadRestrictionType loadRestrictionType = LoadRestrictionType.ONE; private SingleAcceptor<Void> onBackAcceptor = getDefaultOnBackAcceptor(); private SingleAcceptor<Void> onCloseAcceptor = getDefaultOnCloseAcceptor(); private boolean panesInitialized = false; private boolean drag = false; // horizontal orientation private double dragX = 0.0; private Map<Node, Double> paneToTranslateXMapping = new HashMap<>(); // vertical orientation private double dragY = 0.0; private Map<Node, Double> paneToTranslateYMapping = new HashMap<>(); public SwipePane() { super(); try { getLoader(SharedUIComponentType.SWIPE_PANE).load(); } catch (IOException e) { LOG.error(e.getMessage(), e); throw new RuntimeException(e); } } private static final SingleAcceptor<Void> getDefaultOnCloseAcceptor() { return v -> { }; } private static final SingleAcceptor<Void> getDefaultOnBackAcceptor() { return v -> { }; } private static void clipChildren(Region region) { final Rectangle outputClip = new Rectangle(); region.setClip(outputClip); region.layoutBoundsProperty().addListener((ov, oldValue, newValue) -> { outputClip.setWidth(newValue.getWidth()); outputClip.setHeight(newValue.getHeight()); }); } private FXMLLoader getLoader(UIComponentType component) { FXMLLoader loader = new FXMLLoader(getClass().getResource(component.getAbsoluteLocation())); loader.setRoot(this); loader.setController(this); return loader; } @FXML private void initialize() { panes.addListener(this::handlePaneListChanges); circles.addListener(this::handleCircleListChanges); index.addListener(this::handleIndexChanges); progress.setProgress(0.0); progress.managedProperty().bind(progress.visibleProperty()); circleBox.managedProperty().bind(circleBox.visibleProperty()); back.managedProperty().bind(back.visibleProperty()); close.managedProperty().bind(close.visibleProperty()); orientation.addListener((obs, o, n) -> { if (n == null) orientation.set(o); // prevent null values }); layoutBoundsProperty().addListener((obs, o, n) -> { initLayout(); initPanelOpacity(); }); if (isUsePanelClipping()) clipChildren(this); setOnTouchPressed(this::handleTouchPressed); setOnTouchMoved(this::handleTouchMoved); setOnTouchReleased(this::handleTouchReleased); setOnMousePressed(this::handleMousePressed); setOnMouseDragged(this::handleMouseDragged); setOnMouseReleased(this::handleMouseReleased); setOnKeyReleased(this::handleKeyReleased); nodeList.addAll(Arrays.asList(progress, circleBox, back, close)); back.setOnAction(e -> { onBackAcceptor.accept(null); }); close.setOnAction(e -> { onCloseAcceptor.accept(null); }); } public ProgressBar getProgress() { return progress; } public HBox getCircleBox() { return circleBox; } public Button getBack() { return back; } public Button getClose() { return close; } public final ObservableList<SwipePanePlaceholder<?>> getPanes() { return panes; } public final IntegerProperty indexProperty() { return index; } public final int getIndex() { return indexProperty().get(); } public final void setIndex(int index) { indexProperty().set(index); } public final ObjectProperty<Duration> durationProperty() { return duration; } public final Duration getDuration() { return durationProperty().get(); } public final void setDuration(Duration duration) { durationProperty().set(duration); } public final void setOnBackAcceptor(SingleAcceptor<Void> onBackAcceptor) { this.onBackAcceptor = onBackAcceptor == null ? getDefaultOnBackAcceptor() : onBackAcceptor; } public final void setOnCloseAcceptor(SingleAcceptor<Void> onCloseAcceptor) { this.onCloseAcceptor = onCloseAcceptor == null ? getDefaultOnCloseAcceptor() : onCloseAcceptor; } public final BooleanProperty progressVisibleProperty() { return progress.visibleProperty(); } public final boolean getProgressVisible() { return progressVisibleProperty().get(); } public final void setProgressVisible(boolean visible) { progressVisibleProperty().set(visible); } public final BooleanProperty circlesVisibleProperty() { return circleBox.visibleProperty(); } public final boolean getCirclesVisible() { return circlesVisibleProperty().get(); } public final void setCirclesVisible(boolean visible) { circlesVisibleProperty().set(visible); } public final BooleanProperty backVisibleProperty() { return back.visibleProperty(); } public final boolean getBackVisible() { return backVisibleProperty().get(); } public final void setBackVisible(boolean visible) { backVisibleProperty().set(visible); } public final BooleanProperty closeVisibleProperty() { return close.visibleProperty(); } public final boolean getCloseVisible() { return closeVisibleProperty().get(); } public final void setCloseVisible(boolean visible) { closeVisibleProperty().set(visible); } public final BooleanProperty useControlOpacityProperty() { return this.useControlOpacity; } public final boolean isUseControlOpacity() { return this.useControlOpacityProperty().get(); } public final void setUseControlOpacity(final boolean useControlOpacity) { this.useControlOpacityProperty().set(useControlOpacity); } public final BooleanProperty usePanelOpacityProperty() { return this.usePanelOpacity; } public final boolean isUsePanelOpacity() { return this.usePanelOpacityProperty().get(); } public final void setUsePanelOpacity(final boolean usePanelOpacity) { this.usePanelOpacityProperty().set(usePanelOpacity); } public final BooleanProperty usePanelClippingProperty() { return this.usePanelClipping; } public final boolean isUsePanelClipping() { return this.usePanelClippingProperty().get(); } public final void setUsePanelClipping(final boolean usePanelClipping) { this.usePanelClippingProperty().set(usePanelClipping); } public final ObjectProperty<Orientation> orientationProperty() { return this.orientation; } public final Orientation getOrientation() { return this.orientationProperty().get(); } public final void setOrientation(final Orientation orientation) { this.orientationProperty().set(orientation); } public final DoubleProperty scrollRestrictionProperty() { return this.scrollRestriction; } public final double getScrollRestriction() { return this.scrollRestrictionProperty().get(); } public final void setScrollRestriction(final double scrollRestriction) { this.scrollRestrictionProperty().set(scrollRestriction); } public LoadRestrictionType getLoadRestrictionType() { return loadRestrictionType; } public void setLoadRestrictionType(LoadRestrictionType loadRestrictionType) { if (loadRestrictionType == null) this.loadRestrictionType = LoadRestrictionType.ONE; else this.loadRestrictionType = loadRestrictionType; } private void handlePaneListChanges(ListChangeListener.Change<? extends SwipePanePlaceholder<?>> change) { while (change.next()) { List<? extends SwipePanePlaceholder<?>> removed = change.getRemoved(); for (SwipePanePlaceholder<?> pane : removed) { pane.setShow(false); int index = getChildren().indexOf(pane); SwipePaneCircleButton button = (SwipePaneCircleButton) circleBox.lookup("#" + index); if (button == null) continue; circles.remove(button); } getChildren().removeAll(removed); List<? extends SwipePanePlaceholder<?>> added = change.getAddedSubList(); int index = getChildren().indexOf(progress); getChildren().addAll(index, added); for (SwipePanePlaceholder<?> pane : added) { SwipePaneCircleButton b = new SwipePaneCircleButton(); b.setId("" + getChildren().indexOf(pane)); b.setOnAction(e -> { setIndex(Integer.parseInt(b.getId())); }); circles.add(b); pane.setCache(true); pane.setCacheHint(CacheHint.SPEED); } if (getIndex() == -1) setIndex(0); progress.setProgress(getIndex() / (panes.size() - 1.0)); } initLayout(); initPanelOpacity(); } private void handleCircleListChanges(ListChangeListener.Change<? extends SwipePaneCircleButton> change) { while (change.next()) { List<? extends SwipePaneCircleButton> removed = change.getRemoved(); circleBox.getChildren().removeAll(removed); List<? extends SwipePaneCircleButton> added = change.getAddedSubList(); circleBox.getChildren().addAll(added); } } private void handleIndexChanges(ObservableValue<? extends Number> obs, Number o, Number n) { // if (!drag) // initLayout(); final boolean _drag = drag; ParallelTransition parallel = new ParallelTransition(); parallel.setAutoReverse(false); parallel.setCycleCount(1); if (isUseControlOpacity()) { if (!_drag && back.isVisible()) buildOpacityTransition(parallel, back, back.getOpacity(), 0.0, 3.0, false); if (!_drag && close.isVisible()) buildOpacityTransition(parallel, close, close.getOpacity(), 0.0, 3.0, false); } for (int i = 0; i < circles.size(); i++) { circles.get(i).pseudoClassStateChanged(selected, i == getIndex()); if (Orientation.HORIZONTAL == getOrientation()) buildStandardXTransitions(parallel); else if (Orientation.VERTICAL == getOrientation()) buildStandardYTransitions(parallel); } if (isUseControlOpacity()) { if (back.isVisible()) buildOpacityTransition(parallel, back, back.getOpacity(), 1.0, _drag ? 1.0 : 3.0, _drag ? false : true); if (close.isVisible()) buildOpacityTransition(parallel, close, close.getOpacity(), 1.0, _drag ? 1.0 : 3.0, _drag ? false : true); } buildProgressTransition(parallel); parallel.playFromStart(); parallel.setOnFinished(e -> { int index = n.intValue(); if (panes.size() > 0) { for (int i = 0; i < panes.size(); i++) { // panes.get(i).setShow(i == index - 1 || i == index || i == index + 1); // panes.get(i).setShow(i == index); panes.get(i).setShow(showPageOnIndex(index, i)); panes.get(i).setCache(i == index ? false : true); panes.get(i).setCacheHint(i == index ? CacheHint.DEFAULT : CacheHint.SPEED); } panes.get(index).requestFocus(); } }); } private boolean showPageOnIndex(int current, int index) { if (index == current) return true; LoadRestrictionType type = loadRestrictionType == null ? LoadRestrictionType.ONE : loadRestrictionType; int value = type.value; for (int i = current - value; i <= current + value; i++) { if (index == i) return true; } return false; } private void initLayout() { int index = getIndex() * -1; for (Node child : getChildren()) { if (nodeList.contains(child)) continue; if (Orientation.HORIZONTAL == getOrientation()) child.setTranslateX(index * getWidth()); else if (Orientation.VERTICAL == getOrientation()) child.setTranslateY(index * getHeight()); index++; } if (!panesInitialized && panes.size() > 0) { circles.get(getIndex()).pseudoClassStateChanged(selected, true); progress.setProgress(getIndex() / (panes.size() - 1.0)); panesInitialized = true; } } private void initPanelOpacity() { for (Pane p : panes) { p.opacityProperty().unbind(); if (isUsePanelOpacity()) { if (Orientation.HORIZONTAL == getOrientation()) { DoubleBinding binding = Bindings.createDoubleBinding(() -> { double width = getWidth(); double translateX = p.getTranslateX(); double opacityBase = Math.abs(translateX) / (width + width / 3); // if (translateX < (-1.0 * width + width / 3) || translateX > (2 * (width / 3))) { // return 0.0; // } // if (translateX < (-1.0 * width + width / 3)) { // return 1.0 - opacityBase; // } else if (translateX > (2 * (width / 3))) { // return 1.0 - opacityBase; // } // return 1.0; return 1.0 - opacityBase; }, p.translateXProperty()); p.opacityProperty().bind(binding); } else if (Orientation.VERTICAL == getOrientation()) { // TODO } } } } private void handleTouchPressed(TouchEvent event) { if (Orientation.HORIZONTAL == getOrientation()) startX(event.getTouchPoint().getX()); else if (Orientation.VERTICAL == getOrientation()) startY(event.getTouchPoint().getY()); event.consume(); } private void handleTouchMoved(TouchEvent event) { if (Orientation.HORIZONTAL == getOrientation()) dragX(event.getTouchPoint().getX()); else if (Orientation.VERTICAL == getOrientation()) dragY(event.getTouchPoint().getY()); event.consume(); } private void handleTouchReleased(TouchEvent event) { if (Orientation.HORIZONTAL == getOrientation()) endX(event.getTouchPoint().getX()); else if (Orientation.VERTICAL == getOrientation()) endY(event.getTouchPoint().getY()); event.consume(); } private void handleMousePressed(MouseEvent event) { if (Orientation.HORIZONTAL == getOrientation()) startX(event.getX()); else if (Orientation.VERTICAL == getOrientation()) startY(event.getY()); event.consume(); } private void handleMouseDragged(MouseEvent event) { if (Orientation.HORIZONTAL == getOrientation()) dragX(event.getX()); else if (Orientation.VERTICAL == getOrientation()) dragY(event.getY()); event.consume(); } private void handleMouseReleased(MouseEvent event) { if (Orientation.HORIZONTAL == getOrientation()) endX(event.getX()); else if (Orientation.VERTICAL == getOrientation()) endY(event.getY()); event.consume(); } private void handleKeyReleased(KeyEvent event) { final int index = getIndex(); final int size = panes.size(); if (Orientation.HORIZONTAL == orientation.get()) { if (KeyCode.LEFT == event.getCode() || KeyCode.KP_LEFT == event.getCode()) { if ((index - 1) >= 0) { setIndex(index - 1); event.consume(); } } else if (KeyCode.RIGHT == event.getCode() || KeyCode.KP_RIGHT == event.getCode()) { if ((index + 1) < size) { setIndex(index + 1); event.consume(); } } } else if (Orientation.VERTICAL == orientation.get()) { if (KeyCode.UP == event.getCode() || KeyCode.KP_UP == event.getCode()) { if ((index - 1) >= 0) { setIndex(index - 1); event.consume(); } } else if (KeyCode.DOWN == event.getCode() || KeyCode.KP_DOWN == event.getCode()) { if ((index + 1) < size) { setIndex(index + 1); event.consume(); } } } } private double getRelevantScrollRestriction() { double _global = getScrollRestriction(); int _index = getIndex(); double global = _global > 1.0 ? 1.0 : _global; double pane; if (panes == null || panes.isEmpty() || _index < 0 || _index >= panes.size() || panes.get(_index) == null) pane = global; else pane = panes.get(_index).getScrollRestriction() > 1.0 ? 1.0 : panes.get(_index).getScrollRestriction(); return Math.min(global, pane); } private void startX(double x) { if (drag) return; double width = getWidth(); double tolerance = width * getRelevantScrollRestriction(); if (x > tolerance && x < (width - tolerance)) return; // LOG.info(String.format(Locale.ROOT, "[START] x=%.2f / current-index=%d", x, getIndex())); drag = true; dragX = x; paneToTranslateXMapping.clear(); iterateChildren(child -> paneToTranslateXMapping.put(child, child.getTranslateX())); } private void startY(double y) { if (drag) return; double height = getHeight(); double tolerance = height * getRelevantScrollRestriction(); if (y > tolerance && y < (height - tolerance)) return; // LOG.info(String.format(Locale.ROOT, "[START] y=%.2f / current-index=%d", y, getIndex())); drag = true; dragY = y; paneToTranslateYMapping.clear(); iterateChildren(child -> paneToTranslateYMapping.put(child, child.getTranslateY())); } private void dragX(double x) { if (!drag) return; double deltaX = dragX - x; double mult = deltaX < 0 ? -1.0 : 1.0; double width = getWidth(); // LOG.info(String.format(Locale.ROOT, "[INTERMEDIATE] deltaX=%.2f / mult=%.1f / current-index=%d", deltaX, mult, getIndex())); double opacityBase = Math.abs(deltaX) / (width / 3); double controlOpacity = 1.0 - opacityBase; if (deltaX < 0) { // drag right // we are already at the most left node if (getIndex() == 0 && (Math.abs(deltaX) > getWidth() / 5)) { deltaX = mult * getWidth() / 5; } else if (Math.abs(deltaX) > getWidth()) { deltaX = mult * getWidth(); } } else { // drag left // we are already at the most right node if (getIndex() == panes.size() - 1 && (Math.abs(deltaX) > getWidth() / 5)) { deltaX = mult * getWidth() / 5; } else if (Math.abs(deltaX) > getWidth()) { deltaX = mult * getWidth(); } } if (isUseControlOpacity()) { if (back.isVisible()) back.setOpacity(controlOpacity); if (close.isVisible()) close.setOpacity(controlOpacity); } final double dX = deltaX; iterateChildren(child -> { Double d = paneToTranslateXMapping.get(child); if (d != null) child.setTranslateX(d - dX); }); } private void dragY(double y) { if (!drag) return; double deltaY = dragY - y; double mult = deltaY < 0 ? -1.0 : 1.0; double height = getHeight(); // LOG.info(String.format(Locale.ROOT, "[INTERMEDIATE] deltaY=%.2f / mult=%.1f / current-index=%d", deltaY, mult, getIndex())); double opacityBase = Math.abs(deltaY) / (height / 3); double controlOpacity = 1.0 - opacityBase; if (deltaY < 0) { // drag right // we are already at the topmost node if (getIndex() == 0 && (Math.abs(deltaY) > getHeight() / 5)) { deltaY = mult * getHeight() / 5; } else if (Math.abs(deltaY) > getHeight()) { deltaY = mult * getHeight(); } } else { // drag left // we are already at the most bottom node if (getIndex() == panes.size() - 1 && (Math.abs(deltaY) > getHeight() / 5)) { deltaY = mult * getHeight() / 5; } else if (Math.abs(deltaY) > getHeight()) { deltaY = mult * getHeight(); } } if (isUseControlOpacity()) { if (back.isVisible()) back.setOpacity(controlOpacity); if (close.isVisible()) close.setOpacity(controlOpacity); } final double dY = deltaY; iterateChildren(child -> { Double d = paneToTranslateYMapping.get(child); if (d != null) child.setTranslateY(d - dY); }); } private void endX(double x) { if (!drag) return; ParallelTransition parallel = new ParallelTransition(); parallel.setAutoReverse(false); parallel.setCycleCount(1); double deltaX = dragX - x; double width = getWidth(); boolean snap = Math.abs(deltaX) >= (width / 3); // LOG.info(String.format(Locale.ROOT, "[END] deltaX=%.2f / parent-width=%.2f / current-index=%d / snap?=%b", deltaX, width, getIndex(), // snap)); if (deltaX < 0) { // drag right // we are already at the most left node if (getIndex() == 0) { buildStandardXTransitions(parallel); } // snap to next node on the left else if (snap) { setIndex(getIndex() - 1); } // return to original position else { buildReturnToStartXTransitions(parallel); } } else { // drag left // we are already at the most right node if (getIndex() == panes.size() - 1) { buildStandardXTransitions(parallel); } // snap to next node on the right else if (snap) { setIndex(getIndex() + 1); } // return to original position else { buildReturnToStartXTransitions(parallel); } } if (isUseControlOpacity()) { if (back.isVisible()) buildOpacityTransition(parallel, back, back.getOpacity(), 1.0, 1.0, false); if (close.isVisible()) buildOpacityTransition(parallel, close, close.getOpacity(), 1.0, 1.0, false); } buildProgressTransition(parallel); if (!parallel.getChildren().isEmpty()) parallel.playFromStart(); drag = false; dragX = 0.0; paneToTranslateXMapping.clear(); } private void endY(double y) { if (!drag) return; ParallelTransition parallel = new ParallelTransition(); parallel.setAutoReverse(false); parallel.setCycleCount(1); double deltaY = dragY - y; double height = getHeight(); boolean snap = Math.abs(deltaY) >= (height / 3); // LOG.info(String.format(Locale.ROOT, "[END] deltaY=%.2f / parent-height=%.2f / current-index=%d / snap?=%b", deltaY, height, getIndex(), // snap)); if (deltaY < 0) { // drag right // we are already at the most left node if (getIndex() == 0) { buildStandardYTransitions(parallel); } // snap to next node on the left else if (snap) { setIndex(getIndex() - 1); } // return to original position else { buildReturnToStartYTransitions(parallel); } } else { // drag left // we are already at the most right node if (getIndex() == panes.size() - 1) { buildStandardYTransitions(parallel); } // snap to next node on the right else if (snap) { setIndex(getIndex() + 1); } // return to original position else { buildReturnToStartYTransitions(parallel); } } if (isUseControlOpacity()) { if (back.isVisible()) buildOpacityTransition(parallel, back, back.getOpacity(), 1.0, 1.0, false); if (close.isVisible()) buildOpacityTransition(parallel, close, close.getOpacity(), 1.0, 1.0, false); } buildProgressTransition(parallel); if (!parallel.getChildren().isEmpty()) parallel.playFromStart(); drag = false; dragY = 0.0; paneToTranslateYMapping.clear(); } private void iterateChildren(SingleAcceptor<Node> acceptor) { for (Node child : getChildren()) { if (nodeList.contains(child)) continue; acceptor.accept(child); } } private void buildStandardXTransitions(final ParallelTransition parallel) { int index = getIndex() * -1; for (Node child : getChildren()) { if (nodeList.contains(child)) continue; parallel.getChildren().add(buildTranslateXTransition(child, child.getTranslateX(), index * getWidth())); index++; } } private void buildReturnToStartXTransitions(final ParallelTransition parallel) { iterateChildren(child -> { Double d = paneToTranslateXMapping.get(child); if (d != null) { parallel.getChildren().add(buildTranslateXTransition(child, child.getTranslateX(), d)); } }); } private TranslateTransition buildTranslateXTransition(Node child, double fromValue, double toValue) { TranslateTransition tr = new TranslateTransition(getDuration(), child); tr.setAutoReverse(false); tr.setCycleCount(1); tr.setFromX(fromValue); tr.setToX(toValue); return tr; } private void buildStandardYTransitions(final ParallelTransition parallel) { int index = getIndex() * -1; for (Node child : getChildren()) { if (nodeList.contains(child)) continue; parallel.getChildren().add(buildTranslateYTransition(child, child.getTranslateY(), index * getHeight())); index++; } } private void buildReturnToStartYTransitions(final ParallelTransition parallel) { iterateChildren(child -> { Double d = paneToTranslateYMapping.get(child); if (d != null) { parallel.getChildren().add(buildTranslateYTransition(child, child.getTranslateY(), d)); } }); } private TranslateTransition buildTranslateYTransition(Node child, double fromValue, double toValue) { TranslateTransition tr = new TranslateTransition(getDuration(), child); tr.setAutoReverse(false); tr.setCycleCount(1); tr.setFromY(fromValue); tr.setToY(toValue); return tr; } private void buildOpacityTransition(ParallelTransition parallel, Node target, double fromValue, double toValue, double durationDivisor, boolean useDelay) { Duration duration = getDuration().divide(durationDivisor); Duration delay = useDelay ? getDuration().subtract(getDuration().divide(durationDivisor)) : Duration.ZERO; FadeTransition tr = new FadeTransition(duration, target); tr.setDelay(delay); tr.setAutoReverse(false); tr.setCycleCount(1); tr.setFromValue(fromValue); tr.setToValue(toValue); parallel.getChildren().add(tr); } private void buildProgressTransition(final ParallelTransition parallel) { if (panes.size() > 0 && (panes.size() - 1.0) > 0) { ProgressTranistion progress = new ProgressTranistion(this.progress); progress.setDuration(getDuration()); progress.setAutoReverse(false); progress.setCycleCount(1); progress.setFrom(this.progress.getProgress()); progress.setTo(getIndex() / (panes.size() - 1.0)); parallel.getChildren().add(progress); } } public enum LoadRestrictionType { // @formatter:off ONE(0), // default, most aggressive - loads only the current page THREE(1), // load current page and max one to the left and right of it FIVE(2); // load current page and max two to the left and right of it // @formatter:on private final int value; private LoadRestrictionType(final int value) { this.value = value; } public int getValue() { return value; } } }
package utilityClasses; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Scanner; import java.lang.Class; public class ScoreInfo { private String gameName; private File gameScores; private File gamePeople; public ScoreInfo(String gN) { gameName = gN; gameScores = new File("Library/Application Support/Stoffel/Games/Infofiles/" + gameName.concat("Scores.txt")); gamePeople = new File("Library/Application Support/Stoffel/Games/Infofiles/" + gameName.concat("People.txt")); // gameScores = new File("Infofiles/" + gameName.concat("Scores.txt")); // gamePeople = new File("Infofiles/" + gameName.concat("People.txt")); } public void setScores(int score, String person) { try { if (!gameScores.exists()) { gameScores.getParentFile().mkdirs(); gameScores.createNewFile(); } if (!gamePeople.exists()) { gamePeople.getParentFile().mkdirs(); gamePeople.createNewFile(); } Scanner scoreContents = new Scanner(gameScores); // Scanner scoreContents = new Scanner(new File(getClass().getResource(gameScores))); ArrayList<Integer> scores = new ArrayList<Integer>(); while (scoreContents.hasNext()) { scores.add(Integer.parseInt(scoreContents.next())); } scores.add(score); // /////////////////////////////////////////////////////////// Scanner peopleContents = new Scanner(gamePeople); ArrayList<String> people = new ArrayList<String>(); while (peopleContents.hasNext()) { people.add(peopleContents.next()); } people.add(person); ArrayList<String[]> results = scoreOrder(scores, people); PrintWriter scoreWriter = new PrintWriter( new FileWriter(gameScores)); PrintWriter peopleWriter = new PrintWriter(new FileWriter( gamePeople)); for (String[] sp : results) { scoreWriter.println(sp[0]); peopleWriter.println(sp[1]); } peopleWriter.flush(); scoreWriter.flush(); peopleWriter.close(); scoreWriter.close(); scoreContents.close(); peopleContents.close(); } catch (IOException e) { } } public ArrayList<String[]> getScores() { try { Scanner scoreContents = new Scanner(gameScores); ArrayList<Integer> scores = new ArrayList<Integer>(); while (scoreContents.hasNext()) { scores.add(Integer.parseInt(scoreContents.next())); } Scanner peopleContents = new Scanner(gamePeople); ArrayList<String> people = new ArrayList<String>(); while (peopleContents.hasNext()) { people.add(peopleContents.next()); } ArrayList<String[]> results = new ArrayList<String[]>(); for (int i = 0; i < people.size(); i++) { String[] hs = { scores.get(i).toString(), people.get(i) }; results.add(hs); } scoreContents.close(); peopleContents.close(); return results; } catch (FileNotFoundException e) { ArrayList<String[]> n = new ArrayList<String[]>(); String[] m = { "45", "Brady" }; n.add(m); return n; } } public ArrayList<String[]> scoreOrder(ArrayList<Integer> scores, ArrayList<String> people) { ArrayList<String[]> results = new ArrayList<String[]>(); for (int i = 0; i < people.size(); i++) { String[] sp = { scores.get(i).toString(), people.get(i) }; results.add(sp); } Collections.sort(results, new Comparator<String[]>() { @Override public int compare(String[] person1, String[] person2) { return person1[1].compareTo(person2[1]); } }); Collections.sort(results, new Comparator<String[]>() { @Override public int compare(String[] score1, String[] score2) { return Integer.parseInt(score2[0]) - Integer.parseInt(score1[0]); } }); return results; } public void drawScoresHangman(Graphics g) { ArrayList<String[]> results = getScores(); g.setFont(new Font("Joystix", Font.BOLD, 17)); int i = 0; int yStart = 40; int xStart = 30; int lineH = 50; int l = 0; int r = 1; g.setColor(Color.WHITE); for (String[] c : results) { if (l > 12) { i++; l = 0; } int x = (340 * i) + xStart; String dots = ""; int m = String.valueOf(r).length(); // System.out.println(m); for (int n = 0; n < 11 - c[1].length() - m + 1; n++) { dots = dots.concat("."); } dots = dots.concat("."); // CenteredText.draw(c.toString(), 45, 8, g); // System.out.println(pIndex); // Color col = (pIndex == r - 1) ? Color.YELLOW : Color.WHITE; // g.setColor(col); g.drawString(r + ". " + c[1] + dots + c[0], x, (yStart - 2) + (l * lineH)); l++; r++; } } public void drawScores(Graphics g) { ArrayList<String[]> results = getScores(); g.setFont(new Font("Joystix", Font.BOLD, 13)); int i = 0; int yStart = 35; int xStart = 35; int lineH = 30; int l = 0; int r = 1; g.setColor(Color.WHITE); for (String[] c : results) { if (l > 16) { i++; l = 0; } int x = (250 * i) + xStart; String dots = ""; int m = String.valueOf(r).length(); // System.out.println(m); for (int n = 0; n < 11 - c[1].length() - m + 1; n++) { dots = dots.concat("."); } dots = dots.concat("."); // CenteredText lx = new CenteredText(c.toString(), 45, 8, g); // System.out.println(pIndex); // Color col = (pIndex == r - 1) ? Color.YELLOW : Color.WHITE; // g.setColor(col); g.drawString(r + ". " + c[1] + dots + c[0], x, (yStart - 2) + (l * lineH)); l++; r++; } } public void enterName(Graphics g, int wSW, int wSH, int score, String pName) { g.setFont(new Font("Joystix", Font.BOLD, 40)); CenteredText.draw("Enter", 100, g); CenteredText.draw("Your Name", 170, g); int barWidth = 35; int barSpace = 10 + barWidth; int tw = 450; int startText = (wSW - tw) / 2; g.setFont(new Font("Joystix", Font.BOLD, 20)); for (int i = 0; i < 10; i++) { if (pName.length() > i) { CenteredText.draw(Character.toString(pName.charAt(i)), new Rectangle((barSpace * i) + startText, 440, barWidth, 8), g); // g.drawString(Character.toString(pName.charAt(i)), (barSpace * i) // + startText + lx.x, 440); } g.fillRect((barSpace * i) + startText, 442, barWidth, 8); } } // public void verifyFile() { // // try { // gameScores.createNewFile(); // gamePeople.createNewFile(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // public static void main(String[] args) { // // ScoreInfo SI = new ScoreInfo("hole"); // ArrayList<String[]> scores = SI.getScores(); // SI.setScores(10, "BradyTest1"); // System.out.println(); // // } }
/* * Copyright (C) 2014 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.googlecode.eyesfree.utils; import android.content.Context; import android.graphics.Rect; import android.os.Build; import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; import android.text.TextUtils; import android.util.Log; import android.view.accessibility.AccessibilityNodeInfo.AccessibilityAction; import com.googlecode.eyesfree.compat.CompatUtils; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashSet; import java.util.LinkedList; import java.util.List; /** * Provides a series of utilities for interacting with AccessibilityNodeInfo * objects. NOTE: This class only recycles unused nodes that were collected * internally. Any node passed into or returned from a public method is retained * and TalkBack should recycle it when appropriate. * * @author caseyburkhardt@google.com (Casey Burkhardt) */ public class AccessibilityNodeInfoUtils { /** Whether isVisibleToUser() is supported by the current SDK. */ private static final boolean SUPPORTS_VISIBILITY = (Build.VERSION.SDK_INT >= 16); /** * Class for Samsung's TouchWiz implementation of AdapterView. May be * {@code null} on non-Samsung devices. */ private static final Class<?> CLASS_TOUCHWIZ_TWADAPTERVIEW = CompatUtils.getClass( "com.sec.android.touchwiz.widget.TwAdapterView"); /** * Class for Samsung's TouchWiz implementation of AbsListView. May be * {@code null} on non-Samsung devices. */ private static final Class<?> CLASS_TOUCHWIZ_TWABSLISTVIEW = CompatUtils.getClass( "com.sec.android.touchwiz.widget.TwAbsListView"); private AccessibilityNodeInfoUtils() { // This class is not instantiable. } /** * Gets the text of a <code>node</code> by returning the content description * (if available) or by returning the text. * * @param node The node. * @return The node text. */ public static CharSequence getNodeText(AccessibilityNodeInfoCompat node) { if (node == null) { return null; } // Prefer content description over text. // TODO: Why are we checking the trimmed length? final CharSequence contentDescription = node.getContentDescription(); if (!TextUtils.isEmpty(contentDescription) && (TextUtils.getTrimmedLength(contentDescription) > 0)) { return contentDescription; } final CharSequence text = node.getText(); if (!TextUtils.isEmpty(text) && (TextUtils.getTrimmedLength(text) > 0)) { return text; } return null; } /** * Returns the root node of the tree containing {@code node}. */ public static AccessibilityNodeInfoCompat getRoot(AccessibilityNodeInfoCompat node) { if (node == null) { return null; } AccessibilityNodeInfoCompat current = null; AccessibilityNodeInfoCompat parent = AccessibilityNodeInfoCompat.obtain(node); do { current = parent; parent = current.getParent(); } while (parent != null); return current; } /** * Returns whether a node should receive focus from focus traversal or touch * exploration. One of the following must be true: * <ul> * <li>The node is actionable (see * {@link #isActionableForAccessibility(AccessibilityNodeInfoCompat)})</li> * <li>The node is a top-level list item (see * {@link #isTopLevelScrollItem(Context, AccessibilityNodeInfoCompat)})</li> * </ul> * * @param node * @return {@code true} of the node is accessibility focusable. */ public static boolean isAccessibilityFocusable( Context context, AccessibilityNodeInfoCompat node) { if (node == null) { return false; } // Never focus invisible nodes. if (!isVisibleOrLegacy(node)) { return false; } // Always focus "actionable" nodes. if (isActionableForAccessibility(node)) { return true; } if ((Build.VERSION.SDK_INT < 16)) { // In pre-JellyBean, always focus ALL top-level list items and items // that should have independently focusable children. if (isTopLevelScrollItem(context, node)) { return true; } } else { // In post-JellyBean, only focus top-level list items with // non-actionable speaking children. if (isTopLevelScrollItem(context, node) && (isSpeakingNode(context, node) || hasNonActionableSpeakingChildren(context, node))) { return true; } } return false; } /** * Returns whether a node should receive accessibility focus from * navigation. This method should never be called recursively, since it * traverses up the parent hierarchy on every call. * * @see #findFocusFromHover(Context, AccessibilityNodeInfoCompat) */ public static boolean shouldFocusNode(Context context, AccessibilityNodeInfoCompat node) { if (node == null) { return false; } if (!isVisibleOrLegacy(node)) { LogUtils.log(AccessibilityNodeInfoUtils.class, Log.VERBOSE, "Don't focus, node is not visible"); return false; } if (FILTER_ACCESSIBILITY_FOCUSABLE.accept(context, node)) { // TODO: This may still result in focusing non-speaking nodes, but it // won't prevent unlabeled buttons from receiving focus. if (node.getChildCount() <= 0) { LogUtils.log(AccessibilityNodeInfoUtils.class, Log.VERBOSE, "Focus, node is focusable and has no children"); return true; } else if (isSpeakingNode(context, node)) { LogUtils.log(AccessibilityNodeInfoUtils.class, Log.VERBOSE, "Focus, node is focusable and has something to speak"); return true; } else { LogUtils.log(AccessibilityNodeInfoUtils.class, Log.VERBOSE, "Don't focus, node is focusable but has nothing to speak"); return false; } } // If this node has no focusable ancestors, but it still has text, // then it should receive focus from navigation and be read aloud. if (!hasMatchingAncestor(context, node, FILTER_ACCESSIBILITY_FOCUSABLE) && hasText(node)) { LogUtils.log(AccessibilityNodeInfoUtils.class, Log.VERBOSE, "Focus, node has text and no focusable ancestors"); return true; } LogUtils.log(AccessibilityNodeInfoUtils.class, Log.VERBOSE, "Don't focus, failed all focusability tests"); return false; } /** * Returns the node that should receive focus from hover by starting from * the touched node and calling {@link #shouldFocusNode} at each level of * the view hierarchy. */ public static AccessibilityNodeInfoCompat findFocusFromHover( Context context, AccessibilityNodeInfoCompat touched) { return AccessibilityNodeInfoUtils.getSelfOrMatchingAncestor( context, touched, FILTER_SHOULD_FOCUS); } private static boolean isSpeakingNode(Context context, AccessibilityNodeInfoCompat node) { if (hasText(node)) { LogUtils.log(AccessibilityNodeInfoUtils.class, Log.VERBOSE, "Speaking, has text"); return true; } // Special case for check boxes. if (node.isCheckable()) { LogUtils.log(AccessibilityNodeInfoUtils.class, Log.VERBOSE, "Speaking, is checkable"); return true; } // Special case for web content. if (WebInterfaceUtils.supportsWebActions(node)) { LogUtils.log(AccessibilityNodeInfoUtils.class, Log.VERBOSE, "Speaking, has web content"); return true; } // Special case for containers with non-focusable content. if (hasNonActionableSpeakingChildren(context, node)) { LogUtils.log(AccessibilityNodeInfoUtils.class, Log.VERBOSE, "Speaking, has non-actionable speaking children"); return true; } return false; } private static boolean hasNonActionableSpeakingChildren( Context context, AccessibilityNodeInfoCompat node) { final int childCount = node.getChildCount(); AccessibilityNodeInfoCompat child = null; // Has non-actionable, speaking children? for (int i = 0; i < childCount; i++) { try { child = node.getChild(i); if (child == null) { LogUtils.log(AccessibilityNodeInfoUtils.class, Log.VERBOSE, "Child %d is null, skipping it", i); continue; } // Ignore invisible nodes. if (!isVisibleOrLegacy(child)) { LogUtils.log(AccessibilityNodeInfoUtils.class, Log.VERBOSE, "Child %d is invisible, skipping it", i); continue; } // Ignore focusable nodes. if (FILTER_ACCESSIBILITY_FOCUSABLE.accept(context, child)) { LogUtils.log(AccessibilityNodeInfoUtils.class, Log.VERBOSE, "Child %d is focusable, skipping it", i); continue; } // Recursively check non-focusable child nodes. // TODO: Mutual recursion is probably not a good idea. if (isSpeakingNode(context, child)) { LogUtils.log(AccessibilityNodeInfoUtils.class, Log.VERBOSE, "Does have actionable speaking children (child %d)", i); return true; } } finally { AccessibilityNodeInfoUtils.recycleNodes(child); } } LogUtils.log(AccessibilityNodeInfoUtils.class, Log.VERBOSE, "Does not have non-actionable speaking children"); return false; } /** * Returns whether a node is actionable. That is, the node supports one of * the following actions: * <ul> * <li>{@link AccessibilityNodeInfoCompat#isClickable()} * <li>{@link AccessibilityNodeInfoCompat#isFocusable()} * <li>{@link AccessibilityNodeInfoCompat#isLongClickable()} * </ul> * This parities the system method View#isActionableForAccessibility(), which * was added in JellyBean. * * @param node The node to examine. * @return {@code true} if node is actionable. */ public static boolean isActionableForAccessibility(AccessibilityNodeInfoCompat node) { if (node == null) { return false; } // Nodes that are clickable are always actionable. if (isClickable(node) || isLongClickable(node)) { return true; } if (node.isFocusable()) { return true; } return supportsAnyAction(node, AccessibilityNodeInfoCompat.ACTION_FOCUS, AccessibilityNodeInfoCompat.ACTION_NEXT_HTML_ELEMENT, AccessibilityNodeInfoCompat.ACTION_PREVIOUS_HTML_ELEMENT); } public static boolean isSelfOrAncestorFocused( Context context, AccessibilityNodeInfoCompat node) { if (node == null) { return false; } if (node.isAccessibilityFocused()) { return true; } else { return hasMatchingAncestor(context, node, new NodeFilter() { @Override public boolean accept(Context context, AccessibilityNodeInfoCompat node) { return node.isAccessibilityFocused(); } }); } } /** * Returns whether a node is clickable. That is, the node supports at least one of the * following: * <ul> * <li>{@link AccessibilityNodeInfoCompat#isClickable()}</li> * <li>{@link AccessibilityNodeInfoCompat#ACTION_CLICK}</li> * </ul> * * @param node The node to examine. * @return {@code true} if node is clickable. */ public static boolean isClickable(AccessibilityNodeInfoCompat node) { if (node == null) { return false; } if (node.isClickable()) { return true; } return supportsAnyAction(node, AccessibilityNodeInfoCompat.ACTION_CLICK); } /** * Returns whether a node is long clickable. That is, the node supports at least one of the * following: * <ul> * <li>{@link AccessibilityNodeInfoCompat#isLongClickable()}</li> * <li>{@link AccessibilityNodeInfoCompat#ACTION_LONG_CLICK}</li> * </ul> * * @param node The node to examine. * @return {@code true} if node is long clickable. */ public static boolean isLongClickable(AccessibilityNodeInfoCompat node) { if (node == null) { return false; } if (node.isLongClickable()) { return true; } return supportsAnyAction(node, AccessibilityNodeInfoCompat.ACTION_LONG_CLICK); } /** * Check whether a given node has a scrollable ancestor. * * @param node The node to examine. * @return {@code true} if one of the node's ancestors is scrollable. */ private static boolean hasMatchingAncestor( Context context, AccessibilityNodeInfoCompat node, NodeFilter filter) { if (node == null) { return false; } final AccessibilityNodeInfoCompat result = getMatchingAncestor(context, node, filter); if (result == null) { return false; } result.recycle(); return true; } /** * Returns the {@code node} if it matches the {@code filter}, or the first * matching ancestor. Returns {@code null} if no nodes match. */ public static AccessibilityNodeInfoCompat getSelfOrMatchingAncestor( Context context, AccessibilityNodeInfoCompat node, NodeFilter filter) { if (node == null) { return null; } if (filter.accept(context, node)) { return AccessibilityNodeInfoCompat.obtain(node); } return getMatchingAncestor(context, node, filter); } /** * Returns the first ancestor of {@code node} that matches the * {@code filter}. Returns {@code null} if no nodes match. */ private static AccessibilityNodeInfoCompat getMatchingAncestor( Context context, AccessibilityNodeInfoCompat node, NodeFilter filter) { if (node == null) { return null; } final HashSet<AccessibilityNodeInfoCompat> ancestors = new HashSet<AccessibilityNodeInfoCompat>(); try { ancestors.add(AccessibilityNodeInfoCompat.obtain(node)); node = node.getParent(); while (node != null) { if (!ancestors.add(node)) { // Already seen this node, so abort! node.recycle(); return null; } if (filter.accept(context, node)) { // Send a copy since node gets recycled. return AccessibilityNodeInfoCompat.obtain(node); } node = node.getParent(); } } finally { recycleNodes(ancestors); } return null; } /** * Check whether a given node is scrollable. * * @param node The node to examine. * @return {@code true} if the node is scrollable. */ private static boolean isScrollable(AccessibilityNodeInfoCompat node) { if (node.isScrollable()) { return true; } return supportsAnyAction(node, AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD, AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD); } /** * Returns whether the specified node has text. * * @param node The node to check. * @return {@code true} if the node has text. */ private static boolean hasText(AccessibilityNodeInfoCompat node) { if (node == null) { return false; } return (!TextUtils.isEmpty(node.getText()) || !TextUtils.isEmpty(node.getContentDescription())); } /** * Determines whether a node is a top-level item in a scrollable container. * * @param node The node to test. * @return {@code true} if {@code node} is a top-level item in a scrollable * container. */ public static boolean isTopLevelScrollItem(Context context, AccessibilityNodeInfoCompat node) { if (node == null) { return false; } AccessibilityNodeInfoCompat parent = null; try { parent = node.getParent(); if (parent == null) { // Not a child node of anything. return false; } if (isScrollable(node)) { return true; } // AdapterView, ScrollView, and HorizontalScrollView are focusable // containers, but Spinner is a special case. // TODO: Rename or break up this method, since it actually returns // whether the parent is scrollable OR is a focusable container that // should not block its children from receiving focus. if (nodeMatchesAnyClassByType(context, parent, android.widget.AdapterView.class, android.widget.ScrollView.class, android.widget.HorizontalScrollView.class, CLASS_TOUCHWIZ_TWADAPTERVIEW) && !nodeMatchesAnyClassByType(context, parent, android.widget.Spinner.class)) { return true; } return false; } finally { recycleNodes(parent); } } /** * Determines if the current item is at the edge of a list by checking the * scrollable predecessors of the items on both sides. * * @param context The parent context. * @param node The node to check. * @return true if the current item is at the edge of a list. */ public static boolean isEdgeListItem(Context context, AccessibilityNodeInfoCompat node) { return isEdgeListItem(context, node, 0, null); } /** * Determines if the current item is at the edge of a list by checking the * scrollable predecessors of the items on either or both sides. * * @param context The parent context. * @param node The node to check. * @param direction The direction in which to check, one of: * <ul> * <li>{@code -1} to check backward * <li>{@code 0} to check both backward and forward * <li>{@code 1} to check forward * </ul> * @param filter (Optional) Filter used to validate list-type ancestors. * @return true if the current item is at the edge of a list. */ public static boolean isEdgeListItem( Context context, AccessibilityNodeInfoCompat node, int direction, NodeFilter filter) { if (node == null) { return false; } if ((direction <= 0) && isMatchingEdgeListItem(context, node, NodeFocusFinder.SEARCH_BACKWARD, FILTER_SCROLL_BACKWARD.and(filter))) { return true; } if ((direction >= 0) && isMatchingEdgeListItem(context, node, NodeFocusFinder.SEARCH_FORWARD, FILTER_SCROLL_FORWARD.and(filter))) { return true; } return false; } /** * Convenience method determining if the current item is at the edge of a * list and suitable autoscroll. Calls {@code isEdgeListItem} with * {@code FILTER_AUTO_SCROLL}. * * @param context The parent context. * @param node The node to check. * @param direction The direction in which to check, one of: * <ul> * <li>{@code -1} to check backward * <li>{@code 0} to check both backward and forward * <li>{@code 1} to check forward * </ul> * @return true if the current item is at the edge of a list. */ public static boolean isAutoScrollEdgeListItem( Context context, AccessibilityNodeInfoCompat node, int direction) { return isEdgeListItem(context, node, direction, FILTER_AUTO_SCROLL); } /** * Utility method for determining if a searching past a particular node will * fall off the edge of a scrollable container. * * @param cursor Node to check. * @param direction The direction in which to move from the cursor. * @param filter Filter used to validate list-type ancestors. * @return {@code true} if focusing search in the specified direction will * fall off the edge of the container. */ private static boolean isMatchingEdgeListItem(Context context, AccessibilityNodeInfoCompat cursor, int direction, NodeFilter filter) { AccessibilityNodeInfoCompat ancestor = null; AccessibilityNodeInfoCompat searched = null; AccessibilityNodeInfoCompat searchedAncestor = null; try { ancestor = getMatchingAncestor(null, cursor, filter); if (ancestor == null) { // Not contained in a scrollable list. return false; } // Search in the specified direction until we find a focusable node. // TODO: This happens elsewhere -- make into a single utility method. searched = NodeFocusFinder.focusSearch(cursor, direction); while ((searched != null) && !AccessibilityNodeInfoUtils.shouldFocusNode(context, searched)) { final AccessibilityNodeInfoCompat temp = searched; searched = NodeFocusFinder.focusSearch(temp, direction); temp.recycle(); } if ((searched == null) || searched.equals(ancestor)) { // Can't move from this position. return true; } searchedAncestor = getMatchingAncestor(null, searched, filter); if (!ancestor.equals(searchedAncestor)) { // Moves outside of the scrollable list. return true; } } finally { recycleNodes(ancestor, searched, searchedAncestor); } return false; } /** * Determines if the generating class of an * {@link AccessibilityNodeInfoCompat} matches a given {@link Class} by * type. * * @param node A sealed {@link AccessibilityNodeInfoCompat} dispatched by * the accessibility framework. * @param referenceClass A {@link Class} to match by type or inherited type. * @return {@code true} if the {@link AccessibilityNodeInfoCompat} object * matches the {@link Class} by type or inherited type, * {@code false} otherwise. */ public static boolean nodeMatchesClassByType( Context context, AccessibilityNodeInfoCompat node, Class<?> referenceClass) { if ((node == null) || (referenceClass == null)) { return false; } // Attempt to take a shortcut. final CharSequence nodeClassName = node.getClassName(); if (TextUtils.equals(nodeClassName, referenceClass.getName())) { return true; } final ClassLoadingManager loader = ClassLoadingManager.getInstance(); final CharSequence appPackage = node.getPackageName(); return loader.checkInstanceOf(context, nodeClassName, appPackage, referenceClass); } /** * Determines if the generating class of an * {@link AccessibilityNodeInfoCompat} matches any of the given * {@link Class}es by type. * * @param node A sealed {@link AccessibilityNodeInfoCompat} dispatched by * the accessibility framework. * @return {@code true} if the {@link AccessibilityNodeInfoCompat} object * matches the {@link Class} by type or inherited type, * {@code false} otherwise. * @param referenceClasses A variable-length list of {@link Class} objects * to match by type or inherited type. */ public static boolean nodeMatchesAnyClassByType( Context context, AccessibilityNodeInfoCompat node, Class<?>... referenceClasses) { for (Class<?> referenceClass : referenceClasses) { if (nodeMatchesClassByType(context, node, referenceClass)) { return true; } } return false; } /** * Determines if the class of an {@link AccessibilityNodeInfoCompat} matches * a given {@link Class} by package and name. * * @param node A sealed {@link AccessibilityNodeInfoCompat} dispatched by * the accessibility framework. * @param referenceClassName A class name to match. * @return {@code true} if the {@link AccessibilityNodeInfoCompat} matches * the class name. */ public static boolean nodeMatchesClassByName( Context context, AccessibilityNodeInfoCompat node, CharSequence referenceClassName) { if ((node == null) || (referenceClassName == null)) { return false; } // Attempt to take a shortcut. final CharSequence nodeClassName = node.getClassName(); if (TextUtils.equals(nodeClassName, referenceClassName)) { return true; } final ClassLoadingManager loader = ClassLoadingManager.getInstance(); final CharSequence appPackage = node.getPackageName(); return loader.checkInstanceOf(context, nodeClassName, appPackage, referenceClassName); } /** * Recycles the given nodes. * * @param nodes The nodes to recycle. */ public static void recycleNodes(Collection<AccessibilityNodeInfoCompat> nodes) { if (nodes == null) { return; } for (AccessibilityNodeInfoCompat node : nodes) { if (node != null) { node.recycle(); } } nodes.clear(); } /** * Recycles the given nodes. * * @param nodes The nodes to recycle. */ public static void recycleNodes(AccessibilityNodeInfoCompat... nodes) { if (nodes == null) { return; } for (AccessibilityNodeInfoCompat node : nodes) { if (node != null) { node.recycle(); } } } /** * Returns {@code true} if the node supports at least one of the specified * actions. To check whether a node supports multiple actions, combine them * using the {@code |} (logical OR) operator. * * @param node The node to check. * @param actions The actions to check. * @return {@code true} if at least one action is supported. */ public static boolean supportsAnyAction(AccessibilityNodeInfoCompat node, int... actions) { if (node != null) { final int supportedActions = node.getActions(); for (int action : actions) { if ((supportedActions & action) == action) { return true; } } } return false; } /** * Returns {@code true} if the node supports at least one of the specified actions. To check * whether a node supports multiple actions, combine them using the {@code |} (logical OR) * operator. * * <p>Note: this method will check against the getActions() method of AccessibilityNodeInfo, * which will not contain information for actions introduced in API level 21 or later. * * @param node The node to check. * @param actions The actions to check. * @return {@code true} if at least one action is supported. */ public static boolean supportsAnyAction(AccessibilityNodeInfoCompat node, AccessibilityAction... actions) { if (node != null) { // Unwrap the node and compare AccessibilityActions because AccessibilityActions, unlike // AccessibilityActionCompats, are static (so checks for equality work correctly). final List<AccessibilityAction> supportedActions = node.unwrap().getActionList(); for (AccessibilityAction action : actions) { if (supportedActions.contains(action)) { return true; } } } return false; } /** * Returns the result of applying a filter using breadth-first traversal. * * @param context The parent context. * @param node The root node to traverse from. * @param filter The filter to satisfy. * @return The first node reached via BFS traversal that satisfies the * filter. */ public static AccessibilityNodeInfoCompat searchFromBfs( Context context, AccessibilityNodeInfoCompat node, NodeFilter filter) { if (node == null) { return null; } final LinkedList<AccessibilityNodeInfoCompat> queue = new LinkedList<AccessibilityNodeInfoCompat>(); queue.add(AccessibilityNodeInfoCompat.obtain(node)); while (!queue.isEmpty()) { final AccessibilityNodeInfoCompat item = queue.removeFirst(); if (filter.accept(context, item)) { return AccessibilityNodeInfoCompat.obtain(item); } final int childCount = item.getChildCount(); for (int i = 0; i < childCount; i++) { final AccessibilityNodeInfoCompat child = item.getChild(i); if (child != null) { queue.addLast(child); } } } return null; } /** * Returns the result of applying a filter using breadth-first traversal. * * @param context The parent context. * @param node The root node to traverse from. * @param filter The filter to satisfy. * @param maxResults The number of results to stop searching after * @return Returns all nodes reached via BFS traversal that satisfies the * filter. */ public static List<AccessibilityNodeInfoCompat> searchAllFromBfs(Context context, AccessibilityNodeInfoCompat node, NodeFilter filter) { if (node == null) { return null; } final List<AccessibilityNodeInfoCompat> toReturn = new ArrayList<AccessibilityNodeInfoCompat>(); final LinkedList<AccessibilityNodeInfoCompat> queue = new LinkedList<AccessibilityNodeInfoCompat>(); queue.add(AccessibilityNodeInfoCompat.obtain(node)); while (!queue.isEmpty()) { final AccessibilityNodeInfoCompat item = queue.removeFirst(); if (filter.accept(context, item)) { toReturn.add(AccessibilityNodeInfoCompat.obtain(item)); } final int childCount = item.getChildCount(); for (int i = 0; i < childCount; i++) { final AccessibilityNodeInfoCompat child = item.getChild(i); if (child != null) { queue.addLast(child); } } } return toReturn; } /** * Performs in-order traversal from a given node in a particular direction * until a node matching the specified filter is reached. * * @param context The parent context. * @param root The root node to traverse from. * @param filter The filter to satisfy. * @return The first node reached via in-order traversal that satisfies the * filter. */ public static AccessibilityNodeInfoCompat searchFromInOrderTraversal( Context context, AccessibilityNodeInfoCompat root, NodeFilter filter, int direction) { AccessibilityNodeInfoCompat currentNode = NodeFocusFinder.focusSearch(root, direction); final HashSet<AccessibilityNodeInfoCompat> seenNodes = new HashSet<AccessibilityNodeInfoCompat>(); while ((currentNode != null) && !seenNodes.contains(currentNode) && !filter.accept(context, currentNode)) { seenNodes.add(currentNode); currentNode = NodeFocusFinder.focusSearch(currentNode, direction); } // Recycle all the seen nodes. AccessibilityNodeInfoUtils.recycleNodes(seenNodes); return currentNode; } /** * Returns a fresh copy of {@code node} with properties that are * less likely to be stale. Returns {@code null} if the node can't be * found anymore. */ public static AccessibilityNodeInfoCompat refreshNode( AccessibilityNodeInfoCompat node) { if (node == null) { return null; } AccessibilityNodeInfoCompat result = refreshFromChild(node); if (result == null) { result = refreshFromParent(node); } return result; } private static AccessibilityNodeInfoCompat refreshFromChild( AccessibilityNodeInfoCompat node) { if (node.getChildCount() > 0) { AccessibilityNodeInfoCompat firstChild = node.getChild(0); if (firstChild != null) { AccessibilityNodeInfoCompat parent = firstChild.getParent(); firstChild.recycle(); if (node.equals(parent)) { return parent; } else { recycleNodes(parent); } } } return null; } private static AccessibilityNodeInfoCompat refreshFromParent( AccessibilityNodeInfoCompat node) { AccessibilityNodeInfoCompat parent = node.getParent(); if (parent != null) { try { int childCount = parent.getChildCount(); for (int i = 0; i < childCount; ++i) { AccessibilityNodeInfoCompat child = parent.getChild(i); if (node.equals(child)) { return child; } recycleNodes(child); } } finally { parent.recycle(); } } return null; } /** * Helper method that returns {@code true} if the specified node is visible * to the user or if the current SDK doesn't support checking visibility. */ public static boolean isVisibleOrLegacy(AccessibilityNodeInfoCompat node) { return (!AccessibilityNodeInfoUtils.SUPPORTS_VISIBILITY || node.isVisibleToUser()); } /** * Filter for scrollable items. One of the following must be true: * <ul> * <li>{@link AccessibilityNodeInfoCompat#isScrollable()} returns * {@code true}</li> * <li>{@link AccessibilityNodeInfoCompat#getActions()} supports * {@link AccessibilityNodeInfoCompat#ACTION_SCROLL_FORWARD}</li> * <li>{@link AccessibilityNodeInfoCompat#getActions()} supports * {@link AccessibilityNodeInfoCompat#ACTION_SCROLL_BACKWARD}</li> * </ul> */ public static final NodeFilter FILTER_SCROLLABLE = new NodeFilter() { @Override public boolean accept(Context context, AccessibilityNodeInfoCompat node) { return isScrollable(node); } }; private static final NodeFilter FILTER_ACCESSIBILITY_FOCUSABLE = new NodeFilter() { @Override public boolean accept(Context context, AccessibilityNodeInfoCompat node) { return isAccessibilityFocusable(context, node); } }; /** * Filter for items that should receive accessibility focus. Equivalent to * calling {@link #shouldFocusNode(Context, AccessibilityNodeInfoCompat)}. */ public static final NodeFilter FILTER_SHOULD_FOCUS = new NodeFilter() { @Override public boolean accept(Context context, AccessibilityNodeInfoCompat node) { return shouldFocusNode(context, node); } }; /** * Filter that defines which types of views should be auto-scrolled. Generally speaking, only * accepts views that are capable of showing partially-visible data. * * <p>Accepts the following classes (and sub-classes thereof): * * <ul> * <li>{@link android.widget.AbsListView} (and Samsung's TwAbsListView) * <li>{@link android.widget.AbsSpinner} * <li>{@link android.widget.ScrollView} * <li>{@link android.widget.HorizontalScrollView} * </ul> * * <p>Specifically excludes {@link android.widget.AdapterViewAnimator} and sub-classes, since they * represent overlapping views. Also excludes {@link androidx.viewpager.widget.ViewPager} since it * exclusively represents off-screen views. */ private static final NodeFilter FILTER_AUTO_SCROLL = new NodeFilter() { @Override public boolean accept(Context context, AccessibilityNodeInfoCompat node) { return AccessibilityNodeInfoUtils.nodeMatchesAnyClassByType( context, node, android.widget.AbsListView.class, android.widget.AbsSpinner.class, android.widget.ScrollView.class, android.widget.HorizontalScrollView.class, CLASS_TOUCHWIZ_TWABSLISTVIEW); } }; private static final NodeActionFilter FILTER_SCROLL_FORWARD = new NodeActionFilter( AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD); private static final NodeActionFilter FILTER_SCROLL_BACKWARD = new NodeActionFilter( AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD); /** * Convenience class for a {@link NodeFilter} that checks whether nodes * support a specific action or set of actions. */ private static class NodeActionFilter extends NodeFilter { private final int mAction; /** * Creates a new action filter with the specified action mask. * * @param actionMask The bit mask of actions to accept. */ public NodeActionFilter(int actionMask) { mAction = actionMask; } @Override public boolean accept(Context context, AccessibilityNodeInfoCompat node) { return ((node.getActions() & mAction) == mAction); } } /** * Compares two AccessibilityNodeInfos in left-to-right and top-to-bottom * fashion. */ public static class TopToBottomLeftToRightComparator implements Comparator<AccessibilityNodeInfoCompat> { private final Rect mFirstBounds = new Rect(); private final Rect mSecondBounds = new Rect(); private static final int BEFORE = -1; private static final int AFTER = 1; @Override public int compare(AccessibilityNodeInfoCompat first, AccessibilityNodeInfoCompat second) { final Rect firstBounds = mFirstBounds; first.getBoundsInScreen(firstBounds); final Rect secondBounds = mSecondBounds; second.getBoundsInScreen(secondBounds); // First is entirely above second. if (firstBounds.bottom <= secondBounds.top) { return BEFORE; } // First is entirely below second. if (firstBounds.top >= secondBounds.bottom) { return AFTER; } // Smaller left-bound. final int leftDifference = (firstBounds.left - secondBounds.left); if (leftDifference != 0) { return leftDifference; } // Smaller top-bound. final int topDifference = (firstBounds.top - secondBounds.top); if (topDifference != 0) { return topDifference; } // Smaller bottom-bound. final int bottomDifference = (firstBounds.bottom - secondBounds.bottom); if (bottomDifference != 0) { return bottomDifference; } // Smaller right-bound. final int rightDifference = (firstBounds.right - secondBounds.right); if (rightDifference != 0) { return rightDifference; } // Just break the tie somehow. The hash codes are unique // and stable, hence this is deterministic tie breaking. return first.hashCode() - second.hashCode(); } } }
package com.teambox.client.ui.fragments; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.List; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.teambox.client.Application; import com.teambox.client.R; import com.teambox.client.Utilities; import com.teambox.client.db.AccountTable; import com.teambox.client.ui.activities.MainActivity; /** * Fragment which contains and manages account info * * @author Joan Fuentes * */ public class ProfileSummaryFragment extends BaseFragment { private class LoadDataInViewsAsyncTask extends AsyncTask<Void, Void, AccountTable> { @Override protected AccountTable doInBackground(Void... params) { return getInfoToShow(); } private AccountTable getInfoToShow() { List<AccountTable> accounts = AccountTable .listAll(AccountTable.class); if (accounts.size() > 0) { return accounts.get(0); } return null; } @Override protected void onPostExecute(AccountTable account) { if (account != null) { mAccountUser = account; refreshInfoInViews(account); } } } private class LoadProfilePhotoAsyncTask extends AsyncTask<Void, Bitmap, Bitmap> { @Override protected Bitmap doInBackground(Void... params) { Bitmap image = null; if (mAccountUser.profileAvatarUrlCached == null) { image = downloadImageAndUpdateDB(); } else if (mAccountUser.profileAvatarUrlCached .equalsIgnoreCase(mAccountUser.profileAvatarUrl)) { image = getCachedBitmap(image); } else { // Load the current image but continue downloading the new image image = getCachedBitmap(image); publishProgress(image); image = downloadImageAndUpdateDB(); } return image; } private Bitmap downloadImageAndUpdateDB() { Bitmap image; image = Utilities.getBitmapFromURL(mAccountUser.profileAvatarUrl); if (image != null) { File file = saveFileInCache(image); updateCachedImageInDBRecord(file); } return image; } private Bitmap getCachedBitmap(Bitmap image) { File file = new File(getActivity().getCacheDir(), mAccountUser.profileAvatarUrlLocalFile); try { FileInputStream is = new FileInputStream(file); image = BitmapFactory.decodeStream(is); is.close(); } catch (Exception e) { e.printStackTrace(); } return image; } public File getTempFile(Context context, String name) { File file = null; try { file = File.createTempFile(name, null, context.getCacheDir()); } catch (IOException e) { // Error while creating file } return file; } @Override protected void onPostExecute(Bitmap image) { if (image != null) { mImageViewProfilePhoto.setImageBitmap(image); } } @Override protected void onProgressUpdate(Bitmap... image) { super.onProgressUpdate(image); if (image != null) { mImageViewProfilePhoto.setImageBitmap(image[0]); } } private File saveFileInCache(Bitmap image) { File file = getTempFile(getActivity(), "profile_picture"); try { FileOutputStream out = new FileOutputStream(file); image.compress(Bitmap.CompressFormat.PNG, 90, out); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } return file; } private void updateCachedImageInDBRecord(File file) { mAccountUser.profileAvatarUrlCached = mAccountUser.profileAvatarUrl; mAccountUser.profileAvatarUrlLocalFile = file.getName(); mAccountUser.save(); } } private TextView mTextViewName; private TextView mTextViewEmail; private ImageView mImageViewProfilePhoto; private AccountTable mAccountUser; private LoadProfilePhotoAsyncTask mLoadProfilePhotoAsyncTask; private LoadDataInViewsAsyncTask mLoadDataInViewsAsyncTask; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setupActionBar(); refreshDataInViews(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_profile_summary, container, false); mTextViewName = (TextView) view.findViewById(R.id.textViewName); mTextViewEmail = (TextView) view.findViewById(R.id.textViewEmail); mImageViewProfilePhoto = (ImageView) view .findViewById(R.id.imageViewProfilePhoto); ((Button) view.findViewById(R.id.buttonLogout)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Application.processLogout(getActivity(), getFragmentManager()); } }); return view; } @Override public void onStop() { if (mLoadProfilePhotoAsyncTask != null) mLoadProfilePhotoAsyncTask.cancel(true); if (mLoadDataInViewsAsyncTask != null) mLoadDataInViewsAsyncTask.cancel(true); super.onStop(); } @Override public void refreshDataInViews() { mLoadDataInViewsAsyncTask = new LoadDataInViewsAsyncTask(); mLoadDataInViewsAsyncTask.execute(); } public void refreshInfoInViews(AccountTable account) { mTextViewName.setText(account.firstName + " " + account.lastName); mTextViewEmail.setText("( " + account.email + " )"); mLoadProfilePhotoAsyncTask = new LoadProfilePhotoAsyncTask(); mLoadProfilePhotoAsyncTask.execute(); } private void setupActionBar() { final ActionBar actionBar = ((MainActivity) getActivity()) .getSupportActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); } }
/******************************************************************************* * Copyright (c) 2010 Haifeng Li * * 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 smile.data; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import smile.math.Math; import smile.math.SparseArray; import smile.math.matrix.SparseMatrix; /** * List of Lists sparse matrix format. LIL stores one list per row, * where each entry stores a column index and value. Typically, these * entries are kept sorted by column index for faster lookup. * This format is good for incremental matrix construction. * <p> * LIL is typically used to construct the matrix. Once the matrix is * constructed, it is typically converted to a format, such as Harwell-Boeing * column-compressed sparse matrix format, which is more efficient for matrix * operations. * * @author Haifeng Li */ public class SparseDataset implements Iterable<Datum<SparseArray>> { /** * The name of dataset. */ private String name; /** * The optional detailed description of dataset. */ private String description; /** * The attribute property of response variable. null means no response variable. */ private Attribute response = null; /** * The data objects. */ private List<Datum<SparseArray>> data = new ArrayList<Datum<SparseArray>>(); /** * The number of nonzero entries. */ private int n; /** * The number of columns. */ private int numColumns; /** * The number of nonzero entries in each column. */ private int[] colSize; /** * Constructor. */ public SparseDataset() { this("Sparse Dataset"); } /** * Constructor. * @param name the name of dataset. */ public SparseDataset(String name) { this(name, null); } /** * Constructor. * @param response the attribute type of response variable. */ public SparseDataset(Attribute response) { this("SparseDataset", response); } /** * Constructor. * @param name the name of dataset. * @param response the attribute type of response variable. */ public SparseDataset(String name, Attribute response) { this.name = name; this.response = response; numColumns = 0; colSize = new int[100]; } /** * Constructor. * @param ncols the number of columns in the matrix. */ public SparseDataset(int ncols) { numColumns = ncols; colSize = new int[ncols]; } /** * Returns the dataset name. */ public String getName() { return name; } /** * Sets the dataset name. */ public void setName(String name) { this.name = name; } /** * Sets the detailed dataset description. */ public void setDescription(String description) { this.description = description; } /** * Returns the detailed dataset description. */ public String getDescription() { return description; } /** * Returns the attribute of the response variable. null means no response * variable in this dataset. * @return the attribute of the response variable. null means no response * variable in this dataset. */ public Attribute response() { return response; } /** * Returns the size of dataset that is the number of rows. */ public int size() { return data.size(); } /** * Returns the number of columns. */ public int ncols() { return numColumns; } /** * Returns the number of nonzero entries. */ public int length() { return n; } /** * Set the class label of a datum. If the index * exceeds the current matrix size, the matrix will resize itself. * @param i the row index of entry. * @param y the class label or real-valued response of the datum. */ public void set(int i, int y) { if (response == null) { throw new IllegalArgumentException("The dataset has no response values."); } if (response.type != Attribute.Type.NOMINAL) { throw new IllegalArgumentException("The response variable is not nominal."); } if (i < 0) { throw new IllegalArgumentException("Invalid index: i = " + i); } int nrows = size(); if (i >= nrows) { for (int k = nrows; k <= i; k++) { data.add(new Datum<SparseArray>(new SparseArray())); } } get(i).y = y; } /** * Set the real-valued response of a datum. If the index * exceeds the current matrix size, the matrix will resize itself. * @param i the row index of entry. * @param y the class label or real-valued response of the datum. */ public void set(int i, double y) { if (response == null) { throw new IllegalArgumentException("The dataset has no response values."); } if (response.type != Attribute.Type.NUMERIC) { throw new IllegalArgumentException("The response variable is not numeric."); } if (i < 0) { throw new IllegalArgumentException("Invalid index: i = " + i); } int nrows = size(); if (i >= nrows) { for (int k = nrows; k <= i; k++) { data.add(new Datum<SparseArray>(new SparseArray())); } } get(i).y = y; } /** * Set the class label of real-valued response of a datum. If the index * exceeds the current matrix size, the matrix will resize itself. * @param i the row index of entry. * @param y the class label or real-valued response of the datum. * @param weight the optional weight of the datum. */ public void set(int i, double y, double weight) { if (i < 0) { throw new IllegalArgumentException("Invalid index: i = " + i); } int nrows = size(); if (i >= nrows) { for (int k = nrows; k <= i; k++) { data.add(new Datum<SparseArray>(new SparseArray())); } } Datum<SparseArray> datum = get(i); datum.y = y; datum.weight = weight; } /** * Set a nonzero entry into the matrix. If the index exceeds the current * matrix size, the matrix will resize itself. * @param i the row index of entry. * @param j the column index of entry. * @param x the value of entry. */ public void set(int i, int j, double x) { if (i < 0 || j < 0) { throw new IllegalArgumentException("Invalid index: i = " + i + " j = " + j); } int nrows = size(); if (i >= nrows) { for (int k = nrows; k <= i; k++) { data.add(new Datum<SparseArray>(new SparseArray())); } } if (j >= ncols()) { numColumns = j + 1; if (numColumns > colSize.length) { int[] size = new int[3 * numColumns / 2]; System.arraycopy(colSize, 0, size, 0, colSize.length); colSize = size; } } if (get(i).x.set(j, x)) { colSize[j]++; n++; } } /** * Returns the element at the specified position in this dataset. * @param i the index of the element to be returned. */ public Datum<SparseArray> get(int i) { return data.get(i); } /** * Returns the value at entry (i, j). * @param i the row index. * @param j the column index. */ public double get(int i, int j) { if (i < 0 || i >= size() || j < 0 || j >= ncols()) { throw new IllegalArgumentException("Invalid index: i = " + i + " j = " + j); } for (SparseArray.Entry e : get(i).x) { if (e.i == j) { return e.x; } } return 0.0; } /** * Removes the element at the specified position in this dataset. * @param i the index of the element to be removed. * @return the element previously at the specified position. */ public Datum<SparseArray> remove(int i) { Datum<SparseArray> datum = data.remove(i); n -= datum.x.size(); for (SparseArray.Entry item : datum.x) { colSize[item.i]--; } return datum; } /** * Unitize each row so that L2 norm of x = 1. */ public void unitize() { for (Datum<SparseArray> row : this) { double sum = 0.0; for (SparseArray.Entry e : row.x) { sum += Math.sqr(e.x); } sum = Math.sqrt(sum); for (SparseArray.Entry e : row.x) { e.x /= sum; } } } /** * Unitize each row so that L1 norm of x is 1. */ public void unitize1() { for (Datum<SparseArray> row : this) { double sum = 0.0; for (SparseArray.Entry e : row.x) { sum += Math.abs(e.x); } for (SparseArray.Entry e : row.x) { e.x /= sum; } } } /** * Convert into Harwell-Boeing column-compressed sparse matrix format. */ public SparseMatrix toSparseMatrix() { int[] pos = new int[numColumns]; int[] colIndex = new int[numColumns + 1]; for (int i = 0; i < numColumns; i++) { colIndex[i + 1] = colIndex[i] + colSize[i]; } int nrows = size(); int[] rowIndex = new int[n]; double[] x = new double[n]; for (int i = 0; i < nrows; i++) { for (SparseArray.Entry e : get(i).x) { int j = e.i; int k = colIndex[j] + pos[j]; rowIndex[k] = i; x[k] = e.x; pos[j]++; } } return new SparseMatrix(nrows, numColumns, x, rowIndex, colIndex); } /** * Returns an iterator over the elements in this dataset in proper sequence. * @return an iterator over the elements in this dataset in proper sequence */ @Override public Iterator<Datum<SparseArray>> iterator() { return new Iterator<Datum<SparseArray>>() { /** * Current position. */ int i = 0; @Override public boolean hasNext() { return i < data.size(); } @Override public Datum<SparseArray> next() { return get(i++); } @Override public void remove() { SparseDataset.this.remove(i); } }; } /** * Returns a dense two-dimensional array containing the whole matrix in * this dataset in proper sequence. * * @return a dense two-dimensional array containing the whole matrix in * this dataset in proper sequence. */ public double[][] toArray() { int m = data.size(); double[][] a = new double[m][ncols()]; for (int i = 0; i < m; i++) { for (SparseArray.Entry item : get(i).x) { a[i][item.i] = item.x; } } return a; } /** * Returns an array containing all of the elements in this dataset in * proper sequence (from first to last element); the runtime type of the * returned array is that of the specified array. If the dataset fits in * the specified array, it is returned therein. Otherwise, a new array * is allocated with the runtime type of the specified array and the size * of this dataset. * <p> * If the dataset fits in the specified array with room to spare (i.e., the * array has more elements than the dataset), the element in the array * immediately following the end of the dataset is set to null. * * @param a the array into which the elements of this dataset are to be * stored, if it is big enough; otherwise, a new array of the same runtime * type is allocated for this purpose. * @return an array containing the elements of this dataset. */ public SparseArray[] toArray(SparseArray[] a) { int m = data.size(); if (a.length < m) { a = new SparseArray[m]; } for (int i = 0; i < m; i++) { a[i] = get(i).x; } for (int i = m; i < a.length; i++) { a[i] = null; } return a; } /** * Returns an array containing the class labels of the elements in this * dataset in proper sequence (from first to last element). Unknown labels * will be saved as Integer.MIN_VALUE. If the dataset fits in the specified * array, it is returned therein. Otherwise, a new array is allocated with * the size of this dataset. * <p> * If the dataset fits in the specified array with room to spare (i.e., the * array has more elements than the dataset), the element in the array * immediately following the end of the dataset is set to Integer.MIN_VALUE. * * @param a the array into which the class labels of this dataset are to be * stored, if it is big enough; otherwise, a new array is allocated for * this purpose. * @return an array containing the class labels of this dataset. */ public int[] toArray(int[] a) { if (response == null) { throw new IllegalArgumentException("The dataset has no response values."); } if (response.type != Attribute.Type.NOMINAL) { throw new IllegalArgumentException("The response variable is not nominal."); } int m = data.size(); if (a.length < m) { a = new int[m]; } for (int i = 0; i < m; i++) { Datum<SparseArray> datum = get(i); if (Double.isNaN(datum.y)) { a[i] = Integer.MIN_VALUE; } else { a[i] = (int) get(i).y; } } for (int i = m; i < a.length; i++) { a[i] = Integer.MIN_VALUE; } return a; } /** * Returns an array containing the response variable of the elements in this * dataset in proper sequence (from first to last element). If the dataset * fits in the specified array, it is returned therein. Otherwise, a new array * is allocated with the size of this dataset. * <p> * If the dataset fits in the specified array with room to spare (i.e., the * array has more elements than the dataset), the element in the array * immediately following the end of the dataset is set to Double.NaN. * * @param a the array into which the response variable of this dataset are * to be stored, if it is big enough; otherwise, a new array is allocated * for this purpose. * @return an array containing the response variable of this dataset. */ public double[] toArray(double[] a) { if (response == null) { throw new IllegalArgumentException("The dataset has no response values."); } if (response.type != Attribute.Type.NUMERIC) { throw new IllegalArgumentException("The response variable is not numeric."); } int m = data.size(); if (a.length < m) { a = new double[m]; } for (int i = 0; i < m; i++) { a[i] = get(i).y; } for (int i = m; i < a.length; i++) { a[i] = Double.NaN; } return a; } }
/* * Copyright 2014 NAVER Corp. * * 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.navercorp.pinpoint.web.cluster.zookeeper; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.Code; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; import org.jboss.netty.util.HashedWheelTimer; import org.jboss.netty.util.Timeout; import org.jboss.netty.util.TimerTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.navercorp.pinpoint.rpc.util.TimerFactory; import com.navercorp.pinpoint.web.cluster.zookeeper.exception.AuthException; import com.navercorp.pinpoint.web.cluster.zookeeper.exception.BadOperationException; import com.navercorp.pinpoint.web.cluster.zookeeper.exception.ConnectionException; import com.navercorp.pinpoint.web.cluster.zookeeper.exception.NoNodeException; import com.navercorp.pinpoint.web.cluster.zookeeper.exception.PinpointZookeeperException; import com.navercorp.pinpoint.web.cluster.zookeeper.exception.TimeoutException; import com.navercorp.pinpoint.web.cluster.zookeeper.exception.UnknownException; /** * @author koo.taejin */ public class ZookeeperClient { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final AtomicBoolean clientState = new AtomicBoolean(true); private final HashedWheelTimer timer; private final String hostPort; private final int sessionTimeout; private final ZookeeperClusterManager manager; private final long reconnectDelayWhenSessionExpired; // ZK client is thread-safe private volatile ZooKeeper zookeeper; // hmm this structure should contain all necessary information public ZookeeperClient(String hostPort, int sessionTimeout, ZookeeperClusterManager manager) throws KeeperException, IOException, InterruptedException { this(hostPort, sessionTimeout, manager, ZookeeperClusterManager.DEFAULT_RECONNECT_DELAY_WHEN_SESSION_EXPIRED); } public ZookeeperClient(String hostPort, int sessionTimeout, ZookeeperClusterManager manager, long reconnectDelayWhenSessionExpired) throws KeeperException, IOException, InterruptedException { this.hostPort = hostPort; this.sessionTimeout = sessionTimeout; this.manager = manager; this.reconnectDelayWhenSessionExpired = reconnectDelayWhenSessionExpired; this.zookeeper = new ZooKeeper(hostPort, sessionTimeout, manager); // server this.timer = TimerFactory.createHashedWheelTimer(this.getClass().getSimpleName(), 100, TimeUnit.MILLISECONDS, 512); } public void reconnectWhenSessionExpired() { if (!clientState.get()) { logger.warn("ZookeeperClient.reconnectWhenSessionExpired() failed. Error: Already closed."); return; } ZooKeeper zookeeper = this.zookeeper; if (zookeeper.getState().isConnected()) { logger.warn("ZookeeperClient.reconnectWhenSessionExpired() failed. Error: session(0x{}) is connected.", Long.toHexString(zookeeper.getSessionId())); return; } logger.warn("Execute ZookeeperClient.reconnectWhenSessionExpired()(Expired session:0x{}).", Long.toHexString(zookeeper.getSessionId())); try { zookeeper.close(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } ZooKeeper newZookeeper = createNewZookeeper(); if (newZookeeper == null) { logger.warn("Failed to create new Zookeeper instance. It will be retry after {}ms.", reconnectDelayWhenSessionExpired); timer.newTimeout(new TimerTask() { @Override public void run(Timeout timeout) throws Exception { if (timeout.isCancelled()) { return; } reconnectWhenSessionExpired(); } }, reconnectDelayWhenSessionExpired, TimeUnit.MILLISECONDS); } else { this.zookeeper = newZookeeper; } } private ZooKeeper createNewZookeeper() { try { return new ZooKeeper(hostPort, sessionTimeout, manager); } catch (IOException ignore) { // ignore } return null; } /** * do not create node in path suffix * * @throws PinpointZookeeperException * @throws InterruptedException */ public void createPath(String path) throws PinpointZookeeperException, InterruptedException { checkState(); ZooKeeper zookeeper = this.zookeeper; int pos = 1; do { pos = path.indexOf('/', pos + 1); if (pos == -1) { pos = path.length(); return; } try { String subPath = path.substring(0, pos); if (zookeeper.exists(subPath, false) != null) { continue; } zookeeper.create(subPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException exception) { if (exception.code() != Code.NODEEXISTS) { handleException(exception); } } } while (pos < path.length()); } // we need deep node inspection for verification purpose (node content) public String createNode(String znodePath, byte[] data, CreateMode createMode) throws PinpointZookeeperException, InterruptedException { checkState(); ZooKeeper zookeeper = this.zookeeper; try { if (zookeeper.exists(znodePath, false) != null) { return znodePath; } String pathName = zookeeper.create(znodePath, data, Ids.OPEN_ACL_UNSAFE, createMode); return pathName; } catch (KeeperException exception) { if (exception.code() != Code.NODEEXISTS) { handleException(exception); } } return znodePath; } public List<String> getChildren(String path, boolean watch) throws PinpointZookeeperException, InterruptedException { checkState(); ZooKeeper zookeeper = this.zookeeper; try { return zookeeper.getChildren(path, watch); } catch (KeeperException exception) { if (exception.code() != Code.NONODE) { handleException(exception); } } return Collections.emptyList(); } public byte[] getData(String path) throws PinpointZookeeperException, InterruptedException { return getData(path, false); } public byte[] getData(String path, boolean watch) throws PinpointZookeeperException, InterruptedException { checkState(); ZooKeeper zookeeper = this.zookeeper; try { return zookeeper.getData(path, watch, null); } catch (KeeperException exception) { handleException(exception); } throw new UnknownException("UnknownException."); } public void delete(String path) throws PinpointZookeeperException, InterruptedException { checkState(); ZooKeeper zookeeper = this.zookeeper; try { zookeeper.delete(path, -1); } catch (KeeperException exception) { if (exception.code() != Code.NONODE) { handleException(exception); } } } public boolean exists(String path) throws PinpointZookeeperException, InterruptedException { checkState(); ZooKeeper zookeeper = this.zookeeper; try { Stat stat = zookeeper.exists(path, false); if (stat == null) { return false; } } catch (KeeperException exception) { if (exception.code() != Code.NODEEXISTS) { handleException(exception); } } return true; } private void checkState() throws PinpointZookeeperException { if (!this.manager.isConnected() || !clientState.get()) { throw new ConnectionException("instance must be connected."); } } private void handleException(KeeperException keeperException) throws PinpointZookeeperException { switch (keeperException.code()) { case CONNECTIONLOSS: case SESSIONEXPIRED: throw new ConnectionException(keeperException.getMessage(), keeperException); case AUTHFAILED: case INVALIDACL: case NOAUTH: throw new AuthException(keeperException.getMessage(), keeperException); case BADARGUMENTS: case BADVERSION: case NOCHILDRENFOREPHEMERALS: case NOTEMPTY: case NODEEXISTS: throw new BadOperationException(keeperException.getMessage(), keeperException); case NONODE: throw new NoNodeException(keeperException.getMessage(), keeperException); case OPERATIONTIMEOUT: throw new TimeoutException(keeperException.getMessage(), keeperException); default: throw new UnknownException(keeperException.getMessage(), keeperException); } } public void close() { if (clientState.compareAndSet(true, false)) { if (timer != null) { timer.stop(); } if (zookeeper != null) { try { zookeeper.close(); } catch (InterruptedException ignore) { logger.debug(ignore.getMessage(), ignore); } } } } }
/* * Copyright (c) 2009-2010 jMonkeyEngine * 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 'jMonkeyEngine' 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. */ package com.jme3.system.lwjgl; import com.jme3.system.AppSettings; import com.jme3.system.JmeCanvasContext; import com.jme3.system.JmeContext.Type; import com.jme3.system.JmeSystem; import com.jme3.system.Platform; import java.awt.Canvas; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.SwingUtilities; import org.lwjgl.LWJGLException; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.Pbuffer; import org.lwjgl.opengl.PixelFormat; public class LwjglCanvas extends LwjglAbstractDisplay implements JmeCanvasContext { protected static final int TASK_NOTHING = 0, TASK_DESTROY_DISPLAY = 1, TASK_CREATE_DISPLAY = 2, TASK_COMPLETE = 3; // protected static final boolean USE_SHARED_CONTEXT = // Boolean.parseBoolean(System.getProperty("jme3.canvas.sharedctx", "true")); protected static final boolean USE_SHARED_CONTEXT = false; private static final Logger logger = Logger.getLogger(LwjglDisplay.class.getName()); private Canvas canvas; private int width; private int height; private final Object taskLock = new Object(); private int desiredTask = TASK_NOTHING; private Thread renderThread; private boolean runningFirstTime = true; private boolean mouseWasGrabbed = false; private boolean mouseWasCreated = false; private boolean keyboardWasCreated = false; private Pbuffer pbuffer; private PixelFormat pbufferFormat; private PixelFormat canvasFormat; private class GLCanvas extends Canvas { @Override public void addNotify(){ super.addNotify(); if (renderThread != null && renderThread.getState() == Thread.State.TERMINATED) return; // already destroyed. if (renderThread == null){ logger.log(Level.INFO, "EDT: Creating OGL thread."); // Also set some settings on the canvas here. // So we don't do it outside the AWT thread. canvas.setFocusable(true); canvas.setIgnoreRepaint(true); renderThread = new Thread(LwjglCanvas.this, "LWJGL Renderer Thread"); renderThread.start(); }else if (needClose.get()){ return; } logger.log(Level.INFO, "EDT: Telling OGL to create display .."); synchronized (taskLock){ desiredTask = TASK_CREATE_DISPLAY; // while (desiredTask != TASK_COMPLETE){ // try { // taskLock.wait(); // } catch (InterruptedException ex) { // return; // } // } // desiredTask = TASK_NOTHING; } // logger.log(Level.INFO, "EDT: OGL has created the display"); } @Override public void removeNotify(){ if (needClose.get()){ logger.log(Level.INFO, "EDT: Application is stopped. Not restoring canvas."); super.removeNotify(); return; } // We must tell GL context to shutdown and wait for it to // shutdown, otherwise, issues will occur. logger.log(Level.INFO, "EDT: Telling OGL to destroy display .."); synchronized (taskLock){ desiredTask = TASK_DESTROY_DISPLAY; while (desiredTask != TASK_COMPLETE){ try { taskLock.wait(); } catch (InterruptedException ex){ super.removeNotify(); return; } } desiredTask = TASK_NOTHING; } logger.log(Level.INFO, "EDT: Acknowledged receipt of canvas death"); // GL context is dead at this point super.removeNotify(); } } public LwjglCanvas(){ super(); canvas = new GLCanvas(); } @Override public Type getType() { return Type.Canvas; } public void create(boolean waitFor){ if (renderThread == null){ logger.log(Level.INFO, "MAIN: Creating OGL thread."); renderThread = new Thread(LwjglCanvas.this, "LWJGL Renderer Thread"); renderThread.start(); } // do not do anything. // superclass's create() will be called at initInThread() if (waitFor) waitFor(true); } @Override public void setTitle(String title) { } @Override public void restart() { frameRate = settings.getFrameRate(); // TODO: Handle other cases, like change of pixel format, etc. } public Canvas getCanvas(){ return canvas; } @Override protected void runLoop(){ if (desiredTask != TASK_NOTHING){ synchronized (taskLock){ switch (desiredTask){ case TASK_CREATE_DISPLAY: logger.log(Level.INFO, "OGL: Creating display .."); restoreCanvas(); listener.gainFocus(); desiredTask = TASK_NOTHING; break; case TASK_DESTROY_DISPLAY: logger.log(Level.INFO, "OGL: Destroying display .."); listener.loseFocus(); pauseCanvas(); break; } desiredTask = TASK_COMPLETE; taskLock.notifyAll(); } } if (renderable.get()){ int newWidth = Math.max(canvas.getWidth(), 1); int newHeight = Math.max(canvas.getHeight(), 1); if (width != newWidth || height != newHeight){ width = newWidth; height = newHeight; if (listener != null){ listener.reshape(width, height); } } }else{ if (frameRate <= 0){ // NOTE: MUST be done otherwise // Windows OS will freeze Display.sync(30); } } super.runLoop(); } private void pauseCanvas(){ if (Mouse.isCreated()){ if (Mouse.isGrabbed()){ Mouse.setGrabbed(false); mouseWasGrabbed = true; } mouseWasCreated = true; Mouse.destroy(); } if (Keyboard.isCreated()){ keyboardWasCreated = true; Keyboard.destroy(); } renderable.set(false); destroyContext(); } /** * Called to restore the canvas. */ private void restoreCanvas(){ logger.log(Level.INFO, "OGL: Waiting for canvas to become displayable.."); while (!canvas.isDisplayable()){ try { Thread.sleep(10); } catch (InterruptedException ex) { logger.log(Level.SEVERE, "OGL: Interrupted! ", ex); } } logger.log(Level.INFO, "OGL: Creating display context .."); // Set renderable to true, since canvas is now displayable. renderable.set(true); createContext(settings); logger.log(Level.INFO, "OGL: Display is active!"); try { if (mouseWasCreated){ Mouse.create(); if (mouseWasGrabbed){ Mouse.setGrabbed(true); mouseWasGrabbed = false; } } if (keyboardWasCreated){ Keyboard.create(); keyboardWasCreated = false; } } catch (LWJGLException ex){ logger.log(Level.SEVERE, "Encountered exception when restoring input", ex); } SwingUtilities.invokeLater(new Runnable(){ public void run(){ canvas.requestFocus(); } }); } /** * It seems it is best to use one pixel format for all shared contexts. * @see <a href="http://developer.apple.com/library/mac/#qa/qa1248/_index.html">http://developer.apple.com/library/mac/#qa/qa1248/_index.html</a> */ protected PixelFormat acquirePixelFormat(boolean forPbuffer){ if (forPbuffer){ if (pbufferFormat == null){ pbufferFormat = new PixelFormat(settings.getBitsPerPixel(), 0, settings.getDepthBits(), settings.getStencilBits(), 0); } return pbufferFormat; }else{ if (canvasFormat == null){ canvasFormat = new PixelFormat(settings.getBitsPerPixel(), 0, settings.getDepthBits(), settings.getStencilBits(), settings.getSamples()); } return canvasFormat; } } /** * Makes sure the pbuffer is available and ready for use */ protected void makePbufferAvailable() throws LWJGLException{ if (pbuffer != null && pbuffer.isBufferLost()){ logger.log(Level.WARNING, "PBuffer was lost!"); pbuffer.destroy(); pbuffer = null; } if (pbuffer == null) { pbuffer = new Pbuffer(1, 1, acquirePixelFormat(true), null); pbuffer.makeCurrent(); logger.log(Level.INFO, "OGL: Pbuffer has been created"); // Any created objects are no longer valid if (!runningFirstTime){ renderer.resetGLObjects(); } } pbuffer.makeCurrent(); if (!pbuffer.isCurrent()){ throw new LWJGLException("Pbuffer cannot be made current"); } } protected void destroyPbuffer(){ if (pbuffer != null){ if (!pbuffer.isBufferLost()){ pbuffer.destroy(); } pbuffer = null; } } /** * This is called: * 1) When the context thread ends * 2) Any time the canvas becomes non-displayable */ protected void destroyContext(){ try { // invalidate the state so renderer can resume operation if (!USE_SHARED_CONTEXT){ renderer.cleanup(); } if (Display.isCreated()){ /* FIXES: * org.lwjgl.LWJGLException: X Error * BadWindow (invalid Window parameter) request_code: 2 minor_code: 0 * * Destroying keyboard early prevents the error above, triggered * by destroying keyboard in by Display.destroy() or Display.setParent(null). * Therefore Keyboard.destroy() should precede any of these calls. */ if (Keyboard.isCreated()){ // Should only happen if called in // LwjglAbstractDisplay.deinitInThread(). Keyboard.destroy(); } //try { // NOTE: On Windows XP, not calling setParent(null) // freezes the application. // On Mac it freezes the application. // On Linux it fixes a crash with X Window System. if (JmeSystem.getPlatform() == Platform.Windows32 || JmeSystem.getPlatform() == Platform.Windows64){ //Display.setParent(null); } //} catch (LWJGLException ex) { // logger.log(Level.SEVERE, "Encountered exception when setting parent to null", ex); //} Display.destroy(); } // The canvas is no longer visible, // but the context thread is still running. if (!needClose.get()){ // MUST make sure there's still a context current here .. // Display is dead, make pbuffer available to the system makePbufferAvailable(); renderer.invalidateState(); }else{ // The context thread is no longer running. // Destroy pbuffer. destroyPbuffer(); } } catch (LWJGLException ex) { listener.handleError("Failed make pbuffer available", ex); } } /** * This is called: * 1) When the context thread starts * 2) Any time the canvas becomes displayable again. */ @Override protected void createContext(AppSettings settings) { // In case canvas is not visible, we still take framerate // from settings to prevent "100% CPU usage" frameRate = settings.getFrameRate(); try { if (renderable.get()){ if (!runningFirstTime){ // because the display is a different opengl context // must reset the context state. if (!USE_SHARED_CONTEXT){ renderer.cleanup(); } } // if the pbuffer is currently active, // make sure to deactivate it destroyPbuffer(); if (Keyboard.isCreated()){ Keyboard.destroy(); } try { Thread.sleep(1000); } catch (InterruptedException ex) { } Display.setVSyncEnabled(settings.isVSync()); Display.setParent(canvas); if (USE_SHARED_CONTEXT){ Display.create(acquirePixelFormat(false), pbuffer); }else{ Display.create(acquirePixelFormat(false)); } renderer.invalidateState(); }else{ // First create the pbuffer, if it is needed. makePbufferAvailable(); } // At this point, the OpenGL context is active. if (runningFirstTime){ // THIS is the part that creates the renderer. // It must always be called, now that we have the pbuffer workaround. initContextFirstTime(); runningFirstTime = false; } } catch (LWJGLException ex) { listener.handleError("Failed to initialize OpenGL context", ex); // TODO: Fix deadlock that happens after the error (throw runtime exception?) } } }
/* * 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; import com.carrotsearch.randomizedtesting.RandomizedContext; import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite; import org.apache.lucene.search.join.ScoreMode; import org.apache.lucene.util.TimeUnits; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.LatchedActionListener; import org.elasticsearch.action.admin.indices.refresh.RefreshRequest; import org.elasticsearch.action.admin.indices.refresh.RefreshResponse; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.CreateIndexResponse; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.core.internal.io.IOUtils; import org.elasticsearch.index.query.InnerHitBuilder; import org.elasticsearch.index.query.MatchQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.RangeQueryBuilder; import org.elasticsearch.index.query.TermQueryBuilder; import org.elasticsearch.index.query.TermsQueryBuilder; import org.elasticsearch.indices.TermsLookup; import org.elasticsearch.join.query.HasChildQueryBuilder; import org.elasticsearch.join.query.HasParentQueryBuilder; import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptType; import org.elasticsearch.search.aggregations.Aggregation; import org.elasticsearch.search.aggregations.BucketOrder; import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation; import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.CardinalityAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.SumAggregationBuilder; import org.elasticsearch.search.aggregations.metrics.TopHitsAggregationBuilder; import org.elasticsearch.search.aggregations.pipeline.DerivativePipelineAggregationBuilder; import org.elasticsearch.search.aggregations.pipeline.MaxBucketPipelineAggregationBuilder; import org.elasticsearch.search.aggregations.support.ValueType; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.collapse.CollapseBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.rescore.QueryRescoreMode; import org.elasticsearch.search.rescore.QueryRescorerBuilder; import org.elasticsearch.search.sort.ScoreSortBuilder; import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.search.suggest.SuggestBuilder; import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder; import org.elasticsearch.search.suggest.phrase.DirectCandidateGeneratorBuilder; import org.elasticsearch.search.suggest.phrase.PhraseSuggestion; import org.elasticsearch.search.suggest.phrase.PhraseSuggestionBuilder; import org.elasticsearch.search.suggest.term.TermSuggestion; import org.elasticsearch.search.suggest.term.TermSuggestionBuilder; import org.elasticsearch.test.NotEqualMessageBuilder; import org.elasticsearch.test.rest.ESRestTestCase; import org.junit.AfterClass; import org.junit.Before; import java.io.IOException; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.greaterThanOrEqualTo; /** * This test class executes twice, first against the remote cluster, and then against another cluster that has the remote cluster * registered. Given that each test gets executed against both clusters, {@link #assumeMultiClusterSetup()} needs to be used to run a test * against the multi cluster setup only, which is required for testing cross-cluster search. * The goal of this test is not to test correctness of CCS responses, but rather to verify that CCS returns the same responses when * <code>minimizeRoundTrips</code> is set to either <code>true</code> or <code>false</code>. In fact the execution differs depending on * such parameter, hence we want to verify that results are the same in both scenarios. */ @TimeoutSuite(millis = 5 * TimeUnits.MINUTE) // to account for slow as hell VMs public class CCSDuelIT extends ESRestTestCase { private static final String INDEX_NAME = "ccs_duel_index"; private static final String REMOTE_INDEX_NAME = "my_remote_cluster:" + INDEX_NAME; private static final String[] TAGS = new String[] {"java", "xml", "sql", "html", "php", "ruby", "python", "perl"}; private static RestHighLevelClient restHighLevelClient; @Before public void init() throws Exception { super.initClient(); if (restHighLevelClient == null) { restHighLevelClient = new HighLevelClient(client()); String destinationCluster = System.getProperty("tests.rest.suite"); //we index docs with private randomness otherwise the two clusters end up with exactly the same documents //given that this test class is run twice with same seed. RandomizedContext.current().runWithPrivateRandomness(random().nextLong() + destinationCluster.hashCode(), (Callable<Void>) () -> { indexDocuments(destinationCluster + "-"); return null; }); } } private static class HighLevelClient extends RestHighLevelClient { private HighLevelClient(RestClient restClient) { super(restClient, (client) -> {}, Collections.emptyList()); } } @AfterClass public static void cleanupClient() throws IOException { IOUtils.close(restHighLevelClient); restHighLevelClient = null; } @Override protected boolean preserveIndicesUponCompletion() { return true; } @Override protected boolean preserveDataStreamsUponCompletion() { return true; } private static void indexDocuments(String idPrefix) throws IOException, InterruptedException { //this index with a single document is used to test partial failures IndexRequest indexRequest = new IndexRequest(INDEX_NAME + "_err"); indexRequest.id("id"); indexRequest.source("id", "id", "creationDate", "err"); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL); IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT); assertEquals(201, indexResponse.status().getStatus()); CreateIndexRequest createEmptyIndexRequest = new CreateIndexRequest(INDEX_NAME + "_empty"); CreateIndexResponse response = restHighLevelClient.indices().create(createEmptyIndexRequest, RequestOptions.DEFAULT); assertTrue(response.isAcknowledged()); int numShards = randomIntBetween(1, 5); CreateIndexRequest createIndexRequest = new CreateIndexRequest(INDEX_NAME); createIndexRequest.settings(Settings.builder().put("index.number_of_shards", numShards).put("index.number_of_replicas", 0)); createIndexRequest.mapping("{\"properties\":{" + "\"id\":{\"type\":\"keyword\"}," + "\"suggest\":{\"type\":\"completion\"}," + "\"join\":{\"type\":\"join\", \"relations\": {\"question\":\"answer\"}}}}", XContentType.JSON); CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT); assertTrue(createIndexResponse.isAcknowledged()); BulkProcessor bulkProcessor = BulkProcessor.builder((r, l) -> restHighLevelClient.bulkAsync(r, RequestOptions.DEFAULT, l), new BulkProcessor.Listener() { @Override public void beforeBulk(long executionId, BulkRequest request) { } @Override public void afterBulk(long executionId, BulkRequest request, BulkResponse response) { assertFalse(response.hasFailures()); } @Override public void afterBulk(long executionId, BulkRequest request, Throwable failure) { throw new AssertionError("Failed to execute bulk", failure); } }).build(); int numQuestions = randomIntBetween(50, 100); for (int i = 0; i < numQuestions; i++) { bulkProcessor.add(buildIndexRequest(idPrefix + i, "question", null)); } int numAnswers = randomIntBetween(100, 150); for (int i = 0; i < numAnswers; i++) { bulkProcessor.add(buildIndexRequest(idPrefix + (i + 1000), "answer", idPrefix + randomIntBetween(0, numQuestions - 1))); } assertTrue(bulkProcessor.awaitClose(30, TimeUnit.SECONDS)); RefreshResponse refreshResponse = restHighLevelClient.indices().refresh(new RefreshRequest(INDEX_NAME), RequestOptions.DEFAULT); assertEquals(0, refreshResponse.getFailedShards()); assertEquals(numShards, refreshResponse.getSuccessfulShards()); } private static IndexRequest buildIndexRequest(String id, String type, String questionId) { IndexRequest indexRequest = new IndexRequest(INDEX_NAME); indexRequest.id(id); if (questionId != null) { indexRequest.routing(questionId); } indexRequest.create(true); int numTags = randomIntBetween(1, 3); Set<String> tags = new HashSet<>(); if (questionId == null) { for (int i = 0; i < numTags; i++) { tags.add(randomFrom(TAGS)); } } String[] tagsArray = tags.toArray(new String[0]); String date = LocalDate.of(2019, 1, randomIntBetween(1, 31)).format(DateTimeFormatter.ofPattern("yyyy/MM/dd", Locale.ROOT)); Map<String, String> joinField = new HashMap<>(); joinField.put("name", type); if (questionId != null) { joinField.put("parent", questionId); } indexRequest.source(XContentType.JSON, "id", id, "type", type, "votes", randomIntBetween(0, 30), "questionId", questionId, "tags", tagsArray, "user", "user" + randomIntBetween(1, 10), "suggest", Collections.singletonMap("input", tagsArray), "creationDate", date, "join", joinField); return indexRequest; } public void testMatchAll() throws Exception { assumeMultiClusterSetup(); //verify that the order in which documents are returned when they all have the same score is the same SearchRequest searchRequest = initSearchRequest(); duelSearch(searchRequest, CCSDuelIT::assertHits); } public void testMatchQuery() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.size(50); sourceBuilder.query(QueryBuilders.matchQuery("tags", "php")); searchRequest.source(sourceBuilder); duelSearch(searchRequest, CCSDuelIT::assertHits); } public void testTrackTotalHitsUpTo() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.trackTotalHitsUpTo(5); sourceBuilder.query(QueryBuilders.matchQuery("tags", "sql")); searchRequest.source(sourceBuilder); duelSearch(searchRequest, CCSDuelIT::assertHits); } public void testTerminateAfter() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.terminateAfter(10); sourceBuilder.query(QueryBuilders.matchQuery("tags", "perl")); searchRequest.source(sourceBuilder); duelSearch(searchRequest, CCSDuelIT::assertHits); } public void testPagination() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.from(10); sourceBuilder.size(20); sourceBuilder.query(QueryBuilders.matchQuery("tags", "python")); searchRequest.source(sourceBuilder); duelSearch(searchRequest, response -> assertHits(response, 10)); } public void testHighlighting() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.highlighter(new HighlightBuilder().field("tags")); sourceBuilder.query(QueryBuilders.matchQuery("tags", "xml")); searchRequest.source(sourceBuilder); duelSearch(searchRequest, response -> { assertHits(response); assertFalse(response.getHits().getHits()[0].getHighlightFields().isEmpty()); }); } public void testFetchSource() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.fetchSource(new String[]{"tags"}, Strings.EMPTY_ARRAY); sourceBuilder.query(QueryBuilders.matchQuery("tags", "ruby")); searchRequest.source(sourceBuilder); duelSearch(searchRequest, response -> { assertHits(response); assertEquals(1, response.getHits().getHits()[0].getSourceAsMap().size()); }); } public void testDocValueFields() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.docValueField("user.keyword"); sourceBuilder.query(QueryBuilders.matchQuery("tags", "xml")); searchRequest.source(sourceBuilder); duelSearch(searchRequest, response -> { assertHits(response); assertEquals(1, response.getHits().getHits()[0].getFields().size()); assertNotNull(response.getHits().getHits()[0].getFields().get("user.keyword")); }); } public void testScriptFields() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.scriptField("parent", new Script(ScriptType.INLINE, "painless", "doc['join#question']", Collections.emptyMap())); searchRequest.source(sourceBuilder); duelSearch(searchRequest, response -> { assertHits(response); assertEquals(1, response.getHits().getHits()[0].getFields().size()); assertNotNull(response.getHits().getHits()[0].getFields().get("parent")); }); } public void testExplain() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.explain(true); sourceBuilder.query(QueryBuilders.matchQuery("tags", "sql")); searchRequest.source(sourceBuilder); duelSearch(searchRequest, response -> { assertHits(response); assertNotNull(response.getHits().getHits()[0].getExplanation()); }); } public void testRescore() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchQuery("tags", "xml")); QueryRescorerBuilder rescorerBuilder = new QueryRescorerBuilder(new MatchQueryBuilder("tags", "java")); rescorerBuilder.setScoreMode(QueryRescoreMode.Multiply); rescorerBuilder.setRescoreQueryWeight(5); sourceBuilder.addRescorer(rescorerBuilder); searchRequest.source(sourceBuilder); duelSearch(searchRequest, CCSDuelIT::assertHits); } public void testHasParentWithInnerHit() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); HasParentQueryBuilder hasParentQueryBuilder = new HasParentQueryBuilder("question", QueryBuilders.matchQuery("tags", "xml"), true); hasParentQueryBuilder.innerHit(new InnerHitBuilder("inner")); sourceBuilder.query(hasParentQueryBuilder); searchRequest.source(sourceBuilder); duelSearch(searchRequest, CCSDuelIT::assertHits); } public void testHasChildWithInnerHit() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); RangeQueryBuilder rangeQueryBuilder = new RangeQueryBuilder("creationDate").gte("2019/01/01").lte("2019/01/31"); HasChildQueryBuilder query = new HasChildQueryBuilder("answer", rangeQueryBuilder, ScoreMode.Total); query.innerHit(new InnerHitBuilder("inner")); sourceBuilder.query(query); searchRequest.source(sourceBuilder); duelSearch(searchRequest, CCSDuelIT::assertHits); } public void testProfile() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.profile(true); sourceBuilder.query(QueryBuilders.matchQuery("tags", "html")); searchRequest.source(sourceBuilder); duelSearch(searchRequest, response -> { assertHits(response); assertFalse(response.getProfileResults().isEmpty()); }); } public void testSortByField() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.from(30); sourceBuilder.size(25); sourceBuilder.query(QueryBuilders.matchQuery("tags", "php")); sourceBuilder.sort("type.keyword", SortOrder.ASC); sourceBuilder.sort("creationDate", SortOrder.DESC); sourceBuilder.sort("user.keyword", SortOrder.ASC); searchRequest.source(sourceBuilder); duelSearch(searchRequest, response -> { assertHits(response, 30); if (response.getHits().getTotalHits().value > 30) { assertEquals(3, response.getHits().getHits()[0].getSortValues().length); } }); } public void testSortByFieldOneClusterHasNoResults() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); // set to a value greater than the number of shards to avoid differences due to the skipping of shards searchRequest.setPreFilterShardSize(128); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); boolean onlyRemote = randomBoolean(); sourceBuilder.query(new TermQueryBuilder("_index", onlyRemote ? REMOTE_INDEX_NAME : INDEX_NAME)); sourceBuilder.sort("type.keyword", SortOrder.ASC); sourceBuilder.sort("creationDate", SortOrder.DESC); sourceBuilder.sort("user.keyword", SortOrder.ASC); searchRequest.source(sourceBuilder); duelSearch(searchRequest, response -> { assertHits(response); SearchHit[] hits = response.getHits().getHits(); for (SearchHit hit : hits) { assertEquals(3, hit.getSortValues().length); assertEquals(INDEX_NAME, hit.getIndex()); if (onlyRemote) { assertEquals("my_remote_cluster", hit.getClusterAlias()); } else { assertNull(hit.getClusterAlias()); } } }); } public void testFieldCollapsingOneClusterHasNoResults() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); boolean onlyRemote = randomBoolean(); sourceBuilder.query(new TermQueryBuilder("_index", onlyRemote ? REMOTE_INDEX_NAME : INDEX_NAME)); sourceBuilder.collapse(new CollapseBuilder("user.keyword")); searchRequest.source(sourceBuilder); duelSearch(searchRequest, response -> { assertHits(response); for (SearchHit hit : response.getHits().getHits()) { assertEquals(INDEX_NAME, hit.getIndex()); if (onlyRemote) { assertEquals("my_remote_cluster", hit.getClusterAlias()); } else { assertNull(hit.getClusterAlias()); } } }); } public void testFieldCollapsingSortByScore() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); searchRequest.source(sourceBuilder); sourceBuilder.query(QueryBuilders.matchQuery("tags", "ruby")); sourceBuilder.collapse(new CollapseBuilder("user.keyword")); duelSearch(searchRequest, CCSDuelIT::assertHits); } public void testFieldCollapsingSortByField() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); searchRequest.source(sourceBuilder); sourceBuilder.query(QueryBuilders.matchQuery("tags", "ruby")); sourceBuilder.sort("creationDate", SortOrder.DESC); sourceBuilder.sort(new ScoreSortBuilder()); sourceBuilder.collapse(new CollapseBuilder("user.keyword")); duelSearch(searchRequest, response -> { assertHits(response); assertEquals(2, response.getHits().getHits()[0].getSortValues().length); }); } @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/40005") public void testTermsAggs() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); searchRequest.source(buildTermsAggsSource()); duelSearch(searchRequest, CCSDuelIT::assertAggs); } @AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/40005") public void testTermsAggsWithProfile() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); searchRequest.source(buildTermsAggsSource().profile(true)); duelSearch(searchRequest, CCSDuelIT::assertAggs); } private static SearchSourceBuilder buildTermsAggsSource() { SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.size(0); TermsAggregationBuilder cluster = new TermsAggregationBuilder("cluster123").userValueTypeHint(ValueType.STRING); cluster.field("_index"); TermsAggregationBuilder type = new TermsAggregationBuilder("type").userValueTypeHint(ValueType.STRING); type.field("type.keyword"); type.showTermDocCountError(true); type.order(BucketOrder.key(true)); cluster.subAggregation(type); sourceBuilder.aggregation(cluster); TermsAggregationBuilder tags = new TermsAggregationBuilder("tags").userValueTypeHint(ValueType.STRING); tags.field("tags.keyword"); tags.showTermDocCountError(true); tags.size(100); sourceBuilder.aggregation(tags); TermsAggregationBuilder tags2 = new TermsAggregationBuilder("tags").userValueTypeHint(ValueType.STRING); tags2.field("tags.keyword"); tags.subAggregation(tags2); FilterAggregationBuilder answers = new FilterAggregationBuilder("answers", new TermQueryBuilder("type", "answer")); TermsAggregationBuilder answerPerQuestion = new TermsAggregationBuilder("answer_per_question") .userValueTypeHint(ValueType.STRING); answerPerQuestion.showTermDocCountError(true); answerPerQuestion.field("questionId.keyword"); answers.subAggregation(answerPerQuestion); TermsAggregationBuilder answerPerUser = new TermsAggregationBuilder("answer_per_user").userValueTypeHint(ValueType.STRING); answerPerUser.field("user.keyword"); answerPerUser.size(30); answerPerUser.showTermDocCountError(true); answers.subAggregation(answerPerUser); sourceBuilder.aggregation(answers); return sourceBuilder; } public void testDateHistogram() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.size(0); searchRequest.source(sourceBuilder); TermsAggregationBuilder tags = new TermsAggregationBuilder("tags").userValueTypeHint(ValueType.STRING); tags.field("tags.keyword"); tags.showTermDocCountError(true); DateHistogramAggregationBuilder creation = new DateHistogramAggregationBuilder("creation"); creation.field("creationDate"); creation.calendarInterval(DateHistogramInterval.QUARTER); creation.subAggregation(tags); sourceBuilder.aggregation(creation); duelSearch(searchRequest, CCSDuelIT::assertAggs); } public void testCardinalityAgg() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.size(0); searchRequest.source(sourceBuilder); CardinalityAggregationBuilder tags = new CardinalityAggregationBuilder("tags").userValueTypeHint(ValueType.STRING); tags.field("tags.keyword"); sourceBuilder.aggregation(tags); duelSearch(searchRequest, CCSDuelIT::assertAggs); } public void testPipelineAggs() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(new TermQueryBuilder("type", "answer")); searchRequest.source(sourceBuilder); sourceBuilder.size(0); DateHistogramAggregationBuilder daily = new DateHistogramAggregationBuilder("daily"); daily.field("creationDate"); daily.calendarInterval(DateHistogramInterval.DAY); sourceBuilder.aggregation(daily); daily.subAggregation(new DerivativePipelineAggregationBuilder("derivative", "_count")); sourceBuilder.aggregation(new MaxBucketPipelineAggregationBuilder("biggest_day", "daily._count")); daily.subAggregation(new SumAggregationBuilder("votes").field("votes")); sourceBuilder.aggregation(new MaxBucketPipelineAggregationBuilder("most_voted", "daily>votes")); duelSearch(searchRequest, response -> { assertAggs(response); assertNotNull(response.getAggregations().get("most_voted")); }); duelSearch(searchRequest, CCSDuelIT::assertAggs); } public void testTopHits() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); searchRequest.source(sourceBuilder); sourceBuilder.size(0); TopHitsAggregationBuilder topHits = new TopHitsAggregationBuilder("top"); topHits.from(10); topHits.size(10); topHits.sort("creationDate", SortOrder.DESC); topHits.sort("id", SortOrder.ASC); TermsAggregationBuilder tags = new TermsAggregationBuilder("tags").userValueTypeHint(ValueType.STRING); tags.field("tags.keyword"); tags.size(10); tags.subAggregation(topHits); sourceBuilder.aggregation(tags); duelSearch(searchRequest, CCSDuelIT::assertAggs); } public void testTermsLookup() throws Exception { assumeMultiClusterSetup(); IndexRequest indexRequest = new IndexRequest("lookup_index"); indexRequest.id("id"); indexRequest.source("tags", new String[]{"java", "sql", "html", "jax-ws"}); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL); IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT); assertEquals(201, indexResponse.status().getStatus()); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); TermsQueryBuilder termsQueryBuilder = new TermsQueryBuilder("tags", new TermsLookup("lookup_index", "id", "tags")); sourceBuilder.query(termsQueryBuilder); searchRequest.source(sourceBuilder); duelSearch(searchRequest, CCSDuelIT::assertHits); } public void testShardFailures() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = new SearchRequest(INDEX_NAME + "*", REMOTE_INDEX_NAME + "*"); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchQuery("creationDate", "err")); searchRequest.source(sourceBuilder); duelSearch(searchRequest, response -> { assertMultiClusterSearchResponse(response); assertThat(response.getHits().getTotalHits().value, greaterThan(0L)); assertNull(response.getAggregations()); assertNull(response.getSuggest()); assertThat(response.getHits().getHits().length, greaterThan(0)); assertThat(response.getFailedShards(), greaterThanOrEqualTo(2)); }); } public void testTermSuggester() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); searchRequest.source(sourceBuilder); SuggestBuilder suggestBuilder = new SuggestBuilder(); suggestBuilder.setGlobalText("jva hml"); suggestBuilder.addSuggestion("tags", new TermSuggestionBuilder("tags") .suggestMode(TermSuggestionBuilder.SuggestMode.POPULAR)); sourceBuilder.suggest(suggestBuilder); duelSearch(searchRequest, response -> { assertMultiClusterSearchResponse(response); assertEquals(1, response.getSuggest().size()); TermSuggestion tags = response.getSuggest().getSuggestion("tags"); assertThat(tags.getEntries().size(), greaterThan(0)); }); } public void testPhraseSuggester() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); searchRequest.source(sourceBuilder); SuggestBuilder suggestBuilder = new SuggestBuilder(); suggestBuilder.setGlobalText("jva and hml"); suggestBuilder.addSuggestion("tags", new PhraseSuggestionBuilder("tags").addCandidateGenerator( new DirectCandidateGeneratorBuilder("tags").suggestMode("always")).highlight("<em>", "</em>")); sourceBuilder.suggest(suggestBuilder); duelSearch(searchRequest, response -> { assertMultiClusterSearchResponse(response); assertEquals(1, response.getSuggest().size()); PhraseSuggestion tags = response.getSuggest().getSuggestion("tags"); assertThat(tags.getEntries().size(), greaterThan(0)); }); } public void testCompletionSuggester() throws Exception { assumeMultiClusterSetup(); SearchRequest searchRequest = initSearchRequest(); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); searchRequest.source(sourceBuilder); SuggestBuilder suggestBuilder = new SuggestBuilder(); suggestBuilder.addSuggestion("python", new CompletionSuggestionBuilder("suggest").size(10).text("pyth")); suggestBuilder.addSuggestion("java", new CompletionSuggestionBuilder("suggest").size(20).text("jav")); suggestBuilder.addSuggestion("ruby", new CompletionSuggestionBuilder("suggest").size(30).text("rub")); sourceBuilder.suggest(suggestBuilder); duelSearch(searchRequest, response -> { assertMultiClusterSearchResponse(response); assertEquals(Strings.toString(response, true, true), 3, response.getSuggest().size()); assertThat(response.getSuggest().getSuggestion("python").getEntries().size(), greaterThan(0)); assertThat(response.getSuggest().getSuggestion("java").getEntries().size(), greaterThan(0)); assertThat(response.getSuggest().getSuggestion("ruby").getEntries().size(), greaterThan(0)); }); } private static void assumeMultiClusterSetup() { assumeTrue("must run only against the multi_cluster setup", "multi_cluster".equals(System.getProperty("tests.rest.suite"))); } private static SearchRequest initSearchRequest() { List<String> indices = Arrays.asList(INDEX_NAME, "my_remote_cluster:" + INDEX_NAME); Collections.shuffle(indices, random()); return new SearchRequest(indices.toArray(new String[0])); } private static void duelSearch(SearchRequest searchRequest, Consumer<SearchResponse> responseChecker) throws Exception { CountDownLatch latch = new CountDownLatch(2); AtomicReference<Exception> exception1 = new AtomicReference<>(); AtomicReference<SearchResponse> minimizeRoundtripsResponse = new AtomicReference<>(); searchRequest.setCcsMinimizeRoundtrips(true); restHighLevelClient.searchAsync(searchRequest, RequestOptions.DEFAULT, new LatchedActionListener<>(ActionListener.wrap(minimizeRoundtripsResponse::set, exception1::set), latch)); AtomicReference<Exception> exception2 = new AtomicReference<>(); AtomicReference<SearchResponse> fanOutResponse = new AtomicReference<>(); searchRequest.setCcsMinimizeRoundtrips(false); restHighLevelClient.searchAsync(searchRequest, RequestOptions.DEFAULT, new LatchedActionListener<>(ActionListener.wrap(fanOutResponse::set, exception2::set), latch)); latch.await(); if (exception1.get() != null && exception2.get() != null) { exception1.get().addSuppressed(exception2.get()); throw new AssertionError("both requests returned an exception", exception1.get()); } else { if (exception1.get() != null) { throw new AssertionError("one of the two requests returned an exception", exception1.get()); } if (exception2.get() != null) { throw new AssertionError("one of the two requests returned an exception", exception2.get()); } SearchResponse minimizeRoundtripsSearchResponse = minimizeRoundtripsResponse.get(); responseChecker.accept(minimizeRoundtripsSearchResponse); assertEquals(3, minimizeRoundtripsSearchResponse.getNumReducePhases()); SearchResponse fanOutSearchResponse = fanOutResponse.get(); responseChecker.accept(fanOutSearchResponse); assertEquals(1, fanOutSearchResponse.getNumReducePhases()); Map<String, Object> minimizeRoundtripsResponseMap = responseToMap(minimizeRoundtripsSearchResponse); Map<String, Object> fanOutResponseMap = responseToMap(fanOutSearchResponse); if (minimizeRoundtripsResponseMap.equals(fanOutResponseMap) == false) { NotEqualMessageBuilder message = new NotEqualMessageBuilder(); message.compareMaps(minimizeRoundtripsResponseMap, fanOutResponseMap); throw new AssertionError("Didn't match expected value:\n" + message); } } } private static void assertMultiClusterSearchResponse(SearchResponse searchResponse) { assertEquals(2, searchResponse.getClusters().getTotal()); assertEquals(2, searchResponse.getClusters().getSuccessful()); assertThat(searchResponse.getTotalShards(), greaterThan(1)); assertThat(searchResponse.getSuccessfulShards(), greaterThan(1)); } private static void assertHits(SearchResponse response) { assertHits(response, 0); } private static void assertHits(SearchResponse response, int from) { assertMultiClusterSearchResponse(response); assertThat(response.getHits().getTotalHits().value, greaterThan(0L)); assertEquals(0, response.getFailedShards()); assertNull(response.getAggregations()); assertNull(response.getSuggest()); if (response.getHits().getTotalHits().value > from) { assertThat(response.getHits().getHits().length, greaterThan(0)); } else { assertThat(response.getHits().getHits().length, equalTo(0)); } } private static void assertAggs(SearchResponse response) { assertMultiClusterSearchResponse(response); assertThat(response.getHits().getTotalHits().value, greaterThan(0L)); assertEquals(0, response.getHits().getHits().length); assertNull(response.getSuggest()); assertNotNull(response.getAggregations()); List<Aggregation> aggregations = response.getAggregations().asList(); for (Aggregation aggregation : aggregations) { if (aggregation instanceof MultiBucketsAggregation) { MultiBucketsAggregation multiBucketsAggregation = (MultiBucketsAggregation) aggregation; assertThat("agg " + multiBucketsAggregation.getName() + " has 0 buckets", multiBucketsAggregation.getBuckets().size(), greaterThan(0)); } } } @SuppressWarnings("unchecked") private static Map<String, Object> responseToMap(SearchResponse response) throws IOException { BytesReference bytesReference = XContentHelper.toXContent(response, XContentType.JSON, false); Map<String, Object> responseMap = XContentHelper.convertToMap(bytesReference, false, XContentType.JSON).v2(); assertNotNull(responseMap.put("took", -1)); responseMap.remove("num_reduce_phases"); Map<String, Object> profile = (Map<String, Object>)responseMap.get("profile"); if (profile != null) { List<Map<String, Object>> shards = (List <Map<String, Object>>)profile.get("shards"); for (Map<String, Object> shard : shards) { replaceProfileTime(shard); } } return responseMap; } @SuppressWarnings("unchecked") private static void replaceProfileTime(Map<String, Object> map) { for (Map.Entry<String, Object> entry : map.entrySet()) { if (entry.getKey().contains("time")) { assertThat(entry.getValue(), instanceOf(Number.class)); assertNotNull(entry.setValue(-1)); } if (entry.getKey().equals("breakdown")) { Map<String, Long> breakdown = (Map<String, Long>) entry.getValue(); for (String key : breakdown.keySet()) { assertNotNull(breakdown.put(key, -1L)); } } if (entry.getValue() instanceof Map) { replaceProfileTime((Map<String, Object>) entry.getValue()); } if (entry.getValue() instanceof List) { List<Object> list = (List<Object>) entry.getValue(); for (Object obj : list) { if (obj instanceof Map) { replaceProfileTime((Map<String, Object>) obj); } } } } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package JMeter.plugins.functional.samplers.websocket; import java.awt.Color; import org.apache.jmeter.config.gui.ArgumentsPanel; import org.apache.jmeter.protocol.http.gui.HTTPArgumentsPanel; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; /** * * @author Maciej Zaleski */ public class WebSocketSamplerPanel extends javax.swing.JPanel { private static final Logger log = LoggingManager.getLoggerForClass(); private HTTPArgumentsPanel attributePanel; /** * Creates new form WebSocketSamplerPanel */ public WebSocketSamplerPanel() { initComponents(); attributePanel = new HTTPArgumentsPanel(); querystringAttributesPanel.add(attributePanel); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); serverAddressTextField = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); serverPortTextField = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jLabel3 = new javax.swing.JLabel(); connectionTimeoutTextField = new javax.swing.JTextField(); jLabel17 = new javax.swing.JLabel(); responseTimeoutTextField = new javax.swing.JTextField(); jPanel3 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); contextPathTextField = new javax.swing.JTextField(); protocolTextField = new javax.swing.JTextField(); contentEncodingTextField = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); connectionIdTextField = new javax.swing.JTextField(); querystringAttributesPanel = new javax.swing.JPanel(); ignoreSslErrorsCheckBox = new javax.swing.JCheckBox(); jScrollPane1 = new javax.swing.JScrollPane(); requestPayloadEditorPane = new javax.swing.JEditorPane(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); implementationComboBox = new javax.swing.JComboBox(); streamingConnectionCheckBox = new javax.swing.JCheckBox(); jPanel5 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); responsePatternTextField = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); closeConncectionPatternTextField = new javax.swing.JTextField(); jLabel16 = new javax.swing.JLabel(); messageBacklogTextField = new javax.swing.JTextField(); jPanel6 = new javax.swing.JPanel(); jLabel10 = new javax.swing.JLabel(); proxyAddressTextField = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); proxyPortTextField = new javax.swing.JTextField(); jLabel12 = new javax.swing.JLabel(); proxyUsernameTextField = new javax.swing.JTextField(); jLabel13 = new javax.swing.JLabel(); proxyPasswordTextField = new javax.swing.JTextField(); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Web Server")); jLabel1.setText("Server Name or IP:"); jLabel2.setText("Port Number:"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(serverAddressTextField) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(serverPortTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(serverAddressTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(serverPortTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Timeout (milliseconds)")); jLabel3.setText("Connection:"); jLabel17.setText("Response:"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(connectionTimeoutTextField) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel17) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(responseTimeoutTextField) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(connectionTimeoutTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel17) .addComponent(responseTimeoutTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("WebSocket Request")); jLabel4.setText("Protocol [ws/wss]:"); jLabel5.setText("Path:"); jLabel6.setText("Content encoding:"); protocolTextField.setToolTipText(""); jLabel8.setText("Connection Id:"); querystringAttributesPanel.setLayout(new javax.swing.BoxLayout(querystringAttributesPanel, javax.swing.BoxLayout.LINE_AXIS)); ignoreSslErrorsCheckBox.setText("Ignore SSL certificate errors"); jScrollPane1.setViewportView(requestPayloadEditorPane); jLabel14.setText("Request data"); jLabel15.setText("Implementation:"); implementationComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "RFC6455 (v13)" })); streamingConnectionCheckBox.setText("Streaming connection"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(querystringAttributesPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel15) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(implementationComboBox, 0, 1, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(protocolTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(contentEncodingTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(connectionIdTextField)) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel14) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(ignoreSslErrorsCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(streamingConnectionCheckBox))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(contextPathTextField))) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(protocolTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6) .addComponent(contentEncodingTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8) .addComponent(connectionIdTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel15) .addComponent(implementationComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(contextPathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ignoreSslErrorsCheckBox) .addComponent(streamingConnectionCheckBox)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(querystringAttributesPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE) .addGap(8, 8, 8) .addComponent(jLabel14) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE) .addContainerGap()) ); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("WebSocket Response")); jLabel7.setText("Response pattern:"); jLabel9.setText("Close connection pattern:"); jLabel16.setText("Message backlog:"); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(responsePatternTextField) .addGap(18, 18, 18) .addComponent(jLabel16) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(messageBacklogTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addComponent(jLabel9) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(closeConncectionPatternTextField))) .addContainerGap()) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel16) .addComponent(messageBacklogTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(responsePatternTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(closeConncectionPatternTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder("Proxy Server (currently not supported by Jetty)")); jLabel10.setText("Server Name or IP:"); jLabel11.setText("Port Number:"); jLabel12.setText("Username:"); jLabel13.setText("Password:"); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(proxyAddressTextField) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(proxyPortTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel12) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(proxyUsernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel13) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(proxyPasswordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(proxyUsernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel12)) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(proxyPortTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(proxyAddressTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel13) .addComponent(proxyPasswordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField closeConncectionPatternTextField; private javax.swing.JTextField connectionIdTextField; private javax.swing.JTextField connectionTimeoutTextField; private javax.swing.JTextField contentEncodingTextField; private javax.swing.JTextField contextPathTextField; private javax.swing.JCheckBox ignoreSslErrorsCheckBox; private javax.swing.JComboBox implementationComboBox; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField messageBacklogTextField; private javax.swing.JTextField protocolTextField; private javax.swing.JTextField proxyAddressTextField; private javax.swing.JTextField proxyPasswordTextField; private javax.swing.JTextField proxyPortTextField; private javax.swing.JTextField proxyUsernameTextField; private javax.swing.JPanel querystringAttributesPanel; private javax.swing.JEditorPane requestPayloadEditorPane; private javax.swing.JTextField responsePatternTextField; private javax.swing.JTextField responseTimeoutTextField; private javax.swing.JTextField serverAddressTextField; private javax.swing.JTextField serverPortTextField; private javax.swing.JCheckBox streamingConnectionCheckBox; // End of variables declaration//GEN-END:variables public void initFields() { } public void setCloseConncectionPattern(String closeConncectionPattern) { closeConncectionPatternTextField.setText(closeConncectionPattern); } public String getCloseConncectionPattern() { return closeConncectionPatternTextField.getText(); } public void setConnectionId(String connectionId) { connectionIdTextField.setText(connectionId); } public String getConnectionId() { return connectionIdTextField.getText(); } public void setContentEncoding(String contentEncoding) { contentEncodingTextField.setText(contentEncoding); } public String getContentEncoding() { return contentEncodingTextField.getText(); } public void setContextPath(String contextPath) { contextPathTextField.setText(contextPath); } public String getContextPath() { return contextPathTextField.getText(); } public void setProtocol(String protocol) { protocolTextField.setText(protocol); } public String getProtocol() { return protocolTextField.getText(); } public void setProxyAddress(String proxyAddress) { proxyAddressTextField.setText(proxyAddress); } public String getProxyAddress() { return proxyAddressTextField.getText(); } public void setProxyPassword(String proxyPassword) { proxyPasswordTextField.setText(proxyPassword); } public String getProxyPassword() { return proxyPasswordTextField.getText(); } public void setProxyPort(String proxyPort) { proxyPortTextField.setText(proxyPort); } public String getProxyPort() { return proxyPortTextField.getText(); } public void setProxyUsername(String proxyUsername) { proxyUsernameTextField.setText(proxyUsername); } public String getProxyUsername() { return proxyUsernameTextField.getText(); } public void setResponsePattern(String responsePattern) { responsePatternTextField.setText(responsePattern); } public String getResponsePattern() { return responsePatternTextField.getText(); } public void setResponseTimeout(String responseTimeout) { responseTimeoutTextField.setText(responseTimeout); } public String getResponseTimeout() { return responseTimeoutTextField.getText(); } public void setConnectionTimeout(String connectionTimeout) { connectionTimeoutTextField.setText(connectionTimeout); } public String getConnectionTimeout() { return connectionTimeoutTextField.getText(); } public void setServerAddress(String serverAddress) { serverAddressTextField.setText(serverAddress); } public String getServerAddress() { return serverAddressTextField.getText(); } public void setServerPort(String serverPort) { serverPortTextField.setText(serverPort); } public String getServerPort() { return serverPortTextField.getText(); } public void setRequestPayload(String requestPayload) { requestPayloadEditorPane.setText(requestPayload); } public String getRequestPayload() { return requestPayloadEditorPane.getText(); } public void setStreamingConnection(Boolean streamingConnection) { streamingConnectionCheckBox.setSelected(streamingConnection); } public Boolean isStreamingConnection() { return streamingConnectionCheckBox.isSelected(); } public void setIgnoreSslErrors(Boolean ignoreSslErrors) { ignoreSslErrorsCheckBox.setSelected(ignoreSslErrors); } public Boolean isIgnoreSslErrors() { return ignoreSslErrorsCheckBox.isSelected(); } public void setImplementation(String implementation) { implementationComboBox.setSelectedItem(implementation); } public String getImplementation() { return (String) implementationComboBox.getSelectedItem(); } public void setMessageBacklog(String messageBacklog) { messageBacklogTextField.setText(messageBacklog); } public String getMessageBacklog() { return messageBacklogTextField.getText(); } /** * @return the attributePanel */ public ArgumentsPanel getAttributePanel() { return attributePanel; } }
package com.j256.simplejmx.server; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.lang.management.ManagementFactory; import java.lang.reflect.Field; import java.net.InetAddress; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.concurrent.atomic.AtomicInteger; import javax.management.JMException; import javax.management.ObjectName; import javax.management.ReflectionException; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import com.j256.simplejmx.client.JmxClient; import com.j256.simplejmx.common.IoUtils; import com.j256.simplejmx.common.JmxAttributeField; import com.j256.simplejmx.common.JmxAttributeFieldInfo; import com.j256.simplejmx.common.JmxAttributeMethod; import com.j256.simplejmx.common.JmxAttributeMethodInfo; import com.j256.simplejmx.common.JmxFolderName; import com.j256.simplejmx.common.JmxOperation; import com.j256.simplejmx.common.JmxOperationInfo; import com.j256.simplejmx.common.JmxOperationInfo.OperationAction; import com.j256.simplejmx.common.JmxResource; import com.j256.simplejmx.common.JmxSelfNaming; import com.j256.simplejmx.common.ObjectNameUtil; import com.j256.simplejmx.server.JmxServer.LocalSocketFactory; public class JmxServerTest { private static final int DEFAULT_PORT = 5256; private static final String DOMAIN_NAME = "j256"; private static final String OBJECT_NAME = "testObject"; private static final int FOO_VALUE = 1459243; private static final String FOLDER_FIELD_NAME = "00"; private static final String FOLDER_VALUE_NAME = "FolderName"; private static final String FOLDER_NAME = FOLDER_FIELD_NAME + "=" + FOLDER_VALUE_NAME; private static JmxServer server; private static InetAddress serverAddress; private static AtomicInteger serverPortCounter = new AtomicInteger(DEFAULT_PORT); @BeforeClass public static void beforeClass() throws Exception { serverAddress = InetAddress.getByName("127.0.0.1"); server = new JmxServer(serverAddress, DEFAULT_PORT); server.start(); } @AfterClass public static void afterClass() { IoUtils.closeQuietly(server); System.gc(); } @Test public void testJmxServerStartStopStart() throws Exception { JmxServer server = new JmxServer(serverAddress, serverPortCounter.incrementAndGet()); try { server.stop(); server.start(); } finally { IoUtils.closeQuietly(server); } } @Test public void testJmxServerAddressTwoPorts() { int port = serverPortCounter.incrementAndGet(); JmxServer server = new JmxServer(serverAddress, port, port); IoUtils.closeQuietly(server); } @Test public void testJmxServerOnePort() { int port = serverPortCounter.incrementAndGet(); JmxServer server = new JmxServer(port); assertEquals(port, server.getRegistryPort()); assertEquals(port, server.getServerPort()); IoUtils.closeQuietly(server); } @Test public void testJmxServerTwoPorts() { int regPort = serverPortCounter.incrementAndGet(); int serverPort = serverPortCounter.incrementAndGet(); JmxServer server = new JmxServer(regPort, serverPort); assertEquals(regPort, server.getRegistryPort()); assertEquals(serverPort, server.getServerPort()); IoUtils.closeQuietly(server); } @Test public void testJmxServerNoPorts() { int registryPort = serverPortCounter.incrementAndGet(); int serverPort = serverPortCounter.incrementAndGet(); JmxServer server = new JmxServer(); server.setServerPort(serverPort); server.setRegistryPort(registryPort); assertEquals(registryPort, server.getRegistryPort()); assertEquals(serverPort, server.getServerPort()); IoUtils.closeQuietly(server); } @Test public void testCoverage() throws Exception { JmxServer server = new JmxServer(ManagementFactory.getPlatformMBeanServer()); server.start(); IoUtils.closeQuietly(server); server = new JmxServer(true); IoUtils.closeQuietly(server); server = new JmxServer(false); server.setUsePlatformMBeanServer(true); server.setUsePlatformMBeanServer(false); IoUtils.closeQuietly(server); server.setServerSocketFactory(null); server.close(); // LocalSocketFactory LocalSocketFactory lsf1 = new LocalSocketFactory(null); lsf1.hashCode(); assertTrue(lsf1.equals(lsf1)); LocalSocketFactory lsf2 = new LocalSocketFactory(InetAddress.getLocalHost()); lsf2.hashCode(); assertTrue(lsf2.equals(lsf2)); assertFalse(lsf2.equals(null)); assertFalse(lsf2.equals(new Object())); assertFalse(lsf1.equals(lsf2)); assertFalse(lsf2.equals(lsf1)); } @Test(expected = JMException.class) public void testNoStart() throws Exception { JmxServer server = new JmxServer(); server.register(this); server.close(); } @Test(expected = JMException.class) public void testNoStart2() throws Exception { JmxServer server = new JmxServer(); server.register(this, (ObjectName) null, null, null, null); server.close(); } @Test(expected = JMException.class) public void testNoStart3() throws Exception { JmxServer server = new JmxServer(); server.unregisterThrow((ObjectName) null); server.close(); } @Test public void testServiceUrl() throws Exception { int port = serverPortCounter.incrementAndGet(); JmxServer server = new JmxServer(port); server.setServiceUrl("service:jmx:rmi://127.0.0.1:" + port + "/jndi/rmi://127.0.0.1:" + port + "/jmxrmi"); server.start(); server.close(); } @Test(expected = JMException.class) public void testBadServiceUrl() throws Exception { int port = serverPortCounter.incrementAndGet(); JmxServer server = new JmxServer(port); server.setServiceUrl("service:blahblah"); server.start(); server.close(); } @Test(expected = JMException.class) public void testJmxServerDoubleInstance() throws Exception { int port = serverPortCounter.incrementAndGet(); JmxServer first = new JmxServer(serverAddress, port); JmxServer second = new JmxServer(serverAddress, port); try { first.start(); second.start(); } finally { IoUtils.closeQuietly(first); IoUtils.closeQuietly(second); } } @Test(expected = IllegalArgumentException.class) public void testJmxServerWildPort() throws Exception { JmxServer server = new JmxServer(serverAddress, -10); try { server.start(); } finally { IoUtils.closeQuietly(server); } } @Test(expected = JMException.class) public void testDoubleClose() throws Exception { JmxServer server = new JmxServer(serverAddress, serverPortCounter.incrementAndGet()); try { server.start(); } finally { Field field = server.getClass().getDeclaredField("rmiRegistry"); field.setAccessible(true); Registry rmiRegistry = (Registry) field.get(server); // close the rmi registry through trickery! UnicastRemoteObject.unexportObject(rmiRegistry, true); try { server.stopThrow(); } finally { IoUtils.closeQuietly(server); } } } @Test public void testJmxServerInt() throws Exception { JmxServer server = new JmxServer(); try { server.setPort(serverPortCounter.incrementAndGet()); server.setInetAddress(serverAddress); server.start(); } finally { IoUtils.closeQuietly(server); } } @Test(expected = IllegalStateException.class) public void testJmxServerStartNoPort() throws Exception { JmxServer server = new JmxServer(); try { server.start(); fail("Should not have gotten here"); } finally { IoUtils.closeQuietly(server); } } @Test public void testRegister() throws Exception { TestObject obj = new TestObject(); JmxClient client = null; try { client = new JmxClient(serverAddress, DEFAULT_PORT); try { client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo"); fail("should not get here"); } catch (Exception e) { // ignored } assertEquals(0, server.getRegisteredCount()); server.register(obj); assertEquals(1, server.getRegisteredCount()); assertEquals(FOO_VALUE, client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo")); int newValue = FOO_VALUE + 2; client.setAttribute(DOMAIN_NAME, OBJECT_NAME, "foo", newValue); assertEquals(newValue, client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo")); client.invokeOperation(DOMAIN_NAME, OBJECT_NAME, "resetFoo"); assertEquals(0, client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo")); newValue = FOO_VALUE + 12; client.invokeOperation(DOMAIN_NAME, OBJECT_NAME, "resetFoo", (Integer) newValue); assertEquals(newValue, client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo")); newValue = FOO_VALUE + 32; client.invokeOperation(DOMAIN_NAME, OBJECT_NAME, "resetFoo", Integer.toString(newValue)); assertEquals(newValue, client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo")); assertEquals(1, client.getAttributesInfo(DOMAIN_NAME, OBJECT_NAME).length); assertEquals(2, client.getOperationsInfo(DOMAIN_NAME, OBJECT_NAME).length); server.unregister(obj); try { client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo"); fail("should not get here"); } catch (Exception e) { // ignored } } finally { IoUtils.closeQuietly(client); server.unregister(obj); } } @Test(expected = JMException.class) public void testDoubleRegister() throws Exception { TestObject obj = new TestObject(); try { server.register(obj); server.register(obj); } finally { server.unregister(obj); } } @Test(expected = IllegalArgumentException.class) public void testRegisterNoJmxResource() throws Exception { try { // this class has no JmxResource annotation server.register(this); } finally { server.unregister(this); } } @Test(expected = JMException.class) public void testShortAttributeMethodName() throws Exception { ShortAttributeMethodName obj = new ShortAttributeMethodName(); try { server.register(obj); } finally { server.unregister(obj); } } @Test(expected = JMException.class) public void testJustGetAttributeMethodName() throws Exception { JustGet obj = new JustGet(); try { server.register(obj); } finally { server.unregister(obj); } } @Test public void testRegisterFolders() throws Exception { TestObjectFolders obj = new TestObjectFolders(); JmxClient client = null; try { server.register(obj); client = new JmxClient(serverAddress, DEFAULT_PORT); assertEquals(FOO_VALUE, client.getAttribute( ObjectNameUtil.makeObjectName(DOMAIN_NAME, OBJECT_NAME, new String[] { FOLDER_NAME }), "foo")); assertEquals(FOO_VALUE, client.getAttribute(ObjectNameUtil.makeObjectName(DOMAIN_NAME, OBJECT_NAME, new String[] { FOLDER_FIELD_NAME + "=" + FOLDER_VALUE_NAME }), "foo")); } finally { IoUtils.closeQuietly(client); server.unregister(obj); } } @Test public void testSelfNaming() throws Exception { SelfNaming obj = new SelfNaming(); JmxClient client = null; try { server.register(obj); client = new JmxClient(serverAddress, DEFAULT_PORT); assertEquals(FOO_VALUE, client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo")); } finally { IoUtils.closeQuietly(client); server.unregister(obj); } } @Test(expected = IllegalArgumentException.class) public void testInvalidDomain() throws Exception { InvalidDomain obj = new InvalidDomain(); try { server.register(obj); } finally { server.unregister(obj); } } @Test public void testNoDescriptions() throws Exception { NoDescriptions obj = new NoDescriptions(); JmxClient client = null; try { server.register(obj); client = new JmxClient(serverAddress, DEFAULT_PORT); assertEquals(FOO_VALUE, client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo")); } finally { IoUtils.closeQuietly(client); server.unregister(obj); } } @Test public void testHasDescription() throws Exception { HasDescriptions obj = new HasDescriptions(); JmxClient client = null; try { server.register(obj); client = new JmxClient(serverAddress, DEFAULT_PORT); assertEquals(FOO_VALUE, client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo")); } finally { IoUtils.closeQuietly(client); server.unregister(obj); } } @Test public void testOperationParameters() throws Exception { OperationParameters obj = new OperationParameters(); JmxClient client = null; try { server.register(obj); client = new JmxClient(serverAddress, DEFAULT_PORT); String someArg = "pfoewjfpeowjfewf ewopjfwefew"; assertEquals(someArg, client.invokeOperation(DOMAIN_NAME, OBJECT_NAME, "doSomething", someArg)); } finally { IoUtils.closeQuietly(client); server.unregister(obj); } } @Test(expected = ReflectionException.class) public void testThrowingGet() throws Exception { MisterThrow obj = new MisterThrow(); JmxClient client = null; try { server.register(obj); client = new JmxClient(serverAddress, DEFAULT_PORT); client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo"); } finally { IoUtils.closeQuietly(client); server.unregister(obj); } } @Test(expected = ReflectionException.class) public void testThrowingSet() throws Exception { MisterThrow obj = new MisterThrow(); JmxClient client = null; try { server.register(obj); client = new JmxClient(serverAddress, DEFAULT_PORT); client.setAttribute(DOMAIN_NAME, OBJECT_NAME, "foo", 0); } finally { IoUtils.closeQuietly(client); server.unregister(obj); } } @Test(expected = ReflectionException.class) public void testThrowingOperation() throws Exception { MisterThrow obj = new MisterThrow(); JmxClient client = null; try { server.register(obj); client = new JmxClient(serverAddress, DEFAULT_PORT); client.invokeOperation(DOMAIN_NAME, OBJECT_NAME, "someCall"); } finally { IoUtils.closeQuietly(client); server.unregister(obj); } } @Test public void testRegisterObjUserInfoFieldAttribute() throws Exception { RandomObject obj = new RandomObject(); ObjectName objectName = ObjectNameUtil.makeObjectName(DOMAIN_NAME, OBJECT_NAME); JmxClient client = null; try { server.register(obj, objectName, new JmxAttributeFieldInfo[] { new JmxAttributeFieldInfo("foo", true, false /* not writable */, "description") }, null, null); client = new JmxClient(serverAddress, DEFAULT_PORT); int val = 4232431; obj.setFoo(val); assertEquals(val, client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo")); try { client.setAttribute(DOMAIN_NAME, OBJECT_NAME, "foo", 1); fail("Expected this to throw"); } catch (JMException e) { // ignored } } finally { IoUtils.closeQuietly(client); server.unregister(objectName); } } @Test public void testRegisterObjUserInfoFieldMethod() throws Exception { RandomObject obj = new RandomObject(); ObjectName objectName = ObjectNameUtil.makeObjectName(DOMAIN_NAME, OBJECT_NAME); JmxClient client = null; try { server.register(obj, objectName, null, new JmxAttributeMethodInfo[] { new JmxAttributeMethodInfo("getFoo", "description"), new JmxAttributeMethodInfo("setFoo", "description") }, null); client = new JmxClient(serverAddress, DEFAULT_PORT); int val = 4232431; client.setAttribute(DOMAIN_NAME, OBJECT_NAME, "foo", val); assertEquals(val, client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo")); } finally { IoUtils.closeQuietly(client); server.unregister(objectName); } } @Test public void testRegisterObjUserInfoOperationOnly() throws Exception { RandomObject obj = new RandomObject(); ObjectName objectName = ObjectNameUtil.makeObjectName(DOMAIN_NAME, OBJECT_NAME); JmxClient client = null; try { server.register(obj, objectName, null, null, new JmxOperationInfo[] { new JmxOperationInfo("resetFoo", null, null, OperationAction.UNKNOWN, "description") }); client = new JmxClient(serverAddress, DEFAULT_PORT); obj.setFoo(1); client.invokeOperation(DOMAIN_NAME, OBJECT_NAME, "resetFoo"); assertEquals(0, obj.getFoo()); try { client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo"); fail("Expected this to throw"); } catch (JMException e) { // ignored } } finally { IoUtils.closeQuietly(client); server.unregister(objectName); } } @Ignore("this fails every so often") @Test public void testLoopBackAddress() throws Exception { testAddress(null, serverPortCounter.incrementAndGet()); } @Test public void testLocalAddress() throws Exception { testAddress(serverAddress, serverPortCounter.incrementAndGet()); } @Test public void testSubClass() throws Exception { SubClassTestObject obj = new SubClassTestObject(); JmxClient client = null; try { client = new JmxClient(serverAddress, DEFAULT_PORT); try { client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo"); fail("should not get here"); } catch (Exception e) { // ignored } server.register(obj); assertEquals(FOO_VALUE, client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo")); assertEquals(2, client.getAttributesInfo(DOMAIN_NAME, OBJECT_NAME).length); assertEquals(3, client.getOperationsInfo(DOMAIN_NAME, OBJECT_NAME).length); int newValue = FOO_VALUE + 2; client.setAttribute(DOMAIN_NAME, OBJECT_NAME, "foo", newValue); assertEquals(newValue, client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo")); client.invokeOperation(DOMAIN_NAME, OBJECT_NAME, "resetFoo"); assertEquals(0, client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo")); newValue = FOO_VALUE + 12; client.invokeOperation(DOMAIN_NAME, OBJECT_NAME, "resetFoo", newValue); assertEquals(newValue, client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo")); newValue = FOO_VALUE + 32; client.invokeOperation(DOMAIN_NAME, OBJECT_NAME, "resetFoo", Integer.toString(newValue)); assertEquals(newValue * 2, client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo")); server.unregister(obj); try { client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo"); fail("should not get here"); } catch (Exception e) { // ignored } } finally { IoUtils.closeQuietly(client); server.unregister(obj); } } /* =========================================================================================== */ private void testAddress(InetAddress address, int port) throws Exception { JmxServer server; if (address == null) { server = new JmxServer(port); } else { server = new JmxServer(address, port); } RandomObject obj = new RandomObject(); ObjectName objectName = ObjectNameUtil.makeObjectName(DOMAIN_NAME, OBJECT_NAME); JmxClient client = null; try { server.start(); server.register(obj, objectName, null, null, new JmxOperationInfo[] { new JmxOperationInfo("resetFoo", null, null, OperationAction.UNKNOWN, "description") }); if (address == null) { client = new JmxClient(port); } else { client = new JmxClient(address.getHostAddress(), port); } obj.setFoo(1); client.invokeOperation(DOMAIN_NAME, OBJECT_NAME, "resetFoo"); assertEquals(0, obj.getFoo()); try { client.getAttribute(DOMAIN_NAME, OBJECT_NAME, "foo"); fail("Expected this to throw"); } catch (JMException e) { // ignored } } finally { IoUtils.closeQuietly(client); server.unregister(objectName); IoUtils.closeQuietly(server); } } /* =========================================================================================== */ @JmxResource(domainName = DOMAIN_NAME, beanName = OBJECT_NAME) protected static class TestObject { private int foo = FOO_VALUE; @JmxAttributeMethod public int getFoo() { return foo; } @JmxAttributeMethod public void setFoo(int foo) { this.foo = foo; } @JmxOperation public void resetFoo() { this.foo = 0; } @JmxOperation public void resetFoo(int newValue) { this.foo = newValue; } } @JmxResource(domainName = DOMAIN_NAME, beanName = OBJECT_NAME, folderNames = { FOLDER_NAME }) protected static class TestObjectFolders { @JmxAttributeMethod public int getFoo() { return FOO_VALUE; } } @JmxResource(domainName = DOMAIN_NAME, beanName = OBJECT_NAME) protected static class ShortAttributeMethodName { @JmxAttributeMethod public int x() { return 0; } } @JmxResource(domainName = DOMAIN_NAME, beanName = OBJECT_NAME) protected static class JustGet { @JmxAttributeMethod public int get() { return 0; } } @JmxResource(domainName = "not the domain name", beanName = "not the object name") protected static class SelfNaming implements JmxSelfNaming { @JmxAttributeMethod public int getFoo() { return FOO_VALUE; } @Override public String getJmxDomainName() { return DOMAIN_NAME; } @Override public String getJmxBeanName() { return OBJECT_NAME; } @Override public JmxFolderName[] getJmxFolderNames() { return null; } } @JmxResource(domainName = "", beanName = OBJECT_NAME) protected static class InvalidDomain { @JmxAttributeMethod public int getFoo() { return FOO_VALUE; } } @JmxResource(domainName = DOMAIN_NAME, beanName = OBJECT_NAME) protected static class NoDescriptions { @JmxAttributeMethod public int getFoo() { return FOO_VALUE; } @JmxOperation public void doSomething() { } } @JmxResource(description = "Test object", domainName = DOMAIN_NAME, beanName = OBJECT_NAME) protected static class HasDescriptions { @JmxAttributeMethod(description = "Foo value") public int getFoo() { return FOO_VALUE; } } @JmxResource(domainName = DOMAIN_NAME, beanName = OBJECT_NAME) protected static class OperationParameters { @JmxOperation(description = "A value", parameterNames = { "first" }, parameterDescriptions = { "First argument" }) public String doSomething(String first) { return first; } } @JmxResource(domainName = DOMAIN_NAME, beanName = OBJECT_NAME) protected static class MisterThrow { @JmxAttributeMethod public int getFoo() { throw new IllegalStateException("because I can"); } @JmxAttributeMethod public void setFoo(int value) { throw new IllegalStateException("because I can"); } @JmxOperation public void someCall() { throw new IllegalStateException("because I can"); } } protected static class RandomObject { private int foo = FOO_VALUE; public int getFoo() { return foo; } public void setFoo(int foo) { this.foo = foo; } public void resetFoo() { this.foo = 0; } public void resetFoo(int newValue) { this.foo = newValue; } } @JmxResource(domainName = DOMAIN_NAME, beanName = OBJECT_NAME, description = "") protected static class SubClassTestObject extends TestObject { @JmxAttributeField private int bar; // this stops the jmx access @Override public void setFoo(int foo) { super.setFoo(foo); } // set it via a String @JmxOperation public void resetFoo(String newValue) { resetFoo(Integer.parseInt(newValue) * 2); } } }
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * */ package org.unitime.timetable.export.events; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TimeZone; import java.util.TreeSet; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.springframework.stereotype.Service; import org.unitime.commons.CalendarVTimeZoneGenerator; import org.unitime.timetable.defaults.ApplicationProperty; import org.unitime.timetable.export.ExportHelper; import org.unitime.timetable.gwt.client.events.EventComparator.EventMeetingSortBy; import org.unitime.timetable.gwt.shared.EventInterface; import org.unitime.timetable.gwt.shared.EventInterface.ApprovalStatus; import org.unitime.timetable.gwt.shared.EventInterface.ContactInterface; import org.unitime.timetable.gwt.shared.EventInterface.EventLookupRpcRequest; import org.unitime.timetable.gwt.shared.EventInterface.EventType; import org.unitime.timetable.gwt.shared.EventInterface.MeetingInterface; import org.unitime.timetable.gwt.shared.EventInterface.ResourceType; import org.unitime.timetable.model.CourseOffering; import org.unitime.timetable.model.Curriculum; import org.unitime.timetable.model.CurriculumClassification; import org.unitime.timetable.model.Department; import org.unitime.timetable.model.Location; import org.unitime.timetable.model.Session; import org.unitime.timetable.model.StudentGroup; import org.unitime.timetable.model.SubjectArea; import org.unitime.timetable.model.dao.CourseOfferingDAO; import org.unitime.timetable.model.dao.CurriculumClassificationDAO; import org.unitime.timetable.model.dao.CurriculumDAO; import org.unitime.timetable.model.dao.DepartmentDAO; import org.unitime.timetable.model.dao.LocationDAO; import org.unitime.timetable.model.dao.SessionDAO; import org.unitime.timetable.model.dao.StudentGroupDAO; import org.unitime.timetable.model.dao.SubjectAreaDAO; import org.unitime.timetable.model.dao._RootDAO; import org.unitime.timetable.util.Constants; import biweekly.ICalVersion; import biweekly.ICalendar; import biweekly.component.VEvent; import biweekly.io.text.ICalWriter; import biweekly.parameter.Role; import biweekly.property.Attendee; import biweekly.property.CalendarScale; import biweekly.property.DateEnd; import biweekly.property.DateStart; import biweekly.property.DateTimeStamp; import biweekly.property.ExceptionDates; import biweekly.property.Method; import biweekly.property.Organizer; import biweekly.property.RecurrenceId; import biweekly.property.Status; import biweekly.util.Recurrence; import biweekly.util.Recurrence.DayOfWeek; import biweekly.util.Recurrence.Frequency; /** * @author Tomas Muller */ @Service("org.unitime.timetable.export.Exporter:events.ics") public class EventsExportEventsToICal extends EventsExporter { private static Logger sLog = Logger.getLogger(EventsExportEventsToICal.class); @Override public String reference() { return "events.ics"; } @Override protected void print(ExportHelper helper, EventLookupRpcRequest request, List<EventInterface> events, int eventCookieFlags, EventMeetingSortBy sort, boolean asc) throws IOException { helper.setup("text/calendar", reference(), false); ICalendar ical = new ICalendar(); ical.setVersion(ICalVersion.V2_0); ical.setCalendarScale(CalendarScale.gregorian()); ical.setMethod(new Method("PUBLISH")); ical.setExperimentalProperty("X-WR-CALNAME", guessScheduleName(helper, request)); ical.setExperimentalProperty("X-WR-TIMEZONE", TimeZone.getDefault().getID()); ical.setProductId("-//UniTime LLC/UniTime " + Constants.getVersion() + " Events//EN"); for (EventInterface event: events) print(ical, event); ICalWriter writer = new ICalWriter(helper.getWriter(), ICalVersion.V2_0); try { writer.getTimezoneInfo().setGenerator(new CalendarVTimeZoneGenerator()); writer.getTimezoneInfo().setDefaultTimeZone(TimeZone.getDefault()); } catch (IllegalArgumentException e) { sLog.warn("Failed to set default time zone: " + e.getMessage()); } try { writer.write(ical); writer.flush(); } finally { writer.close(); } } public boolean print(ICalendar ical, EventInterface event) throws IOException { return print(ical, event, null); } protected String guessScheduleName(ExportHelper helper, EventLookupRpcRequest request) { org.hibernate.Session hibSession = new _RootDAO().getSession(); String name = MESSAGES.scheduleNameDefault(); if (request.getResourceType() == ResourceType.PERSON) { name = MESSAGES.pagePersonalTimetable(); } else if (helper.getParameter("name") != null) { name = MESSAGES.scheduleNameForResource(Constants.toInitialCase(helper.getParameter("name"))); } else { String resource = getResourceName(request, hibSession); if (resource != null) name = MESSAGES.scheduleNameForResource(resource); else if (request.getResourceType() != null && request.getResourceType() != ResourceType.ROOM) name = CONSTANTS.resourceType()[request.getResourceType().ordinal()]; } boolean allSessions = request.getEventFilter().hasOption("flag") && request.getEventFilter().getOptions("flag").contains("All Sessions"); if (!allSessions && request.getSessionId() != null) { Session session = SessionDAO.getInstance().get(request.getSessionId(), hibSession); name = MESSAGES.scheduleNameForSession(name, session.getAcademicTerm(), session.getAcademicYear()); } return name; } public String getResourceName(EventLookupRpcRequest request, org.hibernate.Session hibSession) { if (request.getResourceType() != null && request.getResourceId() != null) { switch (request.getResourceType()) { case ROOM: Location location = LocationDAO.getInstance().get(request.getResourceId(), hibSession); if (location != null) return location.getDisplayName() == null ? location.getLabel() : location.getDisplayName(); break; case SUBJECT: SubjectArea subject = SubjectAreaDAO.getInstance().get(request.getResourceId(), hibSession); if (subject != null) return subject.getSubjectAreaAbbreviation(); break; case COURSE: CourseOffering course = CourseOfferingDAO.getInstance().get(request.getResourceId(), hibSession); if (course != null) return course.getCourseName(); break; case CURRICULUM: Curriculum curriculum = CurriculumDAO.getInstance().get(request.getResourceId(), hibSession); if (curriculum != null) return (curriculum.getAbbv() == null ? curriculum.getAcademicArea().getAcademicAreaAbbreviation() : curriculum.getAbbv()); CurriculumClassification clasf = CurriculumClassificationDAO.getInstance().get(request.getResourceId(), hibSession); if (clasf != null) return (clasf.getCurriculum().getAbbv() == null ? clasf.getCurriculum().getAcademicArea().getAcademicAreaAbbreviation() : clasf.getCurriculum().getAbbv()) + " " + (clasf.getName() == null ? clasf.getAcademicClassification().getCode() : clasf.getName()); break; case DEPARTMENT: Department department = DepartmentDAO.getInstance().get(request.getResourceId(), hibSession); if (department != null) return department.getAbbreviation() == null ? department.getDeptCode() : department.getAbbreviation(); break; case GROUP: StudentGroup group = StudentGroupDAO.getInstance().get(request.getResourceId(), hibSession); if (group != null) return group.getGroupAbbreviation(); break; } } if (request.getEventFilter().hasOption("room")) { Location location = LocationDAO.getInstance().get(Long.valueOf(request.getEventFilter().getOption("room")), hibSession); if (location != null) return location.getDisplayName() == null ? location.getLabel() : location.getDisplayName(); } return null; } public boolean print(ICalendar ical, EventInterface event, Status status) throws IOException { if (event.getType() == EventType.Unavailabile) return false; TreeSet<ICalendarMeeting> meetings = new TreeSet<ICalendarMeeting>(); Set<Integer> days = new TreeSet<Integer>(); if (event.hasMeetings()) meetings: for (MeetingInterface m: event.getMeetings()) { if (m.isArrangeHours()) continue; if (m.getApprovalStatus() != ApprovalStatus.Approved && m.getApprovalStatus() != ApprovalStatus.Pending) continue; ICalendarMeeting x = new ICalendarMeeting(m, status); for (ICalendarMeeting icm: meetings) if (icm.merge(x)) continue meetings; meetings.add(x); days.add(x.getStart().getDayOfWeek()); } if (meetings.isEmpty()) return false; ICalendarMeeting first = meetings.first(); VEvent master = new VEvent(); master.setDateStart(first.getDateStart()); master.setDateEnd(first.getDateEnd()); master.setLocation(first.getLocation()); master.setStatus(first.getStatus()); List<VEvent> events = new ArrayList<VEvent>(); events.add(master); if (meetings.size() > 1) { // last day of the recurrence DateTime until = new DateTime(meetings.last().getStart().getYear(), meetings.last().getStart().getMonthOfYear(), meetings.last().getStart().getDayOfMonth(), first.getEnd().getHourOfDay(), first.getEnd().getMinuteOfHour(), first.getEnd().getSecondOfMinute()); // count meeting days int nrMeetingDays = 0; for (DateTime date = first.getStart(); !date.isAfter(until); date = date.plusDays(1)) { // skip days of week with no meeting if (days.contains(date.getDayOfWeek())) nrMeetingDays ++; } // make sure that there is enough meeting days to cover all meetings while (nrMeetingDays < meetings.size()) { until = until.plusDays(1); if (days.contains(until.getDayOfWeek())) nrMeetingDays ++; } Recurrence.Builder recur = new Recurrence.Builder(Frequency.WEEKLY); for (Iterator<Integer> i = days.iterator(); i.hasNext(); ) { switch (i.next()) { case DateTimeConstants.MONDAY: recur.byDay(DayOfWeek.MONDAY); break; case DateTimeConstants.TUESDAY: recur.byDay(DayOfWeek.TUESDAY); break; case DateTimeConstants.WEDNESDAY: recur.byDay(DayOfWeek.WEDNESDAY); break; case DateTimeConstants.THURSDAY: recur.byDay(DayOfWeek.THURSDAY); break; case DateTimeConstants.FRIDAY: recur.byDay(DayOfWeek.FRIDAY); break; case DateTimeConstants.SATURDAY: recur.byDay(DayOfWeek.SATURDAY); break; case DateTimeConstants.SUNDAY: recur.byDay(DayOfWeek.SUNDAY); break; } } recur.workweekStarts(DayOfWeek.MONDAY).until(until.toDate()); master.setRecurrenceRule(recur.build()); ExceptionDates exdates = new ExceptionDates(); // for all dates till the last date dates: for (DateTime date = first.getStart(); !date.isAfter(until); date = date.plusDays(1)) { // skip days of week with no meeting if (!days.contains(date.getDayOfWeek())) continue; // try to find a fully matching meeting for (Iterator<ICalendarMeeting> i = meetings.iterator(); i.hasNext();) { ICalendarMeeting ics = i.next(); if (date.getYear() == ics.getStart().getYear() && date.getDayOfYear() == ics.getStart().getDayOfYear() && first.same(ics)) { i.remove(); continue dates; } } // try to find a meeting that is on the same day for (Iterator<ICalendarMeeting> i = meetings.iterator(); i.hasNext();) { ICalendarMeeting ics = i.next(); if (date.getYear() == ics.getStart().getYear() && date.getDayOfYear() == ics.getStart().getDayOfYear()) { VEvent x = new VEvent(); RecurrenceId id = new RecurrenceId(date.toDate(), true); x.setRecurrenceId(id); x.setDateStart(ics.getDateStart()); x.setDateEnd(ics.getDateEnd()); x.setLocation(ics.getLocation()); x.setStatus(ics.getStatus()); events.add(x); i.remove(); continue dates; } } // add exception exdates.addValue(date.toDate()); } // process remaining meetings for (ICalendarMeeting ics: meetings) { VEvent x = new VEvent(); x.setDateStart(ics.getDateStart()); x.setDateEnd(ics.getDateEnd()); x.setLocation(ics.getLocation()); x.setStatus(ics.getStatus()); // use exception as recurrence if there is one available if (!exdates.getValues().isEmpty()) { RecurrenceId id = new RecurrenceId(exdates.getValues().get(0), true); x.setRecurrenceId(id); exdates.getValues().remove(0); } events.add(x); } if (!exdates.getValues().isEmpty()) master.addExceptionDates(exdates); } for (VEvent vevent: events) { vevent.setSequence(event.getSequence()); vevent.setUid(event.getId().toString()); String name = event.getName(); String description = (event.hasInstruction() ? event.getInstruction() : event.getType().getName(CONSTANTS)); if (event.hasCourseTitles() && event.getType() == EventType.Class && ApplicationProperty.EventGridDisplayTitle.isTrue()) { name = event.getCourseTitles().get(0); if (event.hasInstruction() && event.hasExternalIds()) description = event.getInstruction() + " " + event.getExternalIds().get(0); else if (event.hasInstruction() && event.hasSectionNumber()) description = event.getInstruction() + " " + event.getSectionNumber(); } if (event.hasInstructors() && ApplicationProperty.EventCalendarDisplayInstructorsInDescription.isTrue()) { for (ContactInterface instructor: event.getInstructors()) description += "\n" + instructor.getName(MESSAGES); } vevent.setSummary(name); vevent.setDescription(description); if (event.hasTimeStamp()) { DateTimeStamp ts = new DateTimeStamp(event.getTimeStamp()); vevent.setDateTimeStamp(ts); } if (ApplicationProperty.EventCalendarSetOrganizer.isTrue()) { if (event.hasInstructors()) { int idx = 0; for (ContactInterface instructor: event.getInstructors()) { if (idx++ == 0) { Organizer organizer = new Organizer(instructor.getName(MESSAGES), (instructor.hasEmail() ? instructor.getEmail() : "")); vevent.setOrganizer(organizer); } else { Attendee attendee = new Attendee(instructor.getName(MESSAGES), (instructor.hasEmail() ? instructor.getEmail() : "")); attendee.setRole(Role.CHAIR); vevent.addAttendee(attendee); } } } else if (event.hasSponsor()) { Organizer organizer = new Organizer(event.getSponsor().getName(), (event.getSponsor().hasEmail() ? event.getSponsor().getEmail() : "")); vevent.setOrganizer(organizer); } else if (event.hasContact()) { Organizer organizer = new Organizer(event.getContact().getName(MESSAGES), (event.getContact().hasEmail() ? event.getContact().getEmail() : "")); vevent.setOrganizer(organizer); } } else { if (event.hasInstructors()) { int idx = 0; for (ContactInterface instructor: event.getInstructors()) { if (idx++ == 0) { Attendee organizer = new Attendee(instructor.getName(MESSAGES), (instructor.hasEmail() ? instructor.getEmail() : "")); organizer.setRole(Role.ORGANIZER); vevent.addAttendee(organizer); } else { Attendee attendee = new Attendee(instructor.getName(MESSAGES), (instructor.hasEmail() ? instructor.getEmail() : "")); attendee.setRole(Role.CHAIR); vevent.addAttendee(attendee); } } } else if (event.hasSponsor()) { Attendee organizer = new Attendee(event.getSponsor().getName(), (event.getSponsor().hasEmail() ? event.getSponsor().getEmail() : "")); organizer.setRole(Role.ORGANIZER); vevent.addAttendee(organizer); } else if (event.hasContact() && event.getType() != EventType.Class && event.getType() != EventType.FinalExam && event.getType() != EventType.MidtermExam) { Attendee organizer = new Attendee(event.getContact().getName(MESSAGES), (event.getContact().hasEmail() ? event.getContact().getEmail() : "")); organizer.setRole(Role.ORGANIZER); vevent.addAttendee(organizer); } } ical.addEvent(vevent); } return true; } public class ICalendarMeeting implements Comparable<ICalendarMeeting>{ private DateTime iStart, iEnd; private String iLocation; private Status iStatus; public ICalendarMeeting(MeetingInterface meeting, Status status) { if (meeting.getStartTime() != null) { iStart = new DateTime(meeting.getStartTime()); } else { iStart = new DateTime(meeting.getMeetingDate()).plusMinutes((5 * meeting.getStartSlot()) + meeting.getStartOffset()); } if (meeting.getStartTime() != null) { iEnd = new DateTime(meeting.getStopTime()); } else { iEnd = new DateTime(meeting.getMeetingDate()).plusMinutes((5 * meeting.getEndSlot()) + meeting.getEndOffset()); } if (iStart.getSecondOfMinute() != 0) iStart = iStart.minusSeconds(iStart.getSecondOfMinute()); if (iEnd.getSecondOfMinute() != 0) iEnd = iEnd.minusSeconds(iEnd.getSecondOfMinute()); if (iStart.getMillisOfSecond() != 0) iStart = iStart.minusMillis(iStart.getMillisOfSecond()); if (iEnd.getMillisOfSecond() != 0) iEnd = iEnd.minusMillis(iEnd.getMillisOfSecond()); iLocation = meeting.getLocationName(MESSAGES); iStatus = (status != null ? status : meeting.isApproved() ? Status.confirmed() : Status.tentative()); } public DateTime getStart() { return iStart; } public DateStart getDateStart() { DateStart ds = new DateStart(iStart.toDate(), true); return ds; } public DateTime getEnd() { return iEnd; } public DateEnd getDateEnd() { DateEnd de = new DateEnd(iEnd.toDate(), true); return de; } public String getLocation() { return iLocation; } public Status getStatus() { return iStatus; } public boolean merge(ICalendarMeeting m) { if (m.getStart().equals(getStart()) && m.getEnd().equals(getEnd())) { if (m.getStatus().isTentative()) iStatus = Status.tentative(); iLocation += ", " + m.getLocation(); return true; } return false; } public boolean same(ICalendarMeeting m) { return m.getStart().getSecondOfDay() == getStart().getSecondOfDay() && m.getEnd().getSecondOfDay() == getEnd().getSecondOfDay() && getLocation().equals(m.getLocation()) && getStatus().getValue().equals(m.getStatus().getValue()); } public int compareTo(ICalendarMeeting m) { int cmp = getStart().compareTo(m.getStart()); if (cmp != 0) return cmp; return getEnd().compareTo(m.getEnd()); } } }
/* * Copyright 2014 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 android.orm.model; import android.orm.sql.Column; import android.orm.sql.Reader; import android.orm.sql.Value; import android.orm.sql.Writable; import android.orm.sql.Writer; import android.orm.sql.fragment.Predicate; import android.orm.util.Function; import android.orm.util.Maybe; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.jetbrains.annotations.NonNls; import static android.orm.sql.Value.Write.Operation.Update; import static android.orm.util.Maybes.nothing; import static android.orm.util.Maybes.something; public class Version extends Instance.ReadWrite.Base implements Observer.ReadWrite { private static final Function<Long, Long> INCREMENT = new Function<Long, Long>() { @NonNull @Override public Long invoke(@NonNull final Long value) { return value + 1; } }; @NonNull private final Mapper mMapper; @NonNull private final Observer.ReadWrite mObserver; private final Instance.Setter<Long> mSetter = new Instance.Setter<Long>() { @Override public void set(@Nullable final Long current) { mCurrent = something(current); } }; @NonNull private Maybe<Long> mCurrent = nothing(); public Version(@NonNull final Column<Long> column, @Nullable final Observer.ReadWrite observer) { super(); mMapper = new Mapper(column); mObserver = (observer == null) ? DUMMY : observer; } @Nullable public final Long get() { return mCurrent.getOrElse(null); } public final void set(final long version) { mCurrent = something(version); } @NonNull @Override public final String getName() { return mMapper.getName(); } @NonNull @Override public final Instance.Readable.Action prepareRead() { return Instances.action(mMapper, mSetter); } @NonNull @Override public final Writer prepareWriter() { return mMapper.prepareWriter(mCurrent); } @Override public final void beforeRead() { mObserver.beforeRead(); } @Override public final void afterRead() { mObserver.afterRead(); } @Override public final void beforeInsert() { mObserver.beforeInsert(); } @Override public final void afterInsert() { mObserver.afterInsert(); } @Override public final void beforeUpdate() { mObserver.beforeUpdate(); } @Override public final void afterUpdate() { mCurrent = mCurrent.map(INCREMENT); mObserver.afterUpdate(); } @Override public final void beforeSave() { mObserver.beforeSave(); } @Override public final void afterSave() { mObserver.afterSave(); } public static class Mapper extends android.orm.model.Mapper.ReadWrite.Base<Long> { @NonNull private final Column<Long> mColumn; @NonNls @NonNull private final String mName; @NonNull private final Reader.Element.Create<Long> mReader; public Mapper(@NonNull final Column<Long> column) { super(); mColumn = column; mName = column.getName(); mReader = Plan.Read.from(mColumn); } @NonNull @Override public final String getName() { return mName; } @NonNull @Override public final Reader.Element.Create<Long> prepareReader() { return mReader; } @NonNull @Override public final Reader.Element.Create<Long> prepareReader(@NonNull final Long current) { return mReader; } @NonNull @Override public final Writer prepareWriter(@NonNull final Maybe<Long> value) { return new Write(mColumn, value); } } private static class Write implements Writer { @NonNull private final Column<Long> mColumn; @NonNull private final Maybe<Long> mValue; @NonNull private final Predicate mOnUpdate; private Write(@NonNull final Column<Long> column, @NonNull final Maybe<Long> value) { super(); mColumn = column; mValue = value; final Long current = value.getOrElse(null); mOnUpdate = (current == null) ? Predicate.Fail : Predicate.on(column).isEqualTo(current); } @NonNull @Override public final Predicate onUpdate() { return mOnUpdate; } @Override public final void write(@NonNull final Value.Write.Operation operation, @NonNull final Writable output) { final Maybe<Long> value = (operation == Update) ? mValue.map(INCREMENT) : mValue; mColumn.write(operation, value, output); } } }
package com.ookamijin.cheskers; import java.util.ArrayList; public class PlayerHet extends Player { public PlayerHet(Board gameBoard) { super(gameBoard); name = "Heterogenus"; isHet = true; scoreLocation = new Coord(80, 123); poolBounds.set(40, 200, 120, 360); nameX = 0; nameY = 0; } public PlayerHet() { super(); name = "Heterogenus"; isHet = true; scoreLocation = new Coord(80, 123); poolBounds.set(40, 200, 120, 360); nameX = 0; nameY = 0; } @Override public boolean isValid(ArrayList<Coord> tilePath, Chip userChip, ArrayList<Coord> targets) { boolean verdict = false; if (super.isValid(tilePath, userChip, targets)) return true; // one piece jump if (tilePath.size() == 3) { return oneJump(tilePath, userChip, targets); } else if (tilePath.size() > 3 && (tilePath.size() - 2) % 3 != 0) { return false; } else { for (int i = 0; i < (tilePath.size() + 1) / 3; ++i) { ArrayList<Coord> subCoord = new ArrayList<Coord>(); for (int j = 0; j < 3; ++j) { subCoord.add(tilePath.get(i * 2 + j)); } verdict = oneJump(subCoord, userChip, targets); } } return verdict; } private boolean oneJump(ArrayList<Coord> tilePath, Chip userChip, ArrayList<Coord> targets) { boolean verdict = false; if (userChip.isRed()) { verdict = mBoard.tileHasYellow(tilePath.get(1)); } else verdict = mBoard.tileHasRed(tilePath.get(1)); if (verdict) { ++score; targets.add(tilePath.get(1)); } return verdict; } @Override public boolean isBonus(ArrayList<Coord> tilePath, Chip userChip) { Tile mTile = mBoard.getTile(tilePath.get(tilePath.size() - 1)); if (userChip.isRed()) { return mTile.isBonusYellow(); } return mTile.isBonusRed(); } @Override public ArrayList<Coord> doRobot(Board mBoard) { this.mBoard = mBoard; ArrayList<ArrayList<Coord>> moveList; moveList = findAllMoves(); // start debug debug("in robot movelist size is " + moveList.size()); for (int i = 0; i < moveList.size(); ++i) { debug("move " + i + " is: "); debug("its size is " + moveList.get(i).size()); ArrayList<Coord> move = moveList.get(i); for (int j = 0; j < move.size(); ++j) { move.get(j).display(); } } // end debug return pickPriority(moveList); } @Override protected ArrayList<ArrayList<Coord>> findAllMoves() { ArrayList<ArrayList<Coord>> moveList = new ArrayList<ArrayList<Coord>>(); ArrayList<Coord> mTilePath; // search each tile TTBLTR for (int j = 0; j < 6; ++j) { for (int i = 0; i < 6; ++i) { Coord startCoord = new Coord(i, j); debug("searching coord " + i + ", " + j); // tile has chip if (!mBoard.tileHasNothing(startCoord)) { Chip objectChip = mBoard.getChip(startCoord); mTilePath = new ArrayList<Coord>(); if (validLeftMove(startCoord, objectChip, mTilePath)) { moveList.add(mTilePath); } mTilePath = new ArrayList<Coord>(); if (validUpMove(startCoord, objectChip, mTilePath)) { moveList.add(mTilePath); } mTilePath = new ArrayList<Coord>(); if (validRightMove(startCoord, objectChip, mTilePath)) { moveList.add(mTilePath); } mTilePath = new ArrayList<Coord>(); if (validDownMove(startCoord, objectChip, mTilePath)) { moveList.add(mTilePath); } addBufferMoves(startCoord, moveList); } } } return moveList; } private boolean validUpMove(Coord startCoord, Chip objectChip, ArrayList<Coord> mTilePath) { boolean verdict = false; int x = startCoord.getX(); int y = startCoord.getY(); if (y - 2 >= 0) { debug("it was a valid target coord to search up of"); // add move to moveList if (mBoard.tileHasOpposite(new Coord(x, y - 1), objectChip) && mBoard.tileHasNothing(new Coord(x, y - 2))) { debug("up search satisfies rules"); if (mTilePath.size() < 1) { mTilePath.add(new Coord(x, y)); } mTilePath.add(new Coord(x, y - 1)); mTilePath.add(new Coord(x, y - 2)); verdict = true; // double move if (!validUpMove(mTilePath.get(mTilePath.size() - 1), objectChip, mTilePath)) { if (!validRightMove(mTilePath.get(mTilePath.size() - 1), objectChip, mTilePath)) { validLeftMove(mTilePath.get(mTilePath.size() - 1), objectChip, mTilePath); } } } } mTilePath = null; return verdict; } private boolean validDownMove(Coord startCoord, Chip objectChip, ArrayList<Coord> mTilePath) { boolean verdict = false; int x = startCoord.getX(); int y = startCoord.getY(); debug("valid down is checking:"); startCoord.display(); if (y + 2 <= 5) { debug("it was a valid target coord to search down of"); // add move to moveList if (mBoard.tileHasOpposite(new Coord(x, y + 1), objectChip) && mBoard.tileHasNothing(new Coord(x, y + 2))) { debug("down search satisfies rules"); if (mTilePath.size() < 1) { mTilePath.add(new Coord(x, y)); } mTilePath.add(new Coord(x, y + 1)); mTilePath.add(new Coord(x, y + 2)); verdict = true; // double move if (!validDownMove(mTilePath.get(mTilePath.size() - 1), objectChip, mTilePath)) { if (!validRightMove(mTilePath.get(mTilePath.size() - 1), objectChip, mTilePath)) { validLeftMove(mTilePath.get(mTilePath.size() - 1), objectChip, mTilePath); } } } } mTilePath = null; return verdict; } private boolean validLeftMove(Coord startCoord, Chip objectChip, ArrayList<Coord> mTilePath) { boolean verdict = false; int x = startCoord.getX(); int y = startCoord.getY(); if (x - 2 >= 0) { debug("it was a valid target coord to search left of"); // add move to moveList if (mBoard.tileHasOpposite(new Coord(x - 1, y), objectChip) && mBoard.tileHasNothing(new Coord(x - 2, y))) { debug("left search satisfies rules"); if (mTilePath.size() < 1) { mTilePath.add(new Coord(x, y)); } mTilePath.add(new Coord(x - 1, y)); mTilePath.add(new Coord(x - 2, y)); verdict = true; // double move if (!validUpMove(mTilePath.get(mTilePath.size() - 1), objectChip, mTilePath)) { if (!validDownMove(mTilePath.get(mTilePath.size() - 1), objectChip, mTilePath)) { validLeftMove(mTilePath.get(mTilePath.size() - 1), objectChip, mTilePath); } } } } mTilePath = null; return verdict; } private boolean validRightMove(Coord startCoord, Chip objectChip, ArrayList<Coord> mTilePath) { boolean verdict = false; int x = startCoord.getX(); int y = startCoord.getY(); if (x + 2 <= 5) { debug("it was a valid target coord to search right of"); // add move to moveList if (mBoard.tileHasOpposite(new Coord(x + 1, y), objectChip) && mBoard.tileHasNothing(new Coord(x + 2, y))) { debug("right search satisfies rules"); if (mTilePath.size() < 1) { mTilePath.add(new Coord(x, y)); } mTilePath.add(new Coord(x + 1, y)); mTilePath.add(new Coord(x + 2, y)); verdict = true; // double move if (!validUpMove(mTilePath.get(mTilePath.size() - 1), objectChip, mTilePath)) { if (!validDownMove(mTilePath.get(mTilePath.size() - 1), objectChip, mTilePath)) { validRightMove(mTilePath.get(mTilePath.size() - 1), objectChip, mTilePath); } } } } mTilePath = null; return verdict; } protected ArrayList<Coord> pickPriority(ArrayList<ArrayList<Coord>> moveList) { // sub array of double move options. ArrayList<ArrayList<Coord>> subList = new ArrayList<ArrayList<Coord>>(); for (int i = 0; i < moveList.size(); ++i) { if (moveList.get(i).size() > 3) { subList.add(moveList.get(i)); } } if (subList.size() > 0) { moveList = subList; } else { // no double moves, sub array of single moves with bonus for (int i = 0; i < moveList.size(); ++i) { if (moveList.get(i).size() == 3) { if (isRobotBonus(moveList.get(i))) subList.add(moveList.get(i)); } } } if (subList.size() > 0) { moveList = subList; } else { // no bonuses, sub array of single moves for (int i = 0; i < moveList.size(); ++i) { if (moveList.get(i).size() == 3) subList.add(moveList.get(i)); } } if (subList.size() > 0) moveList = subList; if (moveList.size() > 1) tilePath = moveList.get(gen.nextInt(moveList.size() - 1)); else tilePath = moveList.get(0); return tilePath; } private boolean isRobotBonus(ArrayList<Coord> tilePath) { if (mBoard.tileHasRed(tilePath.get(0)) && mBoard.tileIsBonusYellow(tilePath.get(2))) return true; if (mBoard.tileHasYellow(tilePath.get(0)) && mBoard.tileIsBonusRed(tilePath.get(2))) return true; return false; } }
/** * Copyright (C) 2016 Hurence (support@hurence.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hurence.logisland.connect; import com.hurence.logisland.classloading.PluginProxy; import com.hurence.logisland.component.ComponentFactory; import com.hurence.logisland.connect.source.KafkaConnectStreamSourceProvider; import org.apache.kafka.connect.connector.Connector; import org.apache.kafka.connect.connector.ConnectorContext; import org.apache.kafka.connect.connector.Task; import org.apache.kafka.connect.errors.DataException; import org.apache.kafka.connect.json.JsonConverter; import org.apache.kafka.connect.storage.Converter; import org.apache.kafka.connect.storage.OffsetBackingStore; import org.apache.spark.sql.SQLContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; /** * Kafka connect to spark sql streaming bridge. * * @author amarziali */ public abstract class AbstractKafkaConnectComponent<T extends Connector, U extends Task> { private final static Logger LOGGER = LoggerFactory.getLogger(AbstractKafkaConnectComponent.class); protected final T connector; protected final List<U> tasks = new ArrayList<>(); protected final OffsetBackingStore offsetBackingStore; protected final AtomicBoolean startWatch = new AtomicBoolean(false); protected final String connectorName; private final Map<String, String> connectorProperties; protected final SQLContext sqlContext; protected final Converter keyConverter; protected final Converter valueConverter; protected final int maxTasks; protected final String streamId; /** * Base constructor. Should be called by {@link KafkaConnectStreamSourceProvider} * * @param sqlContext the spark sql context. * @param connectorProperties the connector related properties. * @param keyConverter the converter for the data key * @param valueConverter the converter for the data body * @param offsetBackingStore the backing store implementation (can be in-memory, file based, kafka based, etc...) * @param maxTasks the maximum theoretical number of tasks this source should spawn. * @param connectorClass the class of kafka connect source connector to wrap. * @param streamId the Stream id. * */ public AbstractKafkaConnectComponent(SQLContext sqlContext, Map<String, String> connectorProperties, Converter keyConverter, Converter valueConverter, OffsetBackingStore offsetBackingStore, int maxTasks, String connectorClass, String streamId) { try { this.sqlContext = sqlContext; this.maxTasks = maxTasks; //instantiate connector this.connectorName = connectorClass; connector = ComponentFactory.loadComponent(connectorClass); //create converters this.keyConverter = keyConverter; this.valueConverter = valueConverter; this.connectorProperties = connectorProperties; this.streamId = streamId; //Create the connector context final ConnectorContext connectorContext = new ConnectorContext() { @Override public void requestTaskReconfiguration() { try { stopAllTasks(); createAndStartAllTasks(); } catch (Throwable t) { LOGGER.error("Unable to reconfigure tasks for connector " + connectorName(), t); } } @Override public void raiseError(Exception e) { LOGGER.error("Connector " + connectorName() + " raised error : " + e.getMessage(), e); } }; LOGGER.info("Starting connector {}", connectorClass); connector.initialize(connectorContext); this.offsetBackingStore = offsetBackingStore; } catch (Exception e) { throw new DataException("Unable to create connector " + connectorName(), e); } } public void start() { try { offsetBackingStore.start(); //create and start tasks createAndStartAllTasks(); } catch (Exception e) { try { stop(); } catch (Throwable t) { LOGGER.error("Unable to properly stop tasks of connector " + connectorName(), t); } throw new DataException("Unable to start connector " + connectorName(), e); } } protected abstract void initialize(U task); /** * Create all the {@link Runnable} workers needed to host the source tasks. * * @return * @throws IllegalAccessException if task instantiation fails. * @throws InstantiationException if task instantiation fails. */ protected void createAndStartAllTasks() throws IllegalAccessException, InstantiationException, ClassNotFoundException { if (!startWatch.compareAndSet(false, true)) { throw new IllegalStateException("Connector is already started"); } connector.start(connectorProperties); Class<U> taskClass = (Class<U>) connector.taskClass(); List<Map<String, String>> configs = connector.taskConfigs(maxTasks); tasks.clear(); LOGGER.info("Creating {} tasks for connector {}", configs.size(), connectorName()); for (Map<String, String> conf : configs) { //create the task U task = PluginProxy.create(taskClass.newInstance()); initialize(task); task.start(conf); tasks.add(task); } } /** * Create a converter to be used to translate internal data. * Child classes can override this method to provide alternative converters. * * @return an instance of {@link Converter} */ protected Converter createInternalConverter(boolean isKey) { JsonConverter internalConverter = new JsonConverter(); internalConverter.configure(Collections.singletonMap("schemas.enable", "false"), isKey); return internalConverter; } /** * Gets the connector name used by this stream source. * * @return */ protected String connectorName() { return connectorName; } /** * Stops every tasks running and serving for this connector. */ protected void stopAllTasks() { LOGGER.info("Stopping every tasks for connector {}", connectorName()); while (!tasks.isEmpty()) { try { tasks.remove(0).stop(); } catch (Throwable t) { LOGGER.warn("Error occurring while stopping a task of connector " + connectorName(), t); } } } protected void stop() { if (!startWatch.compareAndSet(true, false)) { throw new IllegalStateException("Connector is not started"); } LOGGER.info("Stopping connector {}", connectorName()); stopAllTasks(); offsetBackingStore.stop(); connector.stop(); } /** * Check the stream source state. * * @return */ public boolean isRunning() { return startWatch.get(); } }
/* * The MIT License * * Copyright (c) 2020, Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jeasy.batch.json; import org.jeasy.batch.core.reader.RecordReader; import org.jeasy.batch.core.record.Header; import javax.json.Json; import javax.json.JsonValue; import javax.json.stream.JsonGenerationException; import javax.json.stream.JsonGenerator; import javax.json.stream.JsonGeneratorFactory; import javax.json.stream.JsonParser; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.nio.charset.Charset; import java.time.LocalDateTime; import java.util.HashMap; import static org.jeasy.batch.core.util.Utils.checkNotNull; /** * Record reader that reads Json records from an array of Json objects: * <p> * [ * { * // JSON object * }, * { * // JSON object * } * ] * </p> * <p>This reader produces {@link JsonRecord} instances.</p> * * @author Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com) */ public class JsonRecordReader implements RecordReader<String> { private InputStream inputStream; private JsonParser parser; private JsonGeneratorFactory jsonGeneratorFactory; private Charset charset; private long currentRecordNumber; private JsonParser.Event currentEvent; private JsonParser.Event nextEvent; private int arrayDepth; private int objectDepth; private String key; /** * Create a new {@link JsonRecordReader}. * * @param inputStream to read */ public JsonRecordReader(final InputStream inputStream) { this(inputStream, Charset.defaultCharset()); } /** * Create a new {@link JsonRecordReader}. * * @param inputStream to read * @param charset of the json stream */ public JsonRecordReader(final InputStream inputStream, final Charset charset) { checkNotNull(inputStream, "input stream"); checkNotNull(charset, "charset"); this.inputStream = inputStream; this.charset = charset; this.jsonGeneratorFactory = Json.createGeneratorFactory(new HashMap<>()); } @Override public void open() { parser = Json.createParser(new InputStreamReader(inputStream, charset)); } private boolean hasNextRecord() { if (parser.hasNext()) { currentEvent = parser.next(); if (JsonParser.Event.START_ARRAY.equals(currentEvent)) { arrayDepth++; } if (JsonParser.Event.END_ARRAY.equals(currentEvent)) { arrayDepth--; } if (JsonParser.Event.KEY_NAME.equals(currentEvent)) { key = parser.getString(); } } if (parser.hasNext()) { nextEvent = parser.next(); if (JsonParser.Event.START_ARRAY.equals(nextEvent)) { arrayDepth++; } if (JsonParser.Event.END_ARRAY.equals(nextEvent)) { arrayDepth--; } if (JsonParser.Event.KEY_NAME.equals(nextEvent)) { key = parser.getString(); } } if (JsonParser.Event.START_ARRAY.equals(currentEvent) && JsonParser.Event.END_ARRAY.equals(nextEvent) && arrayDepth == 0) { return false; } if (JsonParser.Event.END_ARRAY.equals(currentEvent) && arrayDepth == 1 && objectDepth == 0) { return false; } return true; } @Override public JsonRecord readRecord() { if (hasNextRecord()) { StringWriter stringWriter = new StringWriter(); JsonGenerator jsonGenerator = jsonGeneratorFactory.createGenerator(stringWriter); writeRecordStart(jsonGenerator); do { moveToNextElement(jsonGenerator); } while (!isEndRootObject()); if (arrayDepth != 2) { jsonGenerator.writeEnd(); } jsonGenerator.close(); Header header = new Header(++currentRecordNumber, getDataSourceName(), LocalDateTime.now()); return new JsonRecord(header, stringWriter.toString()); } else { return null; } } protected String getDataSourceName() { return "Json stream"; } @Override public void close() throws Exception { parser.close(); if (inputStream != null) { inputStream.close(); } } private boolean isEndRootObject() { return objectDepth == 0; } private void writeRecordStart(JsonGenerator jsonGenerator) { if (currentEvent.equals(JsonParser.Event.START_ARRAY)) { if (arrayDepth != 1) { jsonGenerator.writeStartArray(); } arrayDepth++; } if (currentEvent.equals(JsonParser.Event.START_OBJECT)) { jsonGenerator.writeStartObject(); objectDepth++; } if (nextEvent.equals(JsonParser.Event.START_ARRAY)) { jsonGenerator.writeStartArray(); arrayDepth++; } if (nextEvent.equals(JsonParser.Event.START_OBJECT)) { jsonGenerator.writeStartObject(); objectDepth++; } } private void moveToNextElement(JsonGenerator jsonGenerator) { JsonParser.Event event = parser.next(); /* * The jsonGenerator is stateful and its current context (array/object) is not public * => There is no way to query it to know when to use write() or write(key) methods. * The idea to track its state with two boolean inArray and inObject has been tried and was not successful */ switch (event) { case START_ARRAY: try { jsonGenerator.writeStartArray(); } catch (JsonGenerationException e) { // NOSONAR e is safe to ignore here, see comment above jsonGenerator.writeStartArray(key); } break; case END_ARRAY: jsonGenerator.writeEnd(); break; case START_OBJECT: objectDepth++; try { jsonGenerator.writeStartObject(); } catch (Exception e) { // NOSONAR e is safe to ignore here, see comment above jsonGenerator.writeStartObject(key); } break; case END_OBJECT: objectDepth--; jsonGenerator.writeEnd(); break; case VALUE_FALSE: try { jsonGenerator.write(JsonValue.FALSE); } catch (Exception e) { // NOSONAR e is safe to ignore here, see comment above jsonGenerator.write(key, JsonValue.FALSE); } break; case VALUE_NULL: try { jsonGenerator.write(JsonValue.NULL); } catch (Exception e) { // NOSONAR e is safe to ignore here, see comment above jsonGenerator.write(key, JsonValue.NULL); } break; case VALUE_TRUE: try { jsonGenerator.write(JsonValue.TRUE); } catch (Exception e) { // NOSONAR e is safe to ignore here, see comment above jsonGenerator.write(key, JsonValue.TRUE); } break; case KEY_NAME: key = parser.getString(); break; case VALUE_STRING: try { jsonGenerator.write(parser.getString()); } catch (Exception e) { // NOSONAR e is safe to ignore here, see comment above jsonGenerator.write(key, parser.getString()); } break; case VALUE_NUMBER: try { jsonGenerator.write(parser.getBigDecimal()); } catch (Exception e) { // NOSONAR e is safe to ignore here, see comment above jsonGenerator.write(key, parser.getBigDecimal()); } break; default: break; } } }
package com.orientechnologies.orient.core.index.sbtree.local; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.orientechnologies.DatabaseAbstractTest; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.index.OCompositeKey; import com.orientechnologies.orient.core.serialization.serializer.binary.impl.OLinkSerializer; import com.orientechnologies.orient.core.serialization.serializer.binary.impl.index.OCompositeKeySerializer; /** * @author Andrey Lomakin * @since 15.08.13 */ @Test public class SBTreeCompositeKeyTest extends DatabaseAbstractTest { private OSBTree<OCompositeKey, OIdentifiable> localSBTree; @BeforeClass public void beforeClass() { super.beforeClass(); localSBTree = new OSBTree<OCompositeKey, OIdentifiable>("localSBTreeCompositeKeyTest", ".sbt", false, ".nbt", (OAbstractPaginatedStorage) database.getStorage().getUnderlying()); localSBTree.create(OCompositeKeySerializer.INSTANCE, OLinkSerializer.INSTANCE, null, 2, false); } @BeforeMethod public void beforeMethod() { for (double i = 1; i < 4; i++) { for (double j = 1; j < 10; j++) { final OCompositeKey compositeKey = new OCompositeKey(); compositeKey.addKey(i); compositeKey.addKey(j); localSBTree.put(compositeKey, new ORecordId((int) i, (long) j)); } } } @AfterMethod public void afterMethod() { localSBTree.clear(); } @AfterClass public void afterClass() throws Exception { localSBTree.clear(); localSBTree.delete(); super.afterClass(); } public void testIterateBetweenValuesInclusive() { OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor = localSBTree.iterateEntriesBetween(compositeKey(2.0), true, compositeKey(3.0), true, true); Set<ORID> orids = extractRids(cursor); assertEquals(orids.size(), 18); for (int i = 2; i <= 3; i++) { for (int j = 1; j <= 9; j++) { assertTrue(orids.contains(new ORecordId(i, j))); } } cursor = localSBTree.iterateEntriesBetween(compositeKey(2.0), true, compositeKey(3.0), true, false); orids = extractRids(cursor); assertEquals(orids.size(), 18); for (int i = 2; i <= 3; i++) { for (int j = 1; j <= 9; j++) { assertTrue(orids.contains(new ORecordId(i, j))); } } } public void testIterateBetweenValuesFromInclusive() { OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor = localSBTree.iterateEntriesBetween(compositeKey(2.0), true, compositeKey(3.0), false, true); Set<ORID> orids = extractRids(cursor); assertEquals(orids.size(), 9); for (int j = 1; j <= 9; j++) { assertTrue(orids.contains(new ORecordId(2, j))); } cursor = localSBTree.iterateEntriesBetween(compositeKey(2.0), true, compositeKey(3.0), false, false); orids = extractRids(cursor); assertEquals(orids.size(), 9); for (int j = 1; j <= 9; j++) { assertTrue(orids.contains(new ORecordId(2, j))); } } public void testIterateBetweenValuesToInclusive() { OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor = localSBTree.iterateEntriesBetween(compositeKey(2.0), false, compositeKey(3.0), true, true); Set<ORID> orids = extractRids(cursor); assertEquals(orids.size(), 9); for (int i = 1; i <= 9; i++) { assertTrue(orids.contains(new ORecordId(3, i))); } cursor = localSBTree.iterateEntriesBetween(compositeKey(2.0), false, compositeKey(3.0), true, false); orids = extractRids(cursor); assertEquals(orids.size(), 9); for (int i = 1; i <= 9; i++) { assertTrue(orids.contains(new ORecordId(3, i))); } } public void testIterateEntriesNonInclusive() { OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor = localSBTree.iterateEntriesBetween(compositeKey(2.0), false, compositeKey(3.0), false, true); Set<ORID> orids = extractRids(cursor); assertEquals(orids.size(), 0); cursor = localSBTree.iterateEntriesBetween(compositeKey(2.0), false, compositeKey(3.0), false, false); orids = extractRids(cursor); assertEquals(orids.size(), 0); cursor = localSBTree.iterateEntriesBetween(compositeKey(1.0), false, compositeKey(3.0), false, true); orids = extractRids(cursor); assertEquals(orids.size(), 9); for (int i = 1; i <= 9; i++) { assertTrue(orids.contains(new ORecordId(2, i))); } cursor = localSBTree.iterateEntriesBetween(compositeKey(1.0), false, compositeKey(3.0), false, false); orids = extractRids(cursor); assertEquals(orids.size(), 9); for (int i = 1; i <= 9; i++) { assertTrue(orids.contains(new ORecordId(2, i))); } } public void testIterateBetweenValuesInclusivePartialKey() { OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor = localSBTree.iterateEntriesBetween(compositeKey(2.0, 4.0), true, compositeKey(3.0), true, true); Set<ORID> orids = extractRids(cursor); assertEquals(orids.size(), 15); for (int i = 2; i <= 3; i++) { for (int j = 1; j <= 9; j++) { if (i == 2 && j < 4) continue; assertTrue(orids.contains(new ORecordId(i, j))); } } cursor = localSBTree.iterateEntriesBetween(compositeKey(2.0, 4.0), true, compositeKey(3.0), true, false); orids = extractRids(cursor); assertEquals(orids.size(), 15); for (int i = 2; i <= 3; i++) { for (int j = 1; j <= 9; j++) { if (i == 2 && j < 4) continue; assertTrue(orids.contains(new ORecordId(i, j))); } } } public void testIterateBetweenValuesFromInclusivePartialKey() { OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor = localSBTree.iterateEntriesBetween(compositeKey(2.0, 4.0), true, compositeKey(3.0), false, true); Set<ORID> orids = extractRids(cursor); assertEquals(orids.size(), 6); for (int j = 4; j <= 9; j++) { assertTrue(orids.contains(new ORecordId(2, j))); } cursor = localSBTree.iterateEntriesBetween(compositeKey(2.0, 4.0), true, compositeKey(3.0), false, false); orids = extractRids(cursor); assertEquals(orids.size(), 6); for (int j = 4; j <= 9; j++) { assertTrue(orids.contains(new ORecordId(2, j))); } } public void testIterateBetweenValuesToInclusivePartialKey() { OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor = localSBTree.iterateEntriesBetween(compositeKey(2.0, 4.0), false, compositeKey(3.0), true, true); Set<ORID> orids = extractRids(cursor); assertEquals(orids.size(), 14); for (int i = 2; i <= 3; i++) { for (int j = 1; j <= 9; j++) { if (i == 2 && j <= 4) continue; assertTrue(orids.contains(new ORecordId(i, j))); } } cursor = localSBTree.iterateEntriesBetween(compositeKey(2.0, 4.0), false, compositeKey(3.0), true, false); orids = extractRids(cursor); assertEquals(orids.size(), 14); for (int i = 2; i <= 3; i++) { for (int j = 1; j <= 9; j++) { if (i == 2 && j <= 4) continue; assertTrue(orids.contains(new ORecordId(i, j))); } } } public void testIterateBetweenValuesNonInclusivePartial() { OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor = localSBTree.iterateEntriesBetween(compositeKey(2.0, 4.0), false, compositeKey(3.0), false, true); Set<ORID> orids = extractRids(cursor); assertEquals(orids.size(), 5); for (int i = 5; i <= 9; i++) { assertTrue(orids.contains(new ORecordId(2, i))); } cursor = localSBTree.iterateEntriesBetween(compositeKey(2.0, 4.0), false, compositeKey(3.0), false, false); orids = extractRids(cursor); assertEquals(orids.size(), 5); for (int i = 5; i <= 9; i++) { assertTrue(orids.contains(new ORecordId(2, i))); } } public void testIterateValuesMajorInclusivePartial() { OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor = localSBTree.iterateEntriesMajor(compositeKey(2.0), true, true); Set<ORID> orids = extractRids(cursor); assertEquals(orids.size(), 18); for (int i = 2; i <= 3; i++) for (int j = 1; j <= 9; j++) { assertTrue(orids.contains(new ORecordId(i, j))); } cursor = localSBTree.iterateEntriesMajor(compositeKey(2.0), true, false); orids = extractRids(cursor); assertEquals(orids.size(), 18); for (int i = 2; i <= 3; i++) for (int j = 1; j <= 9; j++) { assertTrue(orids.contains(new ORecordId(i, j))); } } public void testIterateMajorNonInclusivePartial() { OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor = localSBTree.iterateEntriesMajor(compositeKey(2.0), false, true); Set<ORID> orids = extractRids(cursor); assertEquals(orids.size(), 9); for (int i = 1; i <= 9; i++) { assertTrue(orids.contains(new ORecordId(3, i))); } cursor = localSBTree.iterateEntriesMajor(compositeKey(2.0), false, false); orids = extractRids(cursor); assertEquals(orids.size(), 9); for (int i = 1; i <= 9; i++) { assertTrue(orids.contains(new ORecordId(3, i))); } } public void testIterateValuesMajorInclusive() { OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor = localSBTree .iterateEntriesMajor(compositeKey(2.0, 3.0), true, true); Set<ORID> orids = extractRids(cursor); assertEquals(orids.size(), 16); for (int i = 2; i <= 3; i++) for (int j = 1; j <= 9; j++) { if (i == 2 && j < 3) continue; assertTrue(orids.contains(new ORecordId(i, j))); } cursor = localSBTree.iterateEntriesMajor(compositeKey(2.0, 3.0), true, false); orids = extractRids(cursor); assertEquals(orids.size(), 16); for (int i = 2; i <= 3; i++) for (int j = 1; j <= 9; j++) { if (i == 2 && j < 3) continue; assertTrue(orids.contains(new ORecordId(i, j))); } } public void testIterateValuesMajorNonInclusive() { OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor = localSBTree.iterateEntriesMajor(compositeKey(2.0, 3.0), false, true); Set<ORID> orids = extractRids(cursor); assertEquals(orids.size(), 15); for (int i = 2; i <= 3; i++) for (int j = 1; j <= 9; j++) { if (i == 2 && j <= 3) continue; assertTrue(orids.contains(new ORecordId(i, j))); } cursor = localSBTree.iterateEntriesMajor(compositeKey(2.0, 3.0), false, false); orids = extractRids(cursor); assertEquals(orids.size(), 15); for (int i = 2; i <= 3; i++) for (int j = 1; j <= 9; j++) { if (i == 2 && j <= 3) continue; assertTrue(orids.contains(new ORecordId(i, j))); } } public void testIterateValuesMinorInclusivePartial() { OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor = localSBTree.iterateEntriesMinor(compositeKey(3.0), true, true); Set<ORID> orids = extractRids(cursor); assertEquals(orids.size(), 27); for (int i = 1; i <= 3; i++) for (int j = 1; j <= 9; j++) { assertTrue(orids.contains(new ORecordId(i, j))); } cursor = localSBTree.iterateEntriesMinor(compositeKey(3.0), true, false); orids = extractRids(cursor); assertEquals(orids.size(), 27); for (int i = 1; i <= 3; i++) for (int j = 1; j <= 9; j++) { assertTrue(orids.contains(new ORecordId(i, j))); } } public void testIterateValuesMinorNonInclusivePartial() { OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor = localSBTree.iterateEntriesMinor(compositeKey(3.0), false, true); Set<ORID> orids = extractRids(cursor); assertEquals(orids.size(), 18); for (int i = 1; i < 3; i++) for (int j = 1; j <= 9; j++) { assertTrue(orids.contains(new ORecordId(i, j))); } cursor = localSBTree.iterateEntriesMinor(compositeKey(3.0), false, false); orids = extractRids(cursor); assertEquals(orids.size(), 18); for (int i = 1; i < 3; i++) for (int j = 1; j <= 9; j++) { assertTrue(orids.contains(new ORecordId(i, j))); } } public void testIterateValuesMinorInclusive() { OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor = localSBTree .iterateEntriesMinor(compositeKey(3.0, 2.0), true, true); Set<ORID> orids = extractRids(cursor); assertEquals(orids.size(), 20); for (int i = 1; i <= 3; i++) for (int j = 1; j <= 9; j++) { if (i == 3 && j > 2) continue; assertTrue(orids.contains(new ORecordId(i, j))); } cursor = localSBTree.iterateEntriesMinor(compositeKey(3.0, 2.0), true, false); orids = extractRids(cursor); assertEquals(orids.size(), 20); for (int i = 1; i <= 3; i++) for (int j = 1; j <= 9; j++) { if (i == 3 && j > 2) continue; assertTrue(orids.contains(new ORecordId(i, j))); } } public void testIterateValuesMinorNonInclusive() { OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor = localSBTree.iterateEntriesMinor(compositeKey(3.0, 2.0), false, true); Set<ORID> orids = extractRids(cursor); assertEquals(orids.size(), 19); for (int i = 1; i < 3; i++) for (int j = 1; j <= 9; j++) { assertTrue(orids.contains(new ORecordId(i, j))); } cursor = localSBTree.iterateEntriesMinor(compositeKey(3.0, 2.0), false, false); orids = extractRids(cursor); assertEquals(orids.size(), 19); for (int i = 1; i < 3; i++) for (int j = 1; j <= 9; j++) { assertTrue(orids.contains(new ORecordId(i, j))); } } private OCompositeKey compositeKey(Comparable<?>... params) { return new OCompositeKey(Arrays.asList(params)); } private Set<ORID> extractRids(OSBTree.OSBTreeCursor<OCompositeKey, OIdentifiable> cursor) { final Set<ORID> orids = new HashSet<ORID>(); while (true) { Map.Entry<OCompositeKey, OIdentifiable> entry = cursor.next(-1); if (entry != null) orids.add(entry.getValue().getIdentity()); else break; } return orids; } }
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.download; import static org.chromium.chrome.browser.download.DownloadSnackbarController.INVALID_NOTIFICATION_ID; import android.app.Notification; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Handler; import android.os.IBinder; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import com.google.ipc.invalidation.util.Preconditions; import org.chromium.base.ContextUtils; import org.chromium.base.Log; import org.chromium.chrome.browser.download.DownloadNotificationService.DownloadStatus; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Manager to stop and start the foreground service associated with downloads. */ public class DownloadForegroundServiceManager { private static class DownloadUpdate { int mNotificationId; Notification mNotification; @DownloadNotificationService.DownloadStatus int mDownloadStatus; Context mContext; DownloadUpdate(int notificationId, Notification notification, @DownloadNotificationService.DownloadStatus int downloadStatus, Context context) { mNotificationId = notificationId; mNotification = notification; mDownloadStatus = downloadStatus; mContext = context; } } private static final String TAG = "DownloadFg"; // Delay to ensure start/stop foreground doesn't happen too quickly (b/74236718). private static final int WAIT_TIME_MS = 200; // Variables used to ensure start/stop foreground doesn't happen too quickly (b/74236718). private final Handler mHandler = new Handler(); private final Runnable mMaybeStopServiceRunnable = new Runnable() { @Override public void run() { Log.w(TAG, "Checking if delayed stopAndUnbindService needs to be resolved."); mStopServiceDelayed = false; processDownloadUpdateQueue(false /* not isProcessingPending */); mHandler.removeCallbacks(mMaybeStopServiceRunnable); Log.w(TAG, "Done checking if delayed stopAndUnbindService needs to be resolved."); } }; private boolean mStopServiceDelayed; private int mPinnedNotificationId = INVALID_NOTIFICATION_ID; // This is true when context.bindService has been called and before context.unbindService. private boolean mIsServiceBound; // This is non-null when onServiceConnected has been called (aka service is active). private DownloadForegroundService mBoundService; @VisibleForTesting final Map<Integer, DownloadUpdate> mDownloadUpdateQueue = new HashMap<>(); public DownloadForegroundServiceManager() {} public void updateDownloadStatus(Context context, @DownloadNotificationService.DownloadStatus int downloadStatus, int notificationId, Notification notification) { if (downloadStatus != DownloadNotificationService.DownloadStatus.IN_PROGRESS) { Log.w(TAG, "updateDownloadStatus status: " + downloadStatus + ", id: " + notificationId); } mDownloadUpdateQueue.put(notificationId, new DownloadUpdate(notificationId, notification, downloadStatus, context)); processDownloadUpdateQueue(false /* not isProcessingPending */); } /** * Process the notification queue for all cases and initiate any needed actions. * In the happy path, the logic should be: * bindAndStartService -> startOrUpdateForegroundService -> stopAndUnbindService. * @param isProcessingPending Whether the call was made to process pending notifications that * have accumulated in the queue during the startup process or if it * was made based on during a basic update. */ @VisibleForTesting void processDownloadUpdateQueue(boolean isProcessingPending) { DownloadUpdate downloadUpdate = findInterestingDownloadUpdate(); if (downloadUpdate == null) return; // When nothing has been initialized, just bind the service. if (!mIsServiceBound) { // If the download update is not active at the onset, don't even start the service! if (!isActive(downloadUpdate.mDownloadStatus)) { cleanDownloadUpdateQueue(); return; } startAndBindService(downloadUpdate.mContext); return; } // Skip everything that happens while waiting for startup. if (mBoundService == null) return; // In the pending case, start foreground with specific notificationId and notification. if (isProcessingPending) { Log.w(TAG, "Starting service with type " + downloadUpdate.mDownloadStatus); startOrUpdateForegroundService( downloadUpdate.mNotificationId, downloadUpdate.mNotification); // Post a delayed task to eventually check to see if service needs to be stopped. postMaybeStopServiceRunnable(); } // If the selected downloadUpdate is not active, there are no active downloads left. // Stop the foreground service. // In the pending case, this will stop the foreground immediately after it was started. if (!isActive(downloadUpdate.mDownloadStatus)) { // Only stop the service if not waiting for delay (ie. WAIT_TIME_MS has transpired). if (!mStopServiceDelayed) { stopAndUnbindService(downloadUpdate.mDownloadStatus); cleanDownloadUpdateQueue(); } else { Log.w(TAG, "Delaying call to stopAndUnbindService."); } return; } // Make sure the pinned notification is still active, if not, update. if (mDownloadUpdateQueue.get(mPinnedNotificationId) == null || !isActive(mDownloadUpdateQueue.get(mPinnedNotificationId).mDownloadStatus)) { startOrUpdateForegroundService( downloadUpdate.mNotificationId, downloadUpdate.mNotification); } // Clear out inactive download updates in queue if there is at least one active download. cleanDownloadUpdateQueue(); } /** Helper code to process download update queue. */ @Nullable private DownloadUpdate findInterestingDownloadUpdate() { Iterator<Map.Entry<Integer, DownloadUpdate>> entries = mDownloadUpdateQueue.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<Integer, DownloadUpdate> entry = entries.next(); // Return an active entry if possible. if (isActive(entry.getValue().mDownloadStatus)) return entry.getValue(); // If there are no active entries, just return the last entry. if (!entries.hasNext()) return entry.getValue(); } // If there's no entries, return null. return null; } private boolean isActive(@DownloadNotificationService.DownloadStatus int downloadStatus) { return downloadStatus == DownloadNotificationService.DownloadStatus.IN_PROGRESS; } private void cleanDownloadUpdateQueue() { Iterator<Map.Entry<Integer, DownloadUpdate>> entries = mDownloadUpdateQueue.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<Integer, DownloadUpdate> entry = entries.next(); // Remove entry that is not active or pinned. if (!isActive(entry.getValue().mDownloadStatus) && entry.getValue().mNotificationId != mPinnedNotificationId) { entries.remove(); } } } /** Helper code to bind service. */ @VisibleForTesting void startAndBindService(Context context) { Log.w(TAG, "startAndBindService"); mIsServiceBound = true; startAndBindServiceInternal(context); } @VisibleForTesting void startAndBindServiceInternal(Context context) { DownloadForegroundService.startDownloadForegroundService(context); context.bindService(new Intent(context, DownloadForegroundService.class), mConnection, Context.BIND_AUTO_CREATE); } private final ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { Log.w(TAG, "onServiceConnected"); if (!(service instanceof DownloadForegroundService.LocalBinder)) { Log.w(TAG, "Not from DownloadNotificationService, do not connect." + " Component name: " + className); return; } mBoundService = ((DownloadForegroundService.LocalBinder) service).getService(); DownloadForegroundServiceObservers.addObserver( DownloadNotificationServiceObserver.class); processDownloadUpdateQueue(true /* isProcessingPending */); } @Override public void onServiceDisconnected(ComponentName componentName) { Log.w(TAG, "onServiceDisconnected"); mBoundService = null; } }; /** Helper code to start or update foreground service. */ @VisibleForTesting void startOrUpdateForegroundService(int notificationId, Notification notification) { Log.w(TAG, "startOrUpdateForegroundService id: " + notificationId); if (mBoundService != null && notificationId != INVALID_NOTIFICATION_ID && notification != null) { // If there was an originally pinned notification, get its id and notification. DownloadUpdate downloadUpdate = mDownloadUpdateQueue.get(mPinnedNotificationId); Notification oldNotification = (downloadUpdate == null) ? null : downloadUpdate.mNotification; boolean killOldNotification = downloadUpdate != null && downloadUpdate.mDownloadStatus == DownloadStatus.CANCELLED; // Start service and handle notifications. mBoundService.startOrUpdateForegroundService(notificationId, notification, mPinnedNotificationId, oldNotification, killOldNotification); // After the service has been started and the notification handled, change stored id. mPinnedNotificationId = notificationId; } } /** Helper code to stop and unbind service. */ @VisibleForTesting void stopAndUnbindService(@DownloadNotificationService.DownloadStatus int downloadStatus) { Log.w(TAG, "stopAndUnbindService status: " + downloadStatus); Preconditions.checkNotNull(mBoundService); mIsServiceBound = false; @DownloadForegroundService.StopForegroundNotification int stopForegroundNotification; if (downloadStatus == DownloadNotificationService.DownloadStatus.CANCELLED) { stopForegroundNotification = DownloadForegroundService.StopForegroundNotification.KILL; } else { stopForegroundNotification = DownloadForegroundService.StopForegroundNotification.DETACH; } DownloadUpdate downloadUpdate = mDownloadUpdateQueue.get(mPinnedNotificationId); Notification oldNotification = (downloadUpdate == null) ? null : downloadUpdate.mNotification; stopAndUnbindServiceInternal( stopForegroundNotification, mPinnedNotificationId, oldNotification); mBoundService = null; mPinnedNotificationId = INVALID_NOTIFICATION_ID; } @VisibleForTesting void stopAndUnbindServiceInternal( @DownloadForegroundService.StopForegroundNotification int stopForegroundStatus, int pinnedNotificationId, Notification pinnedNotification) { mBoundService.stopDownloadForegroundService( stopForegroundStatus, pinnedNotificationId, pinnedNotification); ContextUtils.getApplicationContext().unbindService(mConnection); DownloadForegroundServiceObservers.removeObserver( DownloadNotificationServiceObserver.class); } /** Helper code for testing. */ @VisibleForTesting void setBoundService(DownloadForegroundService service) { mBoundService = service; } // Allow testing methods to skip posting the delayed runnable. @VisibleForTesting void postMaybeStopServiceRunnable() { mHandler.removeCallbacks(mMaybeStopServiceRunnable); mHandler.postDelayed(mMaybeStopServiceRunnable, WAIT_TIME_MS); mStopServiceDelayed = true; } }
package org.edx.mobile.test; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; import org.edx.mobile.util.Config; import org.junit.Test; import java.util.ArrayList; import static org.junit.Assert.*; /** * Created by aleffert on 2/6/15. */ public class ConfigTests extends BaseTestCase { //TODO - should we place constant at a central place? /* Config keys */ private static final String COURSE_ENROLLMENT = "COURSE_ENROLLMENT"; private static final String SOCIAL_SHARING = "SOCIAL_SHARING"; private static final String ZERO_RATING = "ZERO_RATING"; private static final String FACEBOOK = "FACEBOOK"; private static final String GOOGLE = "GOOGLE"; private static final String FABRIC = "FABRIC"; private static final String NEW_RELIC = "NEW_RELIC"; private static final String SEGMENT_IO = "SEGMENT_IO"; private static final String WHITE_LIST_OF_DOMAINS = "WHITE_LIST_OF_DOMAINS"; private static final String ENABLED = "ENABLED"; private static final String DISABLED_CARRIERS = "DISABLED_CARRIERS"; private static final String CARRIERS = "CARRIERS"; private static final String COURSE_SEARCH_URL = "COURSE_SEARCH_URL"; private static final String EXTERNAL_COURSE_SEARCH_URL = "EXTERNAL_COURSE_SEARCH_URL"; private static final String COURSE_INFO_URL_TEMPLATE = "COURSE_INFO_URL_TEMPLATE"; private static final String FACEBOOK_APP_ID = "FACEBOOK_APP_ID"; private static final String FABRIC_KEY = "FABRIC_KEY"; private static final String FABRIC_BUILD_SECRET = "FABRIC_BUILD_SECRET"; private static final String NEW_RELIC_KEY = "NEW_RELIC_KEY"; private static final String SEGMENT_IO_WRITE_KEY = "SEGMENT_IO_WRITE_KEY"; private static final String DOMAINS = "DOMAINS"; private static final String PARSE = "PARSE"; private static final String PARSE_ENABLED = "NOTIFICATIONS_ENABLED"; private static final String PARSE_APPLICATION_ID = "APPLICATION_ID"; private static final String PARSE_CLIENT_KEY = "CLIENT_KEY"; @Test public void testSocialSharingNoConfig() { JsonObject configBase = new JsonObject(); Config config = new Config(configBase); assertFalse(config.getSocialSharingConfig().isEnabled()); assertEquals(config.getSocialSharingConfig().getDisabledCarriers().size(), 0); } @Test public void testSocialSharingEmptyConfig() { JsonObject configBase = new JsonObject(); JsonObject socialConfig = new JsonObject(); configBase.add(SOCIAL_SHARING, socialConfig); Config config = new Config(configBase); assertFalse(config.getSocialSharingConfig().isEnabled()); assertEquals(config.getSocialSharingConfig().getDisabledCarriers().size(), 0); } @Test public void testSocialSharingConfig() { JsonObject configBase = new JsonObject(); JsonObject socialConfig = new JsonObject(); socialConfig.add(ENABLED, new JsonPrimitive(true)); configBase.add(SOCIAL_SHARING, socialConfig); ArrayList<String> carrierList = new ArrayList<String>(); carrierList.add("12345"); carrierList.add("foo"); JsonArray carriers = new JsonArray(); for(String carrier : carrierList) { carriers.add(new JsonPrimitive(carrier)); } socialConfig.add(DISABLED_CARRIERS, carriers); Config config = new Config(configBase); assertTrue(config.getSocialSharingConfig().isEnabled()); assertEquals(carrierList, config.getSocialSharingConfig().getDisabledCarriers()); } @Test public void testZeroRatingNoConfig() { JsonObject configBase = new JsonObject(); Config config = new Config(configBase); assertFalse(config.getZeroRatingConfig().isEnabled()); assertEquals(config.getZeroRatingConfig().getCarriers().size(), 0); } @Test public void testZeroRatingEmptyConfig() { JsonObject configBase = new JsonObject(); JsonObject socialConfig = new JsonObject(); configBase.add(ZERO_RATING, socialConfig); Config config = new Config(configBase); assertFalse(config.getZeroRatingConfig().isEnabled()); assertEquals(config.getZeroRatingConfig().getCarriers().size(), 0); } @Test public void testZeroRatingConfig() { JsonObject configBase = new JsonObject(); JsonObject zeroRatingConfig = new JsonObject(); zeroRatingConfig.add(ENABLED, new JsonPrimitive(true)); configBase.add(ZERO_RATING, zeroRatingConfig); ArrayList<String> carrierList = new ArrayList<String>(); carrierList.add("12345"); carrierList.add("foo"); JsonArray carriers = new JsonArray(); for(String carrier : carrierList) { carriers.add(new JsonPrimitive(carrier)); } zeroRatingConfig.add(CARRIERS, carriers); ArrayList<String> domainList = new ArrayList<>(); domainList.add("domain1"); domainList.add("domain2"); JsonArray domains = new JsonArray(); for(String domain : domainList) { domains.add(new JsonPrimitive(domain)); } zeroRatingConfig.add(WHITE_LIST_OF_DOMAINS, domains); Config config = new Config(configBase); assertTrue(config.getZeroRatingConfig().isEnabled()); assertEquals(carrierList, config.getZeroRatingConfig().getCarriers()); assertEquals(domainList, config.getZeroRatingConfig().getWhiteListedDomains()); } @Test public void testEnrollmentNoConfig() { JsonObject configBase = new JsonObject(); Config config = new Config(configBase); assertFalse(config.getEnrollmentConfig().isEnabled()); assertNull(config.getEnrollmentConfig().getCourseSearchUrl()); assertNull(config.getEnrollmentConfig().getExternalCourseSearchUrl()); assertNull(config.getEnrollmentConfig().getCourseInfoUrlTemplate()); } @Test public void testEnrollmentEmptyConfig() { JsonObject configBase = new JsonObject(); JsonObject enrollmentConfig = new JsonObject(); configBase.add(COURSE_ENROLLMENT, enrollmentConfig); Config config = new Config(configBase); assertFalse(config.getEnrollmentConfig().isEnabled()); assertNull(config.getEnrollmentConfig().getCourseSearchUrl()); assertNull(config.getEnrollmentConfig().getExternalCourseSearchUrl()); assertNull(config.getEnrollmentConfig().getCourseInfoUrlTemplate()); } @Test public void testEnrollmentConfig() { JsonObject configBase = new JsonObject(); JsonObject enrollmentConfig = new JsonObject(); enrollmentConfig.add(ENABLED, new JsonPrimitive(true)); enrollmentConfig.add(COURSE_SEARCH_URL, new JsonPrimitive("fake-url")); enrollmentConfig.add(EXTERNAL_COURSE_SEARCH_URL, new JsonPrimitive("external-fake-url")); enrollmentConfig.add(COURSE_INFO_URL_TEMPLATE, new JsonPrimitive("fake-url-template")); configBase.add(COURSE_ENROLLMENT, enrollmentConfig); Config config = new Config(configBase); assertTrue(config.getEnrollmentConfig().isEnabled()); assertEquals(config.getEnrollmentConfig().getCourseSearchUrl(), "fake-url"); assertEquals(config.getEnrollmentConfig().getExternalCourseSearchUrl(), "external-fake-url"); assertEquals(config.getEnrollmentConfig().getCourseInfoUrlTemplate(), "fake-url-template"); } @Test public void testFacebookNoConfig() { JsonObject configBase = new JsonObject(); Config config = new Config(configBase); assertFalse(config.getFacebookConfig().isEnabled()); assertNull(config.getFacebookConfig().getFacebookAppId()); } @Test public void testFacebookEmptyConfig() { JsonObject fbConfig = new JsonObject(); JsonObject configBase = new JsonObject(); configBase.add(FACEBOOK, fbConfig); Config config = new Config(configBase); assertFalse(config.getFacebookConfig().isEnabled()); assertNull(config.getFacebookConfig().getFacebookAppId()); } @Test public void testFacebookConfig() { String appId = "fake-app-id"; JsonObject fbConfig = new JsonObject(); fbConfig.add(ENABLED, new JsonPrimitive(true)); fbConfig.add(FACEBOOK_APP_ID, new JsonPrimitive(appId)); JsonObject configBase = new JsonObject(); configBase.add(FACEBOOK, fbConfig); Config config = new Config(configBase); assertTrue(config.getFacebookConfig().isEnabled()); assertEquals(appId, config.getFacebookConfig().getFacebookAppId()); } @Test public void testGoogleNoConfig() { JsonObject configBase = new JsonObject(); Config config = new Config(configBase); assertFalse(config.getGoogleConfig().isEnabled()); } @Test public void testGoogleEmptyConfig() { JsonObject googleConfig = new JsonObject(); JsonObject configBase = new JsonObject(); configBase.add(GOOGLE, googleConfig); Config config = new Config(configBase); assertFalse(config.getGoogleConfig().isEnabled()); } @Test public void testGoogleConfig() { JsonObject googleConfig = new JsonObject(); googleConfig.add(ENABLED, new JsonPrimitive(true)); JsonObject configBase = new JsonObject(); configBase.add(GOOGLE, googleConfig); Config config = new Config(configBase); assertTrue(config.getGoogleConfig().isEnabled()); } @Test public void testParseNoConfig() { JsonObject configBase = new JsonObject(); Config config = new Config(configBase); assertFalse(config.getParseNotificationConfig().isEnabled()); assertNull(config.getParseNotificationConfig().getParseApplicationId()); assertNull(config.getParseNotificationConfig().getParseClientKey()); } @Test public void testParseConfig() { String key = "fake-key"; String secret = "fake-secret"; JsonObject parseConfig = new JsonObject(); parseConfig.add(PARSE_ENABLED, new JsonPrimitive(true)); parseConfig.add(PARSE_APPLICATION_ID, new JsonPrimitive(key)); parseConfig.add(PARSE_CLIENT_KEY, new JsonPrimitive(secret)); JsonObject configBase = new JsonObject(); configBase.add(PARSE, parseConfig); Config config = new Config(configBase); assertTrue(config.getParseNotificationConfig().isEnabled()); assertEquals(key, config.getParseNotificationConfig().getParseApplicationId()); assertEquals(secret, config.getParseNotificationConfig().getParseClientKey()); } @Test public void testFabricNoConfig() { JsonObject configBase = new JsonObject(); Config config = new Config(configBase); assertFalse(config.getFabricConfig().isEnabled()); assertNull(config.getFabricConfig().getFabricKey()); assertNull(config.getFabricConfig().getFabricBuildSecret()); } @Test public void testFabricEmptyConfig() { JsonObject fabricConfig = new JsonObject(); JsonObject configBase = new JsonObject(); configBase.add(FABRIC, fabricConfig); Config config = new Config(configBase); assertFalse(config.getFabricConfig().isEnabled()); assertNull(config.getFabricConfig().getFabricKey()); assertNull(config.getFabricConfig().getFabricBuildSecret()); } @Test public void testFabricConfig() { String key = "fake-key"; String secret = "fake-secret"; JsonObject fabricConfig = new JsonObject(); fabricConfig.add(ENABLED, new JsonPrimitive(true)); fabricConfig.add(FABRIC_KEY, new JsonPrimitive(key)); fabricConfig.add(FABRIC_BUILD_SECRET, new JsonPrimitive(secret)); JsonObject configBase = new JsonObject(); configBase.add(FABRIC, fabricConfig); Config config = new Config(configBase); assertTrue(config.getFabricConfig().isEnabled()); assertEquals(key, config.getFabricConfig().getFabricKey()); assertEquals(secret, config.getFabricConfig().getFabricBuildSecret()); } @Test public void testNewRelicNoConfig() { JsonObject configBase = new JsonObject(); Config config = new Config(configBase); assertFalse(config.getNewRelicConfig().isEnabled()); assertNull(config.getNewRelicConfig().getNewRelicKey()); } @Test public void testNewRelicEmptyConfig() { JsonObject fabricConfig = new JsonObject(); JsonObject configBase = new JsonObject(); configBase.add(NEW_RELIC, fabricConfig); Config config = new Config(configBase); assertFalse(config.getNewRelicConfig().isEnabled()); assertNull(config.getNewRelicConfig().getNewRelicKey()); } @Test public void testNewRelicConfig() { String key = "fake-key"; JsonObject newRelicConfig = new JsonObject(); newRelicConfig.add(ENABLED, new JsonPrimitive(true)); newRelicConfig.add(NEW_RELIC_KEY, new JsonPrimitive(key)); JsonObject configBase = new JsonObject(); configBase.add(NEW_RELIC, newRelicConfig); Config config = new Config(configBase); assertTrue(config.getNewRelicConfig().isEnabled()); assertEquals(key, config.getNewRelicConfig().getNewRelicKey()); } @Test public void testSegmentNoConfig() { JsonObject configBase = new JsonObject(); Config config = new Config(configBase); assertFalse(config.getSegmentConfig().isEnabled()); assertNull(config.getSegmentConfig().getSegmentWriteKey()); } @Test public void testSegmentEmptyConfig() { JsonObject segmentConfig = new JsonObject(); JsonObject configBase = new JsonObject(); configBase.add(SEGMENT_IO, segmentConfig); Config config = new Config(configBase); assertFalse(config.getSegmentConfig().isEnabled()); assertNull(config.getSegmentConfig().getSegmentWriteKey()); } @Test public void testSegmentConfig() { String key = "fake-key"; JsonObject segmentConfig = new JsonObject(); segmentConfig.add(ENABLED, new JsonPrimitive(true)); segmentConfig.add(SEGMENT_IO_WRITE_KEY, new JsonPrimitive(key)); JsonObject configBase = new JsonObject(); configBase.add(SEGMENT_IO, segmentConfig); Config config = new Config(configBase); assertTrue(config.getSegmentConfig().isEnabled()); assertEquals(key, config.getSegmentConfig().getSegmentWriteKey()); } }
package io.nextop.rx; import junit.framework.TestCase; import rx.Notification; import rx.Observer; import rx.Scheduler; import rx.Subscription; import rx.exceptions.CompositeException; import rx.exceptions.OnErrorFailedException; import rx.functions.Action1; import rx.functions.Func1; import rx.schedulers.Schedulers; import rx.subjects.BehaviorSubject; import rx.subjects.PublishSubject; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** testing exception handling in RxJava */ public class RxExceptionTest extends TestCase { public void testExceptionSubjectPost() { // test the behavior of surfacing exceptions from a subject // onNext after subscriber BehaviorSubject<Integer> subject = BehaviorSubject.create(); final List<Notification<Integer>> notifications = new ArrayList<Notification<Integer>>(4); Subscription s = subject.subscribe(new Observer<Integer>() { @Override public void onNext(Integer t) { notifications.add(Notification.createOnNext(t)); throw new RuntimeException("onNext " + t); } @Override public void onCompleted() { notifications.add(Notification.<Integer>createOnCompleted()); } @Override public void onError(Throwable e) { notifications.add(Notification.<Integer>createOnError(e)); } }); subject.onNext(0); assertEquals(2, notifications.size()); Notification n0 = notifications.get(0); assertEquals(Notification.Kind.OnNext, n0.getKind()); assertEquals(0, n0.getValue()); Notification n1 = notifications.get(1); assertEquals(Notification.Kind.OnError, n1.getKind()); assertTrue(n1.getThrowable() instanceof RuntimeException); assertEquals("onNext 0", n1.getThrowable().getMessage()); } public void testExceptionSubjectPre() { // test the behavior of surfacing exceptions from a subject // onNext before subscriber BehaviorSubject<Integer> subject = BehaviorSubject.create(); subject.onNext(0); final List<Notification<Integer>> notifications = new ArrayList<Notification<Integer>>(4); Subscription s = subject.subscribe(new Observer<Integer>() { @Override public void onNext(Integer t) { notifications.add(Notification.createOnNext(t)); throw new RuntimeException("onNext " + t); } @Override public void onCompleted() { notifications.add(Notification.<Integer>createOnCompleted()); } @Override public void onError(Throwable e) { notifications.add(Notification.<Integer>createOnError(e)); } }); assertEquals(2, notifications.size()); Notification n0 = notifications.get(0); assertEquals(Notification.Kind.OnNext, n0.getKind()); assertEquals(0, n0.getValue()); Notification n1 = notifications.get(1); assertEquals(Notification.Kind.OnError, n1.getKind()); assertTrue(n1.getThrowable() instanceof RuntimeException); assertEquals("onNext 0", n1.getThrowable().getMessage()); } public void testExceptionSubjectAction() { // test the behavior of surfacing exceptions from a subject BehaviorSubject<Integer> subject = BehaviorSubject.create(); final List<Notification<Integer>> notifications = new ArrayList<Notification<Integer>>(4); Subscription s = subject.subscribe(new Action1<Integer>() { @Override public void call(Integer t) { notifications.add(Notification.createOnNext(t)); throw new RuntimeException("call " + t); } }); try { subject.onNext(0); // (unreachable) expect an exception to be thrown fail(); } catch (RuntimeException e) { assertEquals("call 0", e.getMessage()); } } public void testExceptionSubjectObserverCustomThrow() { // setup: // subject -> observer // shows that an exception in observer#onNext will call observer#onError, // and that an unahndled exception in observer#onError will come back to the caller BehaviorSubject<Integer> subject = BehaviorSubject.create(); final List<Notification<Integer>> notifications = new ArrayList<Notification<Integer>>(4); Subscription s = subject.subscribe(new Observer<Integer>() { @Override public void onNext(Integer t) { notifications.add(Notification.createOnNext(t)); throw new RuntimeException("onNext " + t); } @Override public void onCompleted() { notifications.add(Notification.<Integer>createOnCompleted()); } @Override public void onError(Throwable e) { notifications.add(Notification.<Integer>createOnError(e)); if (e instanceof RuntimeException) { // TODO assume an error path from onNext throw (RuntimeException) e; } else if (e instanceof Error) { // TODO assume an error path from onNext throw (Error) e; } else { // TODO // a normal error path? } } }); try { subject.onNext(0); // (unreachable) expect an exception to be thrown fail(); } catch (RuntimeException e) { // OnErrorFailedException // CompositeException // CompositeException$CompositeExceptionCausalChain // <call 0> assertTrue(e instanceof OnErrorFailedException); assertTrue(e.getCause() instanceof CompositeException); // TODO CompositeException$CompositeExceptionCausalChain assertEquals("onNext 0", e.getCause().getCause().getCause().getMessage()); } } public void testExceptionSubjectIndirect() { // setup: // subject -> subject -> observer // shows that an exception in observer#onNext will call observer#onError, // and that an unhandled exception in observer#onError will *not* come back to the caller // (is this to prevent an infinite loop obs#onNext -> obs#onError -> subjA/B#onError -> obs#onError ... ?) PublishSubject<Integer> entry = PublishSubject.create(); BehaviorSubject<Integer> subject = BehaviorSubject.create(); entry.map(new Func1<Integer, Integer>() { @Override public Integer call(Integer t) { return t + 1; } }).subscribe(subject); final List<Notification<Integer>> notifications = new ArrayList<Notification<Integer>>(4); Subscription s = subject.subscribe(new Observer<Integer>() { @Override public void onNext(Integer t) { notifications.add(Notification.createOnNext(t)); throw new RuntimeException("onNext " + t); } @Override public void onCompleted() { notifications.add(Notification.<Integer>createOnCompleted()); } @Override public void onError(Throwable e) { notifications.add(Notification.<Integer>createOnError(e)); if (e instanceof RuntimeException) { // TODO assume an error path from onNext throw (RuntimeException) e; } else if (e instanceof Error) { // TODO assume an error path from onNext throw (Error) e; } else { // TODO // a normal error path? } } }); entry.onNext(0); // nothing thrown ... assertEquals(2, notifications.size()); Notification n0 = notifications.get(0); assertEquals(Notification.Kind.OnNext, n0.getKind()); assertEquals(/* 0 + 1 */ 1, n0.getValue()); Notification n1 = notifications.get(1); assertEquals(Notification.Kind.OnError, n1.getKind()); } public void testExceptionSubjectIndirectScheduler() throws Exception { // setup: // subject -> subject -> (observe on scheduler) -> observer // shows that an exception in observer#onNext will call observer#onError, // and that an unhandled exception in observer#onError will post to the uncaught exception handler PublishSubject<Integer> entry = PublishSubject.create(); BehaviorSubject<Integer> subject = BehaviorSubject.create(); Scheduler scheduler = Schedulers.io(); entry.map(new Func1<Integer, Integer>() { @Override public Integer call(Integer t) { return t + 1; } }).subscribe(subject); final List<Notification<Integer>> notifications = Collections.synchronizedList(new ArrayList<Notification<Integer>>(4)); final List<Throwable> uncaughtException = Collections.synchronizedList(new ArrayList<Throwable>(4)); Subscription s = subject.observeOn(scheduler).subscribe(new Observer<Integer>() { @Override public void onNext(Integer t) { notifications.add(Notification.createOnNext(t)); throw new RuntimeException("onNext " + t); } @Override public void onCompleted() { notifications.add(Notification.<Integer>createOnCompleted()); } @Override public void onError(Throwable e) { notifications.add(Notification.<Integer>createOnError(e)); if (e instanceof RuntimeException) { // TODO assume an error path from onNext throw (RuntimeException) e; } else if (e instanceof Error) { // TODO assume an error path from onNext throw (Error) e; } else { // TODO // a normal error path? } } }); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { uncaughtException.add(e); } }); entry.onNext(0); // expect nothing to be thrown because async // wait a bit for scheduler to publish notifications Thread.sleep(2000); // expect the exception to come in through the uncaught exception handler for the thread assertEquals(1, uncaughtException.size()); assertEquals(2, notifications.size()); Notification n0 = notifications.get(0); assertEquals(Notification.Kind.OnNext, n0.getKind()); assertEquals(/* 0 + 1 */ 1, n0.getValue()); Notification n1 = notifications.get(1); assertEquals(Notification.Kind.OnError, n1.getKind()); } }
package org.graylog.alarmcallbacks.rundeck; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import okhttp3.OkHttpClient; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.graylog2.alerts.AbstractAlertCondition; import org.graylog2.alerts.types.DummyAlertCondition; import org.graylog2.plugin.alarms.AlertCondition; import org.graylog2.plugin.alarms.callbacks.AlarmCallbackConfigurationException; import org.graylog2.plugin.configuration.Configuration; import org.graylog2.plugin.configuration.ConfigurationException; import org.graylog2.plugin.streams.Stream; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.hasItems; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; public class RundeckAlarmCallbackTest { private static final ImmutableMap<String, Object> VALID_CONFIG_SOURCE = ImmutableMap.<String, Object>builder() .put("rundeck_url", "http://rundeck.example.com") .put("job_id", "test-job-id") .put("api_token", "test_api_token") .put("args", "-test arg") .put("filter_include", "name:node01,tags:linux") .put("filter_exclude", "name:node02,tags:windows") .put("exclude_precedence", true) .build(); private final OkHttpClient okHttpClient = new OkHttpClient(); private RundeckAlarmCallback alarmCallback; @Before public void setUp() { alarmCallback = new RundeckAlarmCallback(okHttpClient); } @Test public void testInitialize() throws AlarmCallbackConfigurationException { final Configuration configuration = new Configuration(VALID_CONFIG_SOURCE); alarmCallback.initialize(configuration); } @Test public void testGetAttributes() throws AlarmCallbackConfigurationException { final Configuration configuration = new Configuration(VALID_CONFIG_SOURCE); alarmCallback.initialize(configuration); final Map<String, Object> attributes = alarmCallback.getAttributes(); assertThat(attributes.keySet(), hasItems("rundeck_url", "job_id", "api_token", "args", "filter_include", "filter_exclude", "exclude_precedence")); assertThat((String) attributes.get("api_token"), equalTo("****")); } @Test public void checkConfigurationSucceedsWithValidConfiguration() throws AlarmCallbackConfigurationException, ConfigurationException { alarmCallback.initialize(new Configuration(VALID_CONFIG_SOURCE)); alarmCallback.checkConfiguration(); } @Test public void testCallSucceedsWithValidConfiguration() throws Exception { final MockResponse mockResponse = new MockResponse() .addHeader(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_XML) .setResponseCode(200); final MockWebServer mockWebServer = new MockWebServer(); mockWebServer.enqueue(mockResponse); mockWebServer.start(); final Stream mockStream = mock(Stream.class); final AlertCondition.CheckResult checkResult = new AbstractAlertCondition.NegativeCheckResult( new DummyAlertCondition( mockStream, "id", new DateTime(2017, 3, 20, 0, 0, DateTimeZone.UTC), "user", Collections.emptyMap()) ); final Configuration configuration = new Configuration(VALID_CONFIG_SOURCE); configuration.setString("rundeck_url", mockWebServer.url("/").toString()); alarmCallback.initialize(configuration); alarmCallback.checkConfiguration(); alarmCallback.call(mockStream, checkResult); final RecordedRequest recordedRequest = mockWebServer.takeRequest(10, TimeUnit.SECONDS); assertEquals(1, mockWebServer.getRequestCount()); assertEquals("POST /api/12/job/test-job-id/executions HTTP/1.1", recordedRequest.getRequestLine()); assertEquals("text/xml", recordedRequest.getHeader("Accept")); assertEquals("test_api_token", recordedRequest.getHeader("X-Rundeck-Auth-Token")); assertEquals(0L, recordedRequest.getBodySize()); mockWebServer.shutdown(); } @Test(expected = ConfigurationException.class) public void checkConfigurationFailsIfJobIdIsMissing() throws AlarmCallbackConfigurationException, ConfigurationException { alarmCallback.initialize(validConfigurationWithout("job_id")); alarmCallback.checkConfiguration(); } @Test(expected = ConfigurationException.class) public void checkConfigurationFailsIfApiTokenIsMissing() throws AlarmCallbackConfigurationException, ConfigurationException { alarmCallback.initialize(validConfigurationWithout("api_token")); alarmCallback.checkConfiguration(); } @Test(expected = ConfigurationException.class) public void checkConfigurationFailsIfArgsContainsInvalidCharacters() throws AlarmCallbackConfigurationException, ConfigurationException { final Map<String, Object> configSource = ImmutableMap.<String, Object>builder() .put("job_id", "TEST-job-id") .put("api_token", "TEST_api_token") .put("args", "&-invalid arg") .build(); alarmCallback.initialize(new Configuration(configSource)); alarmCallback.checkConfiguration(); } @Test(expected = ConfigurationException.class) public void checkConfigurationFailsIfFieldArgsContainsInvalidCharacters() throws AlarmCallbackConfigurationException, ConfigurationException { final Map<String, Object> configSource = ImmutableMap.<String, Object>builder() .put("job_id", "TEST-job-id") .put("api_token", "TEST_api_token") .put("field_args", "&-invalid field arg") .build(); alarmCallback.initialize(new Configuration(configSource)); alarmCallback.checkConfiguration(); } @Test(expected = ConfigurationException.class) public void checkConfigurationFailsIfUsernameContainsInvalidCharacters() throws AlarmCallbackConfigurationException, ConfigurationException { final Map<String, Object> configSource = ImmutableMap.<String, Object>builder() .put("job_id", "TEST-job-id") .put("api_token", "TEST_api_token") .put("as_user", "invalid&user") .build(); alarmCallback.initialize(new Configuration(configSource)); alarmCallback.checkConfiguration(); } @Test(expected = ConfigurationException.class) public void checkConfigurationFailsIfRundeckUrlIsInvalid() throws AlarmCallbackConfigurationException, ConfigurationException { final Map<String, Object> configSource = ImmutableMap.<String, Object>builder() .put("job_id", "TEST-job-id") .put("api_token", "TEST_api_token") .put("rundeck_url", "Definitely$$Not#A!!URL") .build(); alarmCallback.initialize(new Configuration(configSource)); alarmCallback.checkConfiguration(); } @Test(expected = ConfigurationException.class) public void checkConfigurationFailsIfRundeckUrlIsNotHttpOrHttps() throws AlarmCallbackConfigurationException, ConfigurationException { final Map<String, Object> configSource = ImmutableMap.<String, Object>builder() .put("job_id", "TEST-job-id") .put("api_token", "TEST_api_token") .put("rundeck_url", "ftp://example.net") .build(); alarmCallback.initialize(new Configuration(configSource)); alarmCallback.checkConfiguration(); } @Test public void testGetRequestedConfiguration() { assertThat(alarmCallback.getRequestedConfiguration().asList().keySet(), hasItems("rundeck_url", "job_id", "api_token", "args", "filter_include", "filter_exclude", "exclude_precedence")); } @Test public void testGetName() { assertThat(alarmCallback.getName(), equalTo("Rundeck alarm callback")); } private Configuration validConfigurationWithout(final String key) { return new Configuration(Maps.filterEntries(VALID_CONFIG_SOURCE, new Predicate<Map.Entry<String, Object>>() { @Override public boolean apply(Map.Entry<String, Object> input) { return key.equals(input.getKey()); } })); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.asterix.external.parser; import java.io.DataOutput; import java.io.IOException; import org.apache.asterix.common.exceptions.ErrorCode; import org.apache.asterix.dataflow.data.nontagged.serde.AStringSerializerDeserializer; import org.apache.asterix.external.api.IDataParser; import org.apache.asterix.formats.nontagged.SerializerDeserializerProvider; import org.apache.asterix.om.base.ABinary; import org.apache.asterix.om.base.ABoolean; import org.apache.asterix.om.base.ACircle; import org.apache.asterix.om.base.ADate; import org.apache.asterix.om.base.ADateTime; import org.apache.asterix.om.base.ADayTimeDuration; import org.apache.asterix.om.base.ADouble; import org.apache.asterix.om.base.ADuration; import org.apache.asterix.om.base.AFloat; import org.apache.asterix.om.base.AGeometry; import org.apache.asterix.om.base.AInt16; import org.apache.asterix.om.base.AInt32; import org.apache.asterix.om.base.AInt64; import org.apache.asterix.om.base.AInt8; import org.apache.asterix.om.base.AInterval; import org.apache.asterix.om.base.ALine; import org.apache.asterix.om.base.AMutableBinary; import org.apache.asterix.om.base.AMutableCircle; import org.apache.asterix.om.base.AMutableDate; import org.apache.asterix.om.base.AMutableDateTime; import org.apache.asterix.om.base.AMutableDayTimeDuration; import org.apache.asterix.om.base.AMutableDouble; import org.apache.asterix.om.base.AMutableDuration; import org.apache.asterix.om.base.AMutableFloat; import org.apache.asterix.om.base.AMutableGeometry; import org.apache.asterix.om.base.AMutableInt16; import org.apache.asterix.om.base.AMutableInt32; import org.apache.asterix.om.base.AMutableInt64; import org.apache.asterix.om.base.AMutableInt8; import org.apache.asterix.om.base.AMutableInterval; import org.apache.asterix.om.base.AMutableLine; import org.apache.asterix.om.base.AMutablePoint; import org.apache.asterix.om.base.AMutablePoint3D; import org.apache.asterix.om.base.AMutableRectangle; import org.apache.asterix.om.base.AMutableString; import org.apache.asterix.om.base.AMutableTime; import org.apache.asterix.om.base.AMutableUUID; import org.apache.asterix.om.base.AMutableYearMonthDuration; import org.apache.asterix.om.base.ANull; import org.apache.asterix.om.base.APoint; import org.apache.asterix.om.base.APoint3D; import org.apache.asterix.om.base.ARectangle; import org.apache.asterix.om.base.AString; import org.apache.asterix.om.base.ATime; import org.apache.asterix.om.base.AUUID; import org.apache.asterix.om.base.AYearMonthDuration; import org.apache.asterix.om.base.temporal.ADateParserFactory; import org.apache.asterix.om.base.temporal.ADateTimeParserFactory; import org.apache.asterix.om.base.temporal.ADurationParserFactory; import org.apache.asterix.om.base.temporal.ADurationParserFactory.ADurationParseOption; import org.apache.asterix.om.base.temporal.ATimeParserFactory; import org.apache.asterix.om.types.ATypeTag; import org.apache.asterix.om.types.BuiltinType; import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.util.bytes.Base64Parser; import org.apache.hyracks.util.bytes.HexParser; import org.apache.hyracks.util.string.UTF8StringReader; import org.apache.hyracks.util.string.UTF8StringWriter; /** * Base class for data parsers. Includes the common set of definitions for * serializers/deserializers for built-in ADM types. */ public abstract class AbstractDataParser implements IDataParser { protected AMutableInt8 aInt8 = new AMutableInt8((byte) 0); protected AMutableInt16 aInt16 = new AMutableInt16((short) 0); protected AMutableInt32 aInt32 = new AMutableInt32(0); protected AMutableInt64 aInt64 = new AMutableInt64(0); protected AMutableDouble aDouble = new AMutableDouble(0); protected AMutableFloat aFloat = new AMutableFloat(0); protected AMutableString aString = new AMutableString(""); protected AMutableBinary aBinary = new AMutableBinary(null, 0, 0); protected AMutableString aStringFieldName = new AMutableString(""); protected AMutableUUID aUUID = new AMutableUUID(); protected AMutableGeometry aGeomtry = new AMutableGeometry(null); // For temporal and spatial data types protected AMutableTime aTime = new AMutableTime(0); protected AMutableDateTime aDateTime = new AMutableDateTime(0L); protected AMutableDuration aDuration = new AMutableDuration(0, 0); protected AMutableDayTimeDuration aDayTimeDuration = new AMutableDayTimeDuration(0); protected AMutableYearMonthDuration aYearMonthDuration = new AMutableYearMonthDuration(0); protected AMutablePoint aPoint = new AMutablePoint(0, 0); protected AMutablePoint3D aPoint3D = new AMutablePoint3D(0, 0, 0); protected AMutableCircle aCircle = new AMutableCircle(null, 0); protected AMutableRectangle aRectangle = new AMutableRectangle(null, null); protected AMutablePoint aPoint2 = new AMutablePoint(0, 0); protected AMutableLine aLine = new AMutableLine(null, null); protected AMutableDate aDate = new AMutableDate(0); protected AMutableInterval aInterval = new AMutableInterval(0L, 0L, (byte) 0); // Serializers @SuppressWarnings("unchecked") protected ISerializerDeserializer<ADouble> doubleSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ADOUBLE); @SuppressWarnings("unchecked") protected ISerializerDeserializer<AString> stringSerde = SerializerDeserializerProvider.INSTANCE.getAStringSerializerDeserializer(); @SuppressWarnings("unchecked") protected ISerializerDeserializer<ABinary> binarySerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ABINARY); @SuppressWarnings("unchecked") protected ISerializerDeserializer<AFloat> floatSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.AFLOAT); @SuppressWarnings("unchecked") protected ISerializerDeserializer<AInt8> int8Serde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.AINT8); @SuppressWarnings("unchecked") protected ISerializerDeserializer<AInt16> int16Serde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.AINT16); @SuppressWarnings("unchecked") protected ISerializerDeserializer<AInt32> int32Serde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.AINT32); @SuppressWarnings("unchecked") protected ISerializerDeserializer<AInt64> int64Serde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.AINT64); @SuppressWarnings("unchecked") protected ISerializerDeserializer<ABoolean> booleanSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ABOOLEAN); @SuppressWarnings("unchecked") protected ISerializerDeserializer<ANull> nullSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ANULL); protected final AStringSerializerDeserializer untaggedStringSerde = new AStringSerializerDeserializer(new UTF8StringWriter(), new UTF8StringReader()); protected final HexParser hexParser = new HexParser(); protected final Base64Parser base64Parser = new Base64Parser(); // For UUID, we assume that the format is the string representation of UUID // (xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxx) when parsing the data. // Thus, we need to call UUID.fromStringToAMutableUUID() to convert it to the internal representation (byte []). @SuppressWarnings("unchecked") protected ISerializerDeserializer<AUUID> uuidSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.AUUID); protected ISerializerDeserializer<AGeometry> geomSerde = SerializerDeserializerProvider.INSTANCE.getNonTaggedSerializerDeserializer(BuiltinType.AGEOMETRY); // To avoid race conditions, the serdes for temporal and spatial data types needs to be one per parser // ^^^^^^^^^^^^^^^^^^^^^^^^ ??? then why all these serdes are static? @SuppressWarnings("unchecked") protected static final ISerializerDeserializer<ATime> timeSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ATIME); @SuppressWarnings("unchecked") protected static final ISerializerDeserializer<ADate> dateSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ADATE); @SuppressWarnings("unchecked") protected static final ISerializerDeserializer<ADateTime> datetimeSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ADATETIME); @SuppressWarnings("unchecked") protected static final ISerializerDeserializer<ADuration> durationSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ADURATION); @SuppressWarnings("unchecked") protected static final ISerializerDeserializer<ADayTimeDuration> dayTimeDurationSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ADAYTIMEDURATION); @SuppressWarnings("unchecked") protected static final ISerializerDeserializer<AYearMonthDuration> yearMonthDurationSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.AYEARMONTHDURATION); @SuppressWarnings("unchecked") protected final static ISerializerDeserializer<APoint> pointSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.APOINT); @SuppressWarnings("unchecked") protected final static ISerializerDeserializer<APoint3D> point3DSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.APOINT3D); @SuppressWarnings("unchecked") protected final static ISerializerDeserializer<ACircle> circleSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ACIRCLE); @SuppressWarnings("unchecked") protected final static ISerializerDeserializer<ARectangle> rectangleSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ARECTANGLE); @SuppressWarnings("unchecked") protected final static ISerializerDeserializer<ALine> lineSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.ALINE); @SuppressWarnings("unchecked") protected static final ISerializerDeserializer<AInterval> intervalSerde = SerializerDeserializerProvider.INSTANCE.getSerializerDeserializer(BuiltinType.AINTERVAL); protected String filename; void setFilename(String filename) { this.filename = filename; } protected void parseTime(char[] buffer, int begin, int len, DataOutput out) throws HyracksDataException { int chrononTimeInMs = ATimeParserFactory.parseTimePart(buffer, begin, len); aTime.setValue(chrononTimeInMs); timeSerde.serialize(aTime, out); } protected void parseDate(char[] buffer, int begin, int len, DataOutput out) throws HyracksDataException { int chrononTimeInDays = ADateParserFactory.parseDatePartInDays(buffer, begin, len); aDate.setValue(chrononTimeInDays); dateSerde.serialize(aDate, out); } protected void parseDateTime(char[] buffer, int begin, int len, DataOutput out) throws HyracksDataException { long chrononDatetimeInMs = ADateTimeParserFactory.parseDateTimePart(buffer, begin, len); aDateTime.setValue(chrononDatetimeInMs); datetimeSerde.serialize(aDateTime, out); } protected void parseDuration(char[] buffer, int begin, int len, DataOutput out) throws HyracksDataException { ADurationParserFactory.parseDuration(buffer, begin, len, aDuration, ADurationParseOption.All); durationSerde.serialize(aDuration, out); } protected void parseDateTimeDuration(char[] buffer, int begin, int len, DataOutput out) throws HyracksDataException { ADurationParserFactory.parseDuration(buffer, begin, len, aDayTimeDuration, ADurationParseOption.All); dayTimeDurationSerde.serialize(aDayTimeDuration, out); } protected void parseYearMonthDuration(char[] buffer, int begin, int len, DataOutput out) throws HyracksDataException { ADurationParserFactory.parseDuration(buffer, begin, len, aYearMonthDuration, ADurationParseOption.All); yearMonthDurationSerde.serialize(aYearMonthDuration, out); } protected void parsePoint(char[] buffer, int begin, int len, DataOutput out) throws HyracksDataException { try { int commaIndex = indexOf(buffer, begin, len, ','); aPoint.setValue(parseDouble(buffer, begin, commaIndex - begin), parseDouble(buffer, commaIndex + 1, begin + len - commaIndex - 1)); pointSerde.serialize(aPoint, out); } catch (Exception e) { throw new ParseException(ErrorCode.PARSER_ADM_DATA_PARSER_WRONG_INSTANCE, e, new String(buffer, begin, len), "point"); } } protected void parse3DPoint(char[] buffer, int begin, int len, DataOutput out) throws HyracksDataException { try { int firstCommaIndex = indexOf(buffer, begin, len, ','); int secondCommaIndex = indexOf(buffer, firstCommaIndex + 1, begin + len - firstCommaIndex - 1, ','); aPoint3D.setValue(parseDouble(buffer, begin, firstCommaIndex - begin), parseDouble(buffer, firstCommaIndex + 1, secondCommaIndex - firstCommaIndex - 1), parseDouble(buffer, secondCommaIndex + 1, begin + len - secondCommaIndex - 1)); point3DSerde.serialize(aPoint3D, out); } catch (Exception e) { throw new ParseException(ErrorCode.PARSER_ADM_DATA_PARSER_WRONG_INSTANCE, e, new String(buffer, begin, len), "point3d"); } } protected void parseCircle(char[] buffer, int begin, int len, DataOutput out) throws HyracksDataException { try { int firstCommaIndex = indexOf(buffer, begin, len, ','); int spaceIndex = indexOf(buffer, firstCommaIndex + 1, begin + len - firstCommaIndex - 1, ' '); aPoint.setValue(parseDouble(buffer, begin, firstCommaIndex - begin), parseDouble(buffer, firstCommaIndex + 1, spaceIndex - firstCommaIndex - 1)); aCircle.setValue(aPoint, parseDouble(buffer, spaceIndex + 1, begin + len - spaceIndex - 1)); circleSerde.serialize(aCircle, out); } catch (Exception e) { throw new ParseException(ErrorCode.PARSER_ADM_DATA_PARSER_WRONG_INSTANCE, e, new String(buffer, begin, len), "circle"); } } protected void parseRectangle(char[] buffer, int begin, int len, DataOutput out) throws HyracksDataException { try { int spaceIndex = indexOf(buffer, begin, len, ' '); int firstCommaIndex = indexOf(buffer, begin, len, ','); aPoint.setValue(parseDouble(buffer, begin, firstCommaIndex - begin), parseDouble(buffer, firstCommaIndex + 1, spaceIndex - firstCommaIndex - 1)); int secondCommaIndex = indexOf(buffer, spaceIndex + 1, begin + len - spaceIndex - 1, ','); aPoint2.setValue(parseDouble(buffer, spaceIndex + 1, secondCommaIndex - spaceIndex - 1), parseDouble(buffer, secondCommaIndex + 1, begin + len - secondCommaIndex - 1)); if (aPoint.getX() > aPoint2.getX() && aPoint.getY() > aPoint2.getY()) { aRectangle.setValue(aPoint2, aPoint); } else if (aPoint.getX() < aPoint2.getX() && aPoint.getY() < aPoint2.getY()) { aRectangle.setValue(aPoint, aPoint2); } else { throw new IllegalArgumentException( "Rectangle arugment must be either (bottom left point, top right point) or (top right point, bottom left point)"); } rectangleSerde.serialize(aRectangle, out); } catch (Exception e) { throw new ParseException(ErrorCode.PARSER_ADM_DATA_PARSER_WRONG_INSTANCE, e, new String(buffer, begin, len), "rectangle"); } } protected void parseLine(char[] buffer, int begin, int len, DataOutput out) throws HyracksDataException { try { int spaceIndex = indexOf(buffer, begin, len, ' '); int firstCommaIndex = indexOf(buffer, begin, len, ','); aPoint.setValue(parseDouble(buffer, begin, firstCommaIndex - begin), parseDouble(buffer, firstCommaIndex + 1, spaceIndex - firstCommaIndex - 1)); int secondCommaIndex = indexOf(buffer, spaceIndex + 1, begin + len - spaceIndex - 1, ','); aPoint2.setValue(parseDouble(buffer, spaceIndex + 1, secondCommaIndex - spaceIndex - 1), parseDouble(buffer, secondCommaIndex + 1, begin + len - secondCommaIndex - 1)); aLine.setValue(aPoint, aPoint2); lineSerde.serialize(aLine, out); } catch (Exception e) { throw new ParseException(ErrorCode.PARSER_ADM_DATA_PARSER_WRONG_INSTANCE, e, new String(buffer, begin, len), "line"); } } protected void parseHexBinaryString(char[] input, int start, int length, DataOutput out) throws HyracksDataException { hexParser.generateByteArrayFromHexString(input, start, length); aBinary.setValue(hexParser.getByteArray(), 0, hexParser.getLength()); binarySerde.serialize(aBinary, out); } protected void parseBase64BinaryString(char[] input, int start, int length, DataOutput out) throws HyracksDataException { base64Parser.generatePureByteArrayFromBase64String(input, start, length); aBinary.setValue(base64Parser.getByteArray(), 0, base64Parser.getLength()); binarySerde.serialize(aBinary, out); } protected long parseDatePart(String interval, int startOffset, int endOffset) throws HyracksDataException { while (interval.charAt(endOffset) == '"' || interval.charAt(endOffset) == ' ') { endOffset--; } while (interval.charAt(startOffset) == '"' || interval.charAt(startOffset) == ' ') { startOffset++; } return ADateParserFactory.parseDatePart(interval, startOffset, endOffset - startOffset + 1); } protected int parseTimePart(String interval, int startOffset, int endOffset) throws HyracksDataException { while (interval.charAt(endOffset) == '"' || interval.charAt(endOffset) == ' ') { endOffset--; } while (interval.charAt(startOffset) == '"' || interval.charAt(startOffset) == ' ') { startOffset++; } return ATimeParserFactory.parseTimePart(interval, startOffset, endOffset - startOffset + 1); } protected double parseDouble(char[] buffer, int begin, int len) { // TODO: parse double directly from char[] String str = new String(buffer, begin, len); return Double.valueOf(str); } protected float parseFloat(char[] buffer, int begin, int len) { //TODO: pares float directly from char[] String str = new String(buffer, begin, len); return Float.valueOf(str); } protected int indexOf(char[] buffer, int begin, int len, char target) { for (int i = begin; i < begin + len; i++) { if (buffer[i] == target) { return i; } } throw new IllegalArgumentException("Cannot find " + target + " in " + new String(buffer, begin, len)); } protected void parseString(char[] buffer, int begin, int length, DataOutput out) throws HyracksDataException { try { out.writeByte(ATypeTag.STRING.serialize()); untaggedStringSerde.serialize(buffer, begin, length, out); } catch (IOException e) { throw new ParseException(e); } } }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package org.apache.cloudstack.framework.jobs.dao; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Date; import java.util.List; import org.apache.cloudstack.api.ApiConstants; import org.apache.log4j.Logger; import org.apache.cloudstack.framework.jobs.impl.AsyncJobVO; import org.apache.cloudstack.jobs.JobInfo; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.TransactionLegacy; public class AsyncJobDaoImpl extends GenericDaoBase<AsyncJobVO, Long> implements AsyncJobDao { private static final Logger s_logger = Logger.getLogger(AsyncJobDaoImpl.class.getName()); private final SearchBuilder<AsyncJobVO> pendingAsyncJobSearch; private final SearchBuilder<AsyncJobVO> pendingAsyncJobsSearch; private final SearchBuilder<AsyncJobVO> expiringAsyncJobSearch; private final SearchBuilder<AsyncJobVO> pseudoJobSearch; private final SearchBuilder<AsyncJobVO> pseudoJobCleanupSearch; private final SearchBuilder<AsyncJobVO> expiringUnfinishedAsyncJobSearch; private final SearchBuilder<AsyncJobVO> expiringCompletedAsyncJobSearch; private final SearchBuilder<AsyncJobVO> failureMsidAsyncJobSearch; private final GenericSearchBuilder<AsyncJobVO, Long> asyncJobTypeSearch; public AsyncJobDaoImpl() { pendingAsyncJobSearch = createSearchBuilder(); pendingAsyncJobSearch.and("instanceType", pendingAsyncJobSearch.entity().getInstanceType(), SearchCriteria.Op.EQ); pendingAsyncJobSearch.and("instanceId", pendingAsyncJobSearch.entity().getInstanceId(), SearchCriteria.Op.EQ); pendingAsyncJobSearch.and("status", pendingAsyncJobSearch.entity().getStatus(), SearchCriteria.Op.EQ); pendingAsyncJobSearch.done(); expiringAsyncJobSearch = createSearchBuilder(); expiringAsyncJobSearch.and("created", expiringAsyncJobSearch.entity().getCreated(), SearchCriteria.Op.LTEQ); expiringAsyncJobSearch.done(); pendingAsyncJobsSearch = createSearchBuilder(); pendingAsyncJobsSearch.and("instanceType", pendingAsyncJobsSearch.entity().getInstanceType(), SearchCriteria.Op.EQ); pendingAsyncJobsSearch.and("accountId", pendingAsyncJobsSearch.entity().getAccountId(), SearchCriteria.Op.EQ); pendingAsyncJobsSearch.and("status", pendingAsyncJobsSearch.entity().getStatus(), SearchCriteria.Op.EQ); pendingAsyncJobsSearch.done(); expiringUnfinishedAsyncJobSearch = createSearchBuilder(); expiringUnfinishedAsyncJobSearch.and("jobDispatcher", expiringUnfinishedAsyncJobSearch.entity().getDispatcher(), SearchCriteria.Op.NEQ); expiringUnfinishedAsyncJobSearch.and("created", expiringUnfinishedAsyncJobSearch.entity().getCreated(), SearchCriteria.Op.LTEQ); expiringUnfinishedAsyncJobSearch.and("completeMsId", expiringUnfinishedAsyncJobSearch.entity().getCompleteMsid(), SearchCriteria.Op.NULL); expiringUnfinishedAsyncJobSearch.and("jobStatus", expiringUnfinishedAsyncJobSearch.entity().getStatus(), SearchCriteria.Op.EQ); expiringUnfinishedAsyncJobSearch.done(); expiringCompletedAsyncJobSearch = createSearchBuilder(); expiringCompletedAsyncJobSearch.and(ApiConstants.REMOVED, expiringCompletedAsyncJobSearch.entity().getRemoved(), SearchCriteria.Op.LTEQ); expiringCompletedAsyncJobSearch.and("completeMsId", expiringCompletedAsyncJobSearch.entity().getCompleteMsid(), SearchCriteria.Op.NNULL); expiringCompletedAsyncJobSearch.and("jobStatus", expiringCompletedAsyncJobSearch.entity().getStatus(), SearchCriteria.Op.NEQ); expiringCompletedAsyncJobSearch.done(); pseudoJobSearch = createSearchBuilder(); pseudoJobSearch.and("jobDispatcher", pseudoJobSearch.entity().getDispatcher(), Op.EQ); pseudoJobSearch.and("instanceType", pseudoJobSearch.entity().getInstanceType(), Op.EQ); pseudoJobSearch.and("instanceId", pseudoJobSearch.entity().getInstanceId(), Op.EQ); pseudoJobSearch.done(); pseudoJobCleanupSearch = createSearchBuilder(); pseudoJobCleanupSearch.and("initMsid", pseudoJobCleanupSearch.entity().getInitMsid(), Op.EQ); pseudoJobCleanupSearch.done(); failureMsidAsyncJobSearch = createSearchBuilder(); failureMsidAsyncJobSearch.and("initMsid", failureMsidAsyncJobSearch.entity().getInitMsid(), Op.EQ); failureMsidAsyncJobSearch.and("instanceType", failureMsidAsyncJobSearch.entity().getInstanceType(), SearchCriteria.Op.EQ); failureMsidAsyncJobSearch.and("status", failureMsidAsyncJobSearch.entity().getStatus(), SearchCriteria.Op.EQ); failureMsidAsyncJobSearch.and("job_cmd", failureMsidAsyncJobSearch.entity().getCmd(), Op.IN); failureMsidAsyncJobSearch.done(); asyncJobTypeSearch = createSearchBuilder(Long.class); asyncJobTypeSearch.select(null, SearchCriteria.Func.COUNT, asyncJobTypeSearch.entity().getId()); asyncJobTypeSearch.and("job_info", asyncJobTypeSearch.entity().getCmdInfo(),Op.LIKE); asyncJobTypeSearch.and("job_cmd", asyncJobTypeSearch.entity().getCmd(), Op.IN); asyncJobTypeSearch.and("status", asyncJobTypeSearch.entity().getStatus(), SearchCriteria.Op.EQ); asyncJobTypeSearch.done(); } @Override public AsyncJobVO findInstancePendingAsyncJob(String instanceType, long instanceId) { SearchCriteria<AsyncJobVO> sc = pendingAsyncJobSearch.create(); sc.setParameters("instanceType", instanceType); sc.setParameters("instanceId", instanceId); sc.setParameters("status", JobInfo.Status.IN_PROGRESS); List<AsyncJobVO> l = listIncludingRemovedBy(sc); if (l != null && l.size() > 0) { if (l.size() > 1) { s_logger.warn("Instance " + instanceType + "-" + instanceId + " has multiple pending async-job"); } return l.get(0); } return null; } @Override public List<AsyncJobVO> findInstancePendingAsyncJobs(String instanceType, Long accountId) { SearchCriteria<AsyncJobVO> sc = pendingAsyncJobsSearch.create(); sc.setParameters("instanceType", instanceType); if (accountId != null) { sc.setParameters("accountId", accountId); } sc.setParameters("status", JobInfo.Status.IN_PROGRESS); return listBy(sc); } @Override public AsyncJobVO findPseudoJob(long threadId, long msid) { SearchCriteria<AsyncJobVO> sc = pseudoJobSearch.create(); sc.setParameters("jobDispatcher", AsyncJobVO.JOB_DISPATCHER_PSEUDO); sc.setParameters("instanceType", AsyncJobVO.PSEUDO_JOB_INSTANCE_TYPE); sc.setParameters("instanceId", threadId); List<AsyncJobVO> result = listBy(sc); if (result != null && result.size() > 0) { assert (result.size() == 1); return result.get(0); } return null; } @Override public void cleanupPseduoJobs(long msid) { SearchCriteria<AsyncJobVO> sc = pseudoJobCleanupSearch.create(); sc.setParameters("initMsid", msid); this.expunge(sc); } @Override public List<AsyncJobVO> getExpiredJobs(Date cutTime, int limit) { SearchCriteria<AsyncJobVO> sc = expiringAsyncJobSearch.create(); sc.setParameters("created", cutTime); Filter filter = new Filter(AsyncJobVO.class, "created", true, 0L, (long)limit); return listIncludingRemovedBy(sc, filter); } @Override public List<AsyncJobVO> getExpiredUnfinishedJobs(Date cutTime, int limit) { SearchCriteria<AsyncJobVO> sc = expiringUnfinishedAsyncJobSearch.create(); sc.setParameters("jobDispatcher", AsyncJobVO.JOB_DISPATCHER_PSEUDO); sc.setParameters("created", cutTime); sc.setParameters("jobStatus", JobInfo.Status.IN_PROGRESS); Filter filter = new Filter(AsyncJobVO.class, "created", true, 0L, (long)limit); return listIncludingRemovedBy(sc, filter); } @Override public List<AsyncJobVO> getExpiredCompletedJobs(final Date cutTime, final int limit) { final SearchCriteria<AsyncJobVO> sc = expiringCompletedAsyncJobSearch.create(); sc.setParameters(ApiConstants.REMOVED, cutTime); sc.setParameters("jobStatus", JobInfo.Status.IN_PROGRESS); final Filter filter = new Filter(AsyncJobVO.class, ApiConstants.REMOVED, true, 0L, (long)limit); return listIncludingRemovedBy(sc, filter); } @Override @DB public void resetJobProcess(long msid, int jobResultCode, String jobResultMessage) { String sql = "UPDATE async_job SET job_status=?, job_result_code=?, job_result=? where job_status=? AND (job_executing_msid=? OR (job_executing_msid IS NULL AND job_init_msid=?))"; TransactionLegacy txn = TransactionLegacy.currentTxn(); PreparedStatement pstmt = null; try { pstmt = txn.prepareAutoCloseStatement(sql); pstmt.setInt(1, JobInfo.Status.FAILED.ordinal()); pstmt.setInt(2, jobResultCode); pstmt.setString(3, jobResultMessage); pstmt.setInt(4, JobInfo.Status.IN_PROGRESS.ordinal()); pstmt.setLong(5, msid); pstmt.setLong(6, msid); pstmt.execute(); } catch (SQLException e) { s_logger.warn("Unable to reset job status for management server " + msid, e); } catch (Throwable e) { s_logger.warn("Unable to reset job status for management server " + msid, e); } } @Override public List<AsyncJobVO> getResetJobs(long msid) { SearchCriteria<AsyncJobVO> sc = pendingAsyncJobSearch.create(); sc.setParameters("status", JobInfo.Status.IN_PROGRESS); // construct query: (job_executing_msid=msid OR (job_executing_msid IS NULL AND job_init_msid=msid)) SearchCriteria<AsyncJobVO> msQuery = createSearchCriteria(); msQuery.addOr("executingMsid", SearchCriteria.Op.EQ, msid); SearchCriteria<AsyncJobVO> initMsQuery = createSearchCriteria(); initMsQuery.addAnd("executingMsid", SearchCriteria.Op.NULL); initMsQuery.addAnd("initMsid", SearchCriteria.Op.EQ, msid); msQuery.addOr("initMsid", SearchCriteria.Op.SC, initMsQuery); sc.addAnd("executingMsid", SearchCriteria.Op.SC, msQuery); Filter filter = new Filter(AsyncJobVO.class, "created", true, null, null); return listIncludingRemovedBy(sc, filter); } @Override public List<AsyncJobVO> getFailureJobsSinceLastMsStart(long msId, String... cmds) { SearchCriteria<AsyncJobVO> sc = failureMsidAsyncJobSearch.create(); sc.setParameters("initMsid", msId); sc.setParameters("status", AsyncJobVO.Status.FAILED); sc.setParameters("job_cmd", (Object[])cmds); return listBy(sc); } @Override public long countPendingJobs(String havingInfo, String... cmds) { SearchCriteria<Long> sc = asyncJobTypeSearch.create(); sc.setParameters("status", JobInfo.Status.IN_PROGRESS); sc.setParameters("job_cmd", (Object[])cmds); sc.setParameters("job_info", "%" + havingInfo + "%"); List<Long> results = customSearch(sc, null); return results.get(0); } }
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.gradle.service.settings; import com.intellij.openapi.externalSystem.model.settings.LocationSettingType; import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil; import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil; import com.intellij.openapi.externalSystem.util.PaintAwarePanel; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.ui.TextComponentAccessor; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.components.JBCheckBox; import com.intellij.ui.components.JBLabel; import com.intellij.ui.components.JBTextField; import org.gradle.initialization.BuildLayoutParameters; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.gradle.settings.GradleSettings; import org.jetbrains.plugins.gradle.util.GradleBundle; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.io.File; /** * @author Vladislav.Soroka * @since 4/21/2015 */ public class IdeaGradleSystemSettingsControlBuilder implements GradleSystemSettingsControlBuilder { @NotNull private final GradleSettings myInitialSettings; // Used by reflection at showUi() and disposeUiResources() @SuppressWarnings("FieldCanBeLocal") @Nullable private JBLabel myServiceDirectoryLabel; @Nullable private TextFieldWithBrowseButton myServiceDirectoryPathField; private boolean myServiceDirectoryPathModifiedByUser; private boolean dropServiceDirectory; // Used by reflection at showUi() and disposeUiResources() @SuppressWarnings("FieldCanBeLocal") @Nullable private JBLabel myGradleVmOptionsLabel; @Nullable private JBTextField myGradleVmOptionsField; private boolean dropVmOptions; @Nullable private JBCheckBox myOfflineModeBox; private boolean dropOfflineModeBox; public IdeaGradleSystemSettingsControlBuilder(@NotNull GradleSettings initialSettings) { myInitialSettings = initialSettings; } @Override public void fillUi(@NotNull PaintAwarePanel canvas, int indentLevel) { if (!dropOfflineModeBox) { myOfflineModeBox = new JBCheckBox(GradleBundle.message("gradle.settings.text.offline_work")); canvas.add(myOfflineModeBox, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); } addServiceDirectoryControl(canvas, indentLevel); if (!dropVmOptions) { myGradleVmOptionsLabel = new JBLabel(GradleBundle.message("gradle.settings.text.vm.options")); canvas.add(myGradleVmOptionsLabel, ExternalSystemUiUtil.getLabelConstraints(indentLevel)); myGradleVmOptionsField = new JBTextField(); canvas.add(myGradleVmOptionsField, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); } } @Override public void showUi(boolean show) { ExternalSystemUiUtil.showUi(this, show); } @Override public void reset() { if (myServiceDirectoryPathField != null) { myServiceDirectoryPathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor()); myServiceDirectoryPathField.setText(""); String path = myInitialSettings.getServiceDirectoryPath(); if (StringUtil.isEmpty(path)) { deduceServiceDirectory(myServiceDirectoryPathField); myServiceDirectoryPathModifiedByUser = false; } else { myServiceDirectoryPathField.setText(path); } } if (myGradleVmOptionsField != null) { myGradleVmOptionsField.setText(trimIfPossible(myInitialSettings.getGradleVmOptions())); } if (myOfflineModeBox != null) { myOfflineModeBox.setSelected(myInitialSettings.isOfflineWork()); } } @Override public boolean isModified() { if (myServiceDirectoryPathModifiedByUser && myServiceDirectoryPathField != null && !Comparing.equal(ExternalSystemApiUtil.normalizePath(myServiceDirectoryPathField.getText()), ExternalSystemApiUtil.normalizePath(myInitialSettings.getServiceDirectoryPath()))) { return true; } if (myGradleVmOptionsField != null && !Comparing.equal(trimIfPossible(myGradleVmOptionsField.getText()), trimIfPossible( myInitialSettings.getGradleVmOptions()))) { return true; } if (myOfflineModeBox != null && myOfflineModeBox.isSelected() != myInitialSettings.isOfflineWork()) { return true; } return false; } @Override public void apply(@NotNull GradleSettings settings) { if (myServiceDirectoryPathField != null && myServiceDirectoryPathModifiedByUser) { settings.setServiceDirectoryPath(ExternalSystemApiUtil.normalizePath(myServiceDirectoryPathField.getText())); } if (myGradleVmOptionsField != null) { settings.setGradleVmOptions(trimIfPossible(myGradleVmOptionsField.getText())); } if (myOfflineModeBox != null) { settings.setOfflineWork(myOfflineModeBox.isSelected()); } } @Override public boolean validate(@NotNull GradleSettings settings) { return true; } @Override public void disposeUIResources() { ExternalSystemUiUtil.disposeUi(this); } @NotNull @Override public GradleSettings getInitialSettings() { return myInitialSettings; } public IdeaGradleSystemSettingsControlBuilder dropServiceDirectory() { dropServiceDirectory = true; return this; } public IdeaGradleSystemSettingsControlBuilder dropVmOptions() { dropVmOptions = true; return this; } public IdeaGradleSystemSettingsControlBuilder dropOfflineModeBox() { dropOfflineModeBox = true; return this; } private void addServiceDirectoryControl(PaintAwarePanel canvas, int indentLevel) { if (dropServiceDirectory) return; myServiceDirectoryLabel = new JBLabel(GradleBundle.message("gradle.settings.text.service.dir.path")); myServiceDirectoryPathField = new TextFieldWithBrowseButton(); myServiceDirectoryPathField.addBrowseFolderListener("", GradleBundle.message("gradle.settings.title.service.dir.path"), null, new FileChooserDescriptor(false, true, false, false, false, false), TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT); myServiceDirectoryPathField.getTextField().getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { myServiceDirectoryPathModifiedByUser = true; myServiceDirectoryPathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor()); } @Override public void removeUpdate(DocumentEvent e) { myServiceDirectoryPathModifiedByUser = true; myServiceDirectoryPathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor()); } @Override public void changedUpdate(DocumentEvent e) { } }); canvas.add(myServiceDirectoryLabel, ExternalSystemUiUtil.getLabelConstraints(indentLevel)); canvas.add(myServiceDirectoryPathField, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); } private static void deduceServiceDirectory(@NotNull TextFieldWithBrowseButton serviceDirectoryPathField) { File gradleUserHomeDir = new BuildLayoutParameters().getGradleUserHomeDir(); serviceDirectoryPathField.setText(FileUtil.toSystemIndependentName(gradleUserHomeDir.getPath())); serviceDirectoryPathField.getTextField().setForeground(LocationSettingType.DEDUCED.getColor()); } @Nullable private static String trimIfPossible(@Nullable String s) { return StringUtil.nullize(StringUtil.trim(s)); } }
/* * Copyright (C) 2013 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 com.google.common.annotations.GwtCompatible; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.j2objc.annotations.WeakOuter; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.checkerframework.checker.nullness.compatqual.NullableDecl; /** * Skeletal, implementation-agnostic implementation of the {@link Table} interface. * * @author Louis Wasserman */ @GwtCompatible abstract class AbstractTable<R, C, V> implements Table<R, C, V> { @Override public boolean containsRow(@NullableDecl Object rowKey) { return Maps.safeContainsKey(rowMap(), rowKey); } @Override public boolean containsColumn(@NullableDecl Object columnKey) { return Maps.safeContainsKey(columnMap(), columnKey); } @Override public Set<R> rowKeySet() { return rowMap().keySet(); } @Override public Set<C> columnKeySet() { return columnMap().keySet(); } @Override public boolean containsValue(@NullableDecl Object value) { for (Map<C, V> row : rowMap().values()) { if (row.containsValue(value)) { return true; } } return false; } @Override public boolean contains(@NullableDecl Object rowKey, @NullableDecl Object columnKey) { Map<C, V> row = Maps.safeGet(rowMap(), rowKey); return row != null && Maps.safeContainsKey(row, columnKey); } @Override public V get(@NullableDecl Object rowKey, @NullableDecl Object columnKey) { Map<C, V> row = Maps.safeGet(rowMap(), rowKey); return (row == null) ? null : Maps.safeGet(row, columnKey); } @Override public boolean isEmpty() { return size() == 0; } @Override public void clear() { Iterators.clear(cellSet().iterator()); } @CanIgnoreReturnValue @Override public V remove(@NullableDecl Object rowKey, @NullableDecl Object columnKey) { Map<C, V> row = Maps.safeGet(rowMap(), rowKey); return (row == null) ? null : Maps.safeRemove(row, columnKey); } @CanIgnoreReturnValue @Override public V put(R rowKey, C columnKey, V value) { return row(rowKey).put(columnKey, value); } @Override public void putAll(Table<? extends R, ? extends C, ? extends V> table) { for (Table.Cell<? extends R, ? extends C, ? extends V> cell : table.cellSet()) { put(cell.getRowKey(), cell.getColumnKey(), cell.getValue()); } } private transient Set<Cell<R, C, V>> cellSet; @Override public Set<Cell<R, C, V>> cellSet() { Set<Cell<R, C, V>> result = cellSet; return (result == null) ? cellSet = createCellSet() : result; } Set<Cell<R, C, V>> createCellSet() { return new CellSet(); } abstract Iterator<Table.Cell<R, C, V>> cellIterator(); @WeakOuter class CellSet extends AbstractSet<Cell<R, C, V>> { @Override public boolean contains(Object o) { if (o instanceof Cell) { Cell<?, ?, ?> cell = (Cell<?, ?, ?>) o; Map<C, V> row = Maps.safeGet(rowMap(), cell.getRowKey()); return row != null && Collections2.safeContains( row.entrySet(), Maps.immutableEntry(cell.getColumnKey(), cell.getValue())); } return false; } @Override public boolean remove(@NullableDecl Object o) { if (o instanceof Cell) { Cell<?, ?, ?> cell = (Cell<?, ?, ?>) o; Map<C, V> row = Maps.safeGet(rowMap(), cell.getRowKey()); return row != null && Collections2.safeRemove( row.entrySet(), Maps.immutableEntry(cell.getColumnKey(), cell.getValue())); } return false; } @Override public void clear() { AbstractTable.this.clear(); } @Override public Iterator<Table.Cell<R, C, V>> iterator() { return cellIterator(); } @Override public int size() { return AbstractTable.this.size(); } } private transient Collection<V> values; @Override public Collection<V> values() { Collection<V> result = values; return (result == null) ? values = createValues() : result; } Collection<V> createValues() { return new Values(); } Iterator<V> valuesIterator() { return new TransformedIterator<Cell<R, C, V>, V>(cellSet().iterator()) { @Override V transform(Cell<R, C, V> cell) { return cell.getValue(); } }; } @WeakOuter class Values extends AbstractCollection<V> { @Override public Iterator<V> iterator() { return valuesIterator(); } @Override public boolean contains(Object o) { return containsValue(o); } @Override public void clear() { AbstractTable.this.clear(); } @Override public int size() { return AbstractTable.this.size(); } } @Override public boolean equals(@NullableDecl Object obj) { return Tables.equalsImpl(this, obj); } @Override public int hashCode() { return cellSet().hashCode(); } /** Returns the string representation {@code rowMap().toString()}. */ @Override public String toString() { return rowMap().toString(); } }
/* Tree234.java */ package dict; /** * A Tree234 implements an ordered integer dictionary ADT using a 2-3-4 tree. * Only int keys are stored; no object is associated with each key. Duplicate * keys are not stored in the tree. * * @author Jonathan Shewchuk **/ public class Tree234 extends IntDictionary { /** * You may add fields if you wish, but don't change anything that * would prevent toString() or find() from working correctly. * * (inherited) size is the number of keys in the dictionary. * root is the root of the 2-3-4 tree. **/ Tree234Node root; /** * Tree234() constructs an empty 2-3-4 tree. * * You may change this constructor, but you may not change the fact that * an empty Tree234 contains no nodes. */ public Tree234() { root = null; size = 0; } /** * toString() prints this Tree234 as a String. Each node is printed * in the form such as (for a 3-key node) * * (child1)key1(child2)key2(child3)key3(child4) * * where each child is a recursive call to toString, and null children * are printed as a space with no parentheses. Here's an example. * ((1)7(11 16)22(23)28(37 49))50((60)84(86 95 100)) * * DO NOT CHANGE THIS METHOD. The test code depends on it. * * @return a String representation of the 2-3-4 tree. **/ @Override public String toString() { if (root == null) { return ""; } else { /* Most of the work is done by Tree234Node.toString(). */ return root.toString(); } } /** * printTree() prints this Tree234 as a tree, albeit sideways. * * You're welcome to change this method if you like. It won't be tested. **/ public void printTree() { if (root != null) { /* Most of the work is done by Tree234Node.printSubtree(). */ root.printSubtree(0); } } /** * find() prints true if "key" is in this 2-3-4 tree; false otherwise. * * @param key is the key sought. * @return true if "key" is in the tree; false otherwise. **/ public boolean find(int key) { Tree234Node node = root; while (node != null) { if (key < node.key1) { node = node.child1; } else if (key == node.key1) { return true; } else if ((node.keys == 1) || (key < node.key2)) { node = node.child2; } else if (key == node.key2) { return true; } else if ((node.keys == 2) || (key < node.key3)) { node = node.child3; } else if (key == node.key3) { return true; } else { node = node.child4; } } return false; } /** * insert() inserts the key "key" into this 2-3-4 tree. If "key" is * already present, a duplicate copy is NOT inserted. * * @param key is the key sought. **/ public void insert(int key) { // if tree is empty, make new root node containing the key if (isEmpty()) { root = new Tree234Node(null, key); size = 1; return; } // start at root and iterate until hitting a leaf node Tree234Node node = root; while (node != null) { // if the key is already in the tree, we are done. Nothing inserted. if (keyInNode(key, node)) { return; } // any node with 3 keys must send its middle key up to its parent if (node.keys == 3) { // send the middle node to either parent or new root if (node == root) { root = new Tree234Node(null, node.key2); node.parent = root; } else { insertKeyInParent(node); } // split the node into two nodes, each with one key Tree234Node left = new Tree234Node(node.parent, node.key1); Tree234Node right = new Tree234Node(node.parent, node.key3); left.keys = 1; right.keys = 1; // fix parent's pointers to children to include the new nodes if (node.key2 == node.parent.key1) { node.parent.child4 = node.parent.child3; node.parent.child3 = node.parent.child2; node.parent.child2 = right; node.parent.child1 = left; } else if (node.key2 == node.parent.key2) { node.parent.child4 = node.parent.child3; node.parent.child3 = right; node.parent.child2 = left; } else { node.parent.child4 = right; node.parent.child3 = left; } // assign the split node's children to the two new nodes left.child1 = node.child1; left.child2 = node.child2; right.child1 = node.child3; right.child2 = node.child4; // if there are children, set the children's pointers to their // new parents if (node.child1 != null) { left.child1.parent = left; left.child2.parent = left; right.child1.parent = right; right.child2.parent = right; } else { // otherwise jump ship from the split node to one of the // new ones if (key < node.key1) { node = left; } else { node = right; } } } // now we get the next node Tree234Node next = getNextNode(node, key); // if we have reached a leaf, insert the key here if (next == null) { insertKey(node, key); size++; } node = next; } } /** * keyInNode() determines if a given key is in node "n". * * @param key the key sought. * @param n the node to check in. * @return true if the key is in the node, false otherwise. */ private boolean keyInNode(int key, Tree234Node n) { return (key == n.key1) || (key == n.key2) || (key == n.key3); } /** * insertKeyInParent() is a helper method for insert() that takes the middle * key from a three-key node and moves it to the correct position in that * node's parent. * * @param child the node whose middle key is to be kicked upstairs. */ private void insertKeyInParent(Tree234Node child) { Tree234Node parent = child.parent; if (child == parent.child1) { parent.key3 = parent.key2; parent.key2 = parent.key1; parent.key1 = child.key2; } else if (child == parent.child2) { parent.key3 = parent.key2; parent.key2 = child.key2; } else if (child == parent.child3) { parent.key3 = child.key2; } else { System.err.println("ERROR: There were more than 3 children!"); } parent.keys++; } /** * getNextNode() takes a node and returns the child node that should be * searched next for the key. * * @param node the current (parent) node. * @param key the key sought. * @return the node to be searched next. */ private Tree234Node getNextNode(Tree234Node node, int key) { if (key < node.key1) { return node.child1; } else if ((node.keys == 1) || (key < node.key2)) { return node.child2; } else if ((node.keys == 2) || (key < node.key3)) { return node.child3; } else { return node.child4; } } /** * insertKey() places a given key into the correct position in "node". It * assumes the key is not already in the node. * @param node the node within which to place the key. * @param key the key to be inserted. */ private void insertKey(Tree234Node node, int key) { if (key < node.key1) { node.key3 = node.key2; node.key2 = node.key1; node.key1 = key; } else if ((node.keys < 2) || (key < node.key2)) { node.key3 = node.key2; node.key2 = key; } else { node.key3 = key; } node.keys++; } /** * testHelper() prints the String representation of this tree, then * compares it with the expected String, and prints an error message if * the two are not equal. * * @param correctString is what the tree should look like. **/ public void testHelper(String correctString) { String treeString = toString(); System.out.println(treeString); if (!treeString.equals(correctString)) { System.out.println("ERROR: Should be " + correctString); } } /** * main() is a bunch of test code. Feel free to add test code of your own; * this code won't be tested or graded. **/ public static void main(String[] args) { Tree234 t = new Tree234(); System.out.println("\nInserting 84."); t.insert(84); t.testHelper("84"); System.out.println("\nInserting 7."); t.insert(7); t.testHelper("7 84"); System.out.println("\nInserting 22."); t.insert(22); t.testHelper("7 22 84"); System.out.println("\nInserting 95."); t.insert(95); t.testHelper("(7)22(84 95)"); System.out.println("\nInserting 50."); t.insert(50); t.testHelper("(7)22(50 84 95)"); System.out.println("\nInserting 11."); t.insert(11); t.testHelper("(7 11)22(50 84 95)"); System.out.println("\nInserting 37."); t.insert(37); t.testHelper("(7 11)22(37 50)84(95)"); System.out.println("\nInserting 60."); t.insert(60); t.testHelper("(7 11)22(37 50 60)84(95)"); System.out.println("\nInserting 1."); t.insert(1); t.testHelper("(1 7 11)22(37 50 60)84(95)"); System.out.println("\nInserting 23."); t.insert(23); t.testHelper("(1 7 11)22(23 37)50(60)84(95)"); System.out.println("\nInserting 16."); t.insert(16); t.testHelper("((1)7(11 16)22(23 37))50((60)84(95))"); System.out.println("\nInserting 100."); t.insert(100); t.testHelper("((1)7(11 16)22(23 37))50((60)84(95 100))"); System.out.println("\nInserting 28."); t.insert(28); t.testHelper("((1)7(11 16)22(23 28 37))50((60)84(95 100))"); System.out.println("\nInserting 86."); t.insert(86); t.testHelper("((1)7(11 16)22(23 28 37))50((60)84(86 95 100))"); System.out.println("\nInserting 49."); t.insert(49); t.testHelper("((1)7(11 16)22(23)28(37 49))50((60)84(86 95 100))"); System.out.println("\nInserting 81."); t.insert(81); t.testHelper("((1)7(11 16)22(23)28(37 49))50((60 81)84(86 95 100))"); System.out.println("\nInserting 51."); t.insert(51); t.testHelper("((1)7(11 16)22(23)28(37 49))50((51 60 81)84(86 95 100))"); System.out.println("\nInserting 99."); t.insert(99); t.testHelper("((1)7(11 16)22(23)28(37 49))50((51 60 81)84(86)95(99 100))"); System.out.println("\nInserting 75."); t.insert(75); t.testHelper("((1)7(11 16)22(23)28(37 49))50((51)60(75 81)84(86)95" + "(99 100))"); System.out.println("\nInserting 66."); t.insert(66); t.testHelper("((1)7(11 16)22(23)28(37 49))50((51)60(66 75 81))84((86)95" + "(99 100))"); System.out.println("\nInserting 4."); t.insert(4); t.testHelper("((1 4)7(11 16))22((23)28(37 49))50((51)60(66 75 81))84" + "((86)95(99 100))"); System.out.println("\nInserting 80."); t.insert(80); t.testHelper("(((1 4)7(11 16))22((23)28(37 49)))50(((51)60(66)75" + "(80 81))84((86)95(99 100)))"); System.out.println("\nFinal tree:"); t.printTree(); } }
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.ads.googleads.v9.services; import com.google.ads.googleads.v9.resources.SmartCampaignSearchTermView; import com.google.ads.googleads.v9.resources.SmartCampaignSearchTermViewName; import com.google.ads.googleads.v9.services.stub.SmartCampaignSearchTermViewServiceStub; import com.google.ads.googleads.v9.services.stub.SmartCampaignSearchTermViewServiceStubSettings; import com.google.api.core.BetaApi; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.rpc.UnaryCallable; import java.io.IOException; import java.util.concurrent.TimeUnit; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Service Description: Service to manage Smart campaign search term views. * * <p>This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: * * <pre>{@code * try (SmartCampaignSearchTermViewServiceClient smartCampaignSearchTermViewServiceClient = * SmartCampaignSearchTermViewServiceClient.create()) { * SmartCampaignSearchTermViewName resourceName = * SmartCampaignSearchTermViewName.of("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[QUERY]"); * SmartCampaignSearchTermView response = * smartCampaignSearchTermViewServiceClient.getSmartCampaignSearchTermView(resourceName); * } * }</pre> * * <p>Note: close() needs to be called on the SmartCampaignSearchTermViewServiceClient object to * clean up resources such as threads. In the example above, try-with-resources is used, which * automatically calls close(). * * <p>The surface of this class includes several types of Java methods for each of the API's * methods: * * <ol> * <li> A "flattened" method. With this type of method, the fields of the request type have been * converted into function parameters. It may be the case that not all fields are available as * parameters, and not every API method will have a flattened method entry point. * <li> A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. * <li> A "callable" method. This type of method takes no parameters and returns an immutable API * callable object, which can be used to initiate calls to the service. * </ol> * * <p>See the individual methods for example code. * * <p>Many parameters require resource names to be formatted in a particular way. To assist with * these names, this class includes a format method for each type of name, and additionally a parse * method to extract the individual identifiers contained within names that are returned. * * <p>This class can be customized by passing in a custom instance of * SmartCampaignSearchTermViewServiceSettings to create(). For example: * * <p>To customize credentials: * * <pre>{@code * SmartCampaignSearchTermViewServiceSettings smartCampaignSearchTermViewServiceSettings = * SmartCampaignSearchTermViewServiceSettings.newBuilder() * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials)) * .build(); * SmartCampaignSearchTermViewServiceClient smartCampaignSearchTermViewServiceClient = * SmartCampaignSearchTermViewServiceClient.create(smartCampaignSearchTermViewServiceSettings); * }</pre> * * <p>To customize the endpoint: * * <pre>{@code * SmartCampaignSearchTermViewServiceSettings smartCampaignSearchTermViewServiceSettings = * SmartCampaignSearchTermViewServiceSettings.newBuilder().setEndpoint(myEndpoint).build(); * SmartCampaignSearchTermViewServiceClient smartCampaignSearchTermViewServiceClient = * SmartCampaignSearchTermViewServiceClient.create(smartCampaignSearchTermViewServiceSettings); * }</pre> * * <p>Please refer to the GitHub repository's samples for more quickstart code snippets. */ @Generated("by gapic-generator-java") public class SmartCampaignSearchTermViewServiceClient implements BackgroundResource { private final SmartCampaignSearchTermViewServiceSettings settings; private final SmartCampaignSearchTermViewServiceStub stub; /** Constructs an instance of SmartCampaignSearchTermViewServiceClient with default settings. */ public static final SmartCampaignSearchTermViewServiceClient create() throws IOException { return create(SmartCampaignSearchTermViewServiceSettings.newBuilder().build()); } /** * Constructs an instance of SmartCampaignSearchTermViewServiceClient, using the given settings. * The channels are created based on the settings passed in, or defaults for any settings that are * not set. */ public static final SmartCampaignSearchTermViewServiceClient create( SmartCampaignSearchTermViewServiceSettings settings) throws IOException { return new SmartCampaignSearchTermViewServiceClient(settings); } /** * Constructs an instance of SmartCampaignSearchTermViewServiceClient, using the given stub for * making calls. This is for advanced usage - prefer using * create(SmartCampaignSearchTermViewServiceSettings). */ @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public static final SmartCampaignSearchTermViewServiceClient create( SmartCampaignSearchTermViewServiceStub stub) { return new SmartCampaignSearchTermViewServiceClient(stub); } /** * Constructs an instance of SmartCampaignSearchTermViewServiceClient, using the given settings. * This is protected so that it is easy to make a subclass, but otherwise, the static factory * methods should be preferred. */ protected SmartCampaignSearchTermViewServiceClient( SmartCampaignSearchTermViewServiceSettings settings) throws IOException { this.settings = settings; this.stub = ((SmartCampaignSearchTermViewServiceStubSettings) settings.getStubSettings()).createStub(); } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") protected SmartCampaignSearchTermViewServiceClient(SmartCampaignSearchTermViewServiceStub stub) { this.settings = null; this.stub = stub; } public final SmartCampaignSearchTermViewServiceSettings getSettings() { return settings; } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public SmartCampaignSearchTermViewServiceStub getStub() { return stub; } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the attributes of the requested Smart campaign search term view. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() [HeaderError]() * [InternalError]() [QuotaError]() [RequestError]() * * <p>Sample code: * * <pre>{@code * try (SmartCampaignSearchTermViewServiceClient smartCampaignSearchTermViewServiceClient = * SmartCampaignSearchTermViewServiceClient.create()) { * SmartCampaignSearchTermViewName resourceName = * SmartCampaignSearchTermViewName.of("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[QUERY]"); * SmartCampaignSearchTermView response = * smartCampaignSearchTermViewServiceClient.getSmartCampaignSearchTermView(resourceName); * } * }</pre> * * @param resourceName Required. The resource name of the Smart campaign search term view to * fetch. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final SmartCampaignSearchTermView getSmartCampaignSearchTermView( SmartCampaignSearchTermViewName resourceName) { GetSmartCampaignSearchTermViewRequest request = GetSmartCampaignSearchTermViewRequest.newBuilder() .setResourceName(resourceName == null ? null : resourceName.toString()) .build(); return getSmartCampaignSearchTermView(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the attributes of the requested Smart campaign search term view. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() [HeaderError]() * [InternalError]() [QuotaError]() [RequestError]() * * <p>Sample code: * * <pre>{@code * try (SmartCampaignSearchTermViewServiceClient smartCampaignSearchTermViewServiceClient = * SmartCampaignSearchTermViewServiceClient.create()) { * String resourceName = * SmartCampaignSearchTermViewName.of("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[QUERY]") * .toString(); * SmartCampaignSearchTermView response = * smartCampaignSearchTermViewServiceClient.getSmartCampaignSearchTermView(resourceName); * } * }</pre> * * @param resourceName Required. The resource name of the Smart campaign search term view to * fetch. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final SmartCampaignSearchTermView getSmartCampaignSearchTermView(String resourceName) { GetSmartCampaignSearchTermViewRequest request = GetSmartCampaignSearchTermViewRequest.newBuilder().setResourceName(resourceName).build(); return getSmartCampaignSearchTermView(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the attributes of the requested Smart campaign search term view. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() [HeaderError]() * [InternalError]() [QuotaError]() [RequestError]() * * <p>Sample code: * * <pre>{@code * try (SmartCampaignSearchTermViewServiceClient smartCampaignSearchTermViewServiceClient = * SmartCampaignSearchTermViewServiceClient.create()) { * GetSmartCampaignSearchTermViewRequest request = * GetSmartCampaignSearchTermViewRequest.newBuilder() * .setResourceName( * SmartCampaignSearchTermViewName.of("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[QUERY]") * .toString()) * .build(); * SmartCampaignSearchTermView response = * smartCampaignSearchTermViewServiceClient.getSmartCampaignSearchTermView(request); * } * }</pre> * * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ public final SmartCampaignSearchTermView getSmartCampaignSearchTermView( GetSmartCampaignSearchTermViewRequest request) { return getSmartCampaignSearchTermViewCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD. /** * Returns the attributes of the requested Smart campaign search term view. * * <p>List of thrown errors: [AuthenticationError]() [AuthorizationError]() [HeaderError]() * [InternalError]() [QuotaError]() [RequestError]() * * <p>Sample code: * * <pre>{@code * try (SmartCampaignSearchTermViewServiceClient smartCampaignSearchTermViewServiceClient = * SmartCampaignSearchTermViewServiceClient.create()) { * GetSmartCampaignSearchTermViewRequest request = * GetSmartCampaignSearchTermViewRequest.newBuilder() * .setResourceName( * SmartCampaignSearchTermViewName.of("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[QUERY]") * .toString()) * .build(); * ApiFuture<SmartCampaignSearchTermView> future = * smartCampaignSearchTermViewServiceClient * .getSmartCampaignSearchTermViewCallable() * .futureCall(request); * // Do something. * SmartCampaignSearchTermView response = future.get(); * } * }</pre> */ public final UnaryCallable<GetSmartCampaignSearchTermViewRequest, SmartCampaignSearchTermView> getSmartCampaignSearchTermViewCallable() { return stub.getSmartCampaignSearchTermViewCallable(); } @Override public final void close() { stub.close(); } @Override public void shutdown() { stub.shutdown(); } @Override public boolean isShutdown() { return stub.isShutdown(); } @Override public boolean isTerminated() { return stub.isTerminated(); } @Override public void shutdownNow() { stub.shutdownNow(); } @Override public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException { return stub.awaitTermination(duration, unit); } }
/* * Copyright 2012-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.jvm.java; import static com.facebook.buck.jvm.java.JavaCompilationConstants.DEFAULT_JAVAC_OPTIONS; import static org.easymock.EasyMock.createNiceMock; import static org.easymock.EasyMock.replay; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.facebook.buck.android.AndroidLibraryBuilder; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.io.filesystem.TestProjectFilesystems; import com.facebook.buck.jvm.core.HasClasspathEntries; import com.facebook.buck.jvm.core.HasJavaAbi; import com.facebook.buck.jvm.core.JavaLibrary; import com.facebook.buck.jvm.core.JavaPackageFinder; import com.facebook.buck.jvm.java.testutil.AbiCompilationModeTest; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.BuildTargetFactory; import com.facebook.buck.parser.exceptions.NoSuchBuildTargetException; import com.facebook.buck.rules.BuildContext; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.DefaultBuildTargetSourcePath; import com.facebook.buck.rules.DefaultSourcePathResolver; import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer; import com.facebook.buck.rules.FakeBuildContext; import com.facebook.buck.rules.FakeBuildableContext; import com.facebook.buck.rules.FakeSourcePath; import com.facebook.buck.rules.PathSourcePath; import com.facebook.buck.rules.RuleKey; import com.facebook.buck.rules.SingleThreadedBuildRuleResolver; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.SourcePathRuleFinder; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.rules.TargetNode; import com.facebook.buck.rules.TestBuildRuleParams; import com.facebook.buck.rules.TestCellBuilder; import com.facebook.buck.rules.keys.DefaultRuleKeyFactory; import com.facebook.buck.rules.keys.InputBasedRuleKeyFactory; import com.facebook.buck.rules.keys.TestDefaultRuleKeyFactory; import com.facebook.buck.rules.keys.TestInputBasedRuleKeyFactory; import com.facebook.buck.shell.ExportFileBuilder; import com.facebook.buck.shell.GenruleBuilder; import com.facebook.buck.step.ExecutionContext; import com.facebook.buck.step.Step; import com.facebook.buck.step.StepRunner; import com.facebook.buck.step.TestExecutionContext; import com.facebook.buck.testutil.AllExistingProjectFilesystem; import com.facebook.buck.testutil.FakeFileHashCache; import com.facebook.buck.testutil.FakeProjectFilesystem; import com.facebook.buck.testutil.MoreAsserts; import com.facebook.buck.testutil.TargetGraphFactory; import com.facebook.buck.util.Ansi; import com.facebook.buck.util.Console; import com.facebook.buck.util.HumanReadableException; import com.facebook.buck.util.RichStream; import com.facebook.buck.util.Verbosity; import com.facebook.buck.util.cache.FileHashCache; import com.facebook.buck.util.cache.FileHashCacheMode; import com.facebook.buck.util.cache.impl.StackedFileHashCache; import com.facebook.buck.util.zip.CustomJarOutputStream; import com.facebook.buck.util.zip.ZipOutputStreams; import com.google.common.base.Charsets; import com.google.common.base.Splitter; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.Ordering; import com.google.common.hash.Hashing; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.TreeSet; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class DefaultJavaLibraryTest extends AbiCompilationModeTest { private static final String ANNOTATION_SCENARIO_TARGET = "//android/java/src/com/facebook:fb"; @Rule public TemporaryFolder tmp = new TemporaryFolder(); private String annotationScenarioGenPath; private BuildRuleResolver ruleResolver; private JavaBuckConfig testJavaBuckConfig; @Before public void setUp() throws InterruptedException { ruleResolver = new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); testJavaBuckConfig = getJavaBuckConfigWithCompilationMode(); ProjectFilesystem filesystem = TestProjectFilesystems.createProjectFilesystem(tmp.getRoot().toPath()); StepRunner stepRunner = createNiceMock(StepRunner.class); JavaPackageFinder packageFinder = createNiceMock(JavaPackageFinder.class); replay(packageFinder, stepRunner); annotationScenarioGenPath = filesystem .resolve(filesystem.getBuckPaths().getAnnotationDir()) .resolve("android/java/src/com/facebook/__fb_gen__") .toAbsolutePath() .toString(); } /** Make sure that when isAndroidLibrary is true, that the Android bootclasspath is used. */ @Test @SuppressWarnings("PMD.AvoidUsingHardCodedIP") public void testBuildInternalWithAndroidBootclasspath() throws Exception { String folder = "android/java/src/com/facebook"; tmp.newFolder(folder.split("/")); BuildTarget buildTarget = BuildTargetFactory.newInstance("//" + folder + ":fb"); Path src = Paths.get(folder, "Main.java"); tmp.newFile(src.toString()); BuildRule libraryRule = AndroidLibraryBuilder.createBuilder(buildTarget).addSrc(src).build(ruleResolver); DefaultJavaLibrary javaLibrary = (DefaultJavaLibrary) libraryRule; BuildContext context = createBuildContext(); List<Step> steps = javaLibrary.getBuildSteps(context, new FakeBuildableContext()); // Find the JavacStep and verify its bootclasspath. Step step = Iterables.find(steps, command -> command instanceof JavacStep); assertNotNull("Expected a JavacStep in the steplist.", step); JavacStep javac = (JavacStep) step; assertEquals( "Should compile Main.java rather than generated R.java.", ImmutableSet.of(src), javac.getSrcs()); } @Test public void testJavaLibaryThrowsIfResourceIsDirectory() throws Exception { ProjectFilesystem filesystem = new AllExistingProjectFilesystem() { @Override public boolean isDirectory(Path path, LinkOption... linkOptionsk) { return true; } }; try { createJavaLibraryBuilder(BuildTargetFactory.newInstance("//library:code")) .addResource(FakeSourcePath.of("library")) .build(ruleResolver, filesystem); fail("An exception should have been thrown because a directory was passed as a resource."); } catch (HumanReadableException e) { assertTrue(e.getHumanReadableErrorMessage().contains("a directory is not a valid input")); } } /** Verify adding an annotation processor java binary. */ @Test public void testAddAnnotationProcessorJavaBinary() throws Exception { AnnotationProcessingScenario scenario = new AnnotationProcessingScenario(); scenario.addAnnotationProcessorTarget(validJavaBinary); scenario .getAnnotationProcessingParamsBuilder() .setLegacyAnnotationProcessorNames(ImmutableList.of("MyProcessor")); ImmutableList<String> parameters = scenario.buildAndGetCompileParameters(); MoreAsserts.assertContainsOne(parameters, "-processorpath"); MoreAsserts.assertContainsOne(parameters, "-processor"); assertHasProcessor(parameters, "MyProcessor"); MoreAsserts.assertContainsOne(parameters, "-s"); MoreAsserts.assertContainsOne(parameters, annotationScenarioGenPath); assertEquals( "Expected '-processor MyProcessor' parameters", parameters.indexOf("-processor") + 1, parameters.indexOf("MyProcessor")); assertEquals( "Expected '-s " + annotationScenarioGenPath + "' parameters", parameters.indexOf("-s") + 1, parameters.indexOf(annotationScenarioGenPath)); for (String parameter : parameters) { assertThat("Expected no custom annotation options.", parameter.startsWith("-A"), is(false)); } } /** Verify adding an annotation processor prebuilt jar. */ @Test public void testAddAnnotationProcessorPrebuiltJar() throws Exception { AnnotationProcessingScenario scenario = new AnnotationProcessingScenario(); scenario.addAnnotationProcessorTarget(validPrebuiltJar); scenario .getAnnotationProcessingParamsBuilder() .setLegacyAnnotationProcessorNames(ImmutableList.of("MyProcessor")); ImmutableList<String> parameters = scenario.buildAndGetCompileParameters(); MoreAsserts.assertContainsOne(parameters, "-processorpath"); MoreAsserts.assertContainsOne(parameters, "-processor"); assertHasProcessor(parameters, "MyProcessor"); MoreAsserts.assertContainsOne(parameters, "-s"); MoreAsserts.assertContainsOne(parameters, annotationScenarioGenPath); } /** Verify adding an annotation processor java library. */ @Test public void testAddAnnotationProcessorJavaLibrary() throws Exception { AnnotationProcessingScenario scenario = new AnnotationProcessingScenario(); scenario.addAnnotationProcessorTarget(validPrebuiltJar); scenario .getAnnotationProcessingParamsBuilder() .setLegacyAnnotationProcessorNames(ImmutableList.of("MyProcessor")); ImmutableList<String> parameters = scenario.buildAndGetCompileParameters(); MoreAsserts.assertContainsOne(parameters, "-processorpath"); MoreAsserts.assertContainsOne(parameters, "-processor"); assertHasProcessor(parameters, "MyProcessor"); MoreAsserts.assertContainsOne(parameters, "-s"); MoreAsserts.assertContainsOne(parameters, annotationScenarioGenPath); } /** Verify adding multiple annotation processors. */ @Test public void testAddAnnotationProcessorJar() throws Exception { AnnotationProcessingScenario scenario = new AnnotationProcessingScenario(); scenario.addAnnotationProcessorTarget(validPrebuiltJar); scenario.addAnnotationProcessorTarget(validJavaBinary); scenario.addAnnotationProcessorTarget(validJavaLibrary); scenario .getAnnotationProcessingParamsBuilder() .setLegacyAnnotationProcessorNames(ImmutableList.of("MyProcessor")); ImmutableList<String> parameters = scenario.buildAndGetCompileParameters(); MoreAsserts.assertContainsOne(parameters, "-processorpath"); MoreAsserts.assertContainsOne(parameters, "-processor"); assertHasProcessor(parameters, "MyProcessor"); MoreAsserts.assertContainsOne(parameters, "-s"); MoreAsserts.assertContainsOne(parameters, annotationScenarioGenPath); } @Test public void testGetClasspathEntriesMap() throws Exception { ProjectFilesystem filesystem = new FakeProjectFilesystem(); BuildTarget libraryOneTarget = BuildTargetFactory.newInstance("//:libone"); TargetNode<?, ?> libraryOne = createJavaLibraryBuilder(libraryOneTarget) .addSrc(Paths.get("java/src/com/libone/Bar.java")) .build(); BuildTarget libraryTwoTarget = BuildTargetFactory.newInstance("//:libtwo"); TargetNode<?, ?> libraryTwo = createJavaLibraryBuilder(libraryTwoTarget) .addSrc(Paths.get("java/src/com/libtwo/Foo.java")) .addDep(libraryOne.getBuildTarget()) .build(); BuildTarget parentTarget = BuildTargetFactory.newInstance("//:parent"); TargetNode<?, ?> parent = createJavaLibraryBuilder(parentTarget) .addSrc(Paths.get("java/src/com/parent/Meh.java")) .addDep(libraryTwo.getBuildTarget()) .build(); TargetGraph targetGraph = TargetGraphFactory.newInstance(libraryOne, libraryTwo, parent); ruleResolver = new SingleThreadedBuildRuleResolver( targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); JavaLibrary libraryOneRule = (JavaLibrary) ruleResolver.requireRule(libraryOneTarget); JavaLibrary parentRule = (JavaLibrary) ruleResolver.requireRule(parentTarget); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(ruleResolver)); Path root = libraryOneRule.getProjectFilesystem().getRootPath(); assertEquals( ImmutableSet.of( root.resolve(DefaultJavaLibrary.getOutputJarPath(libraryOneTarget, filesystem)), root.resolve(DefaultJavaLibrary.getOutputJarPath(libraryTwoTarget, filesystem)), root.resolve(DefaultJavaLibrary.getOutputJarPath(parentTarget, filesystem))), resolve(parentRule.getTransitiveClasspaths(), pathResolver)); } @Test public void testGetClasspathDeps() throws Exception { BuildTarget libraryOneTarget = BuildTargetFactory.newInstance("//:libone"); TargetNode<?, ?> libraryOne = createJavaLibraryBuilder(libraryOneTarget) .addSrc(Paths.get("java/src/com/libone/Bar.java")) .build(); BuildTarget libraryTwoTarget = BuildTargetFactory.newInstance("//:libtwo"); TargetNode<?, ?> libraryTwo = createJavaLibraryBuilder(libraryTwoTarget) .addSrc(Paths.get("java/src/com/libtwo/Foo.java")) .addDep(libraryOne.getBuildTarget()) .build(); BuildTarget parentTarget = BuildTargetFactory.newInstance("//:parent"); TargetNode<?, ?> parent = createJavaLibraryBuilder(parentTarget) .addSrc(Paths.get("java/src/com/parent/Meh.java")) .addDep(libraryTwo.getBuildTarget()) .build(); TargetGraph targetGraph = TargetGraphFactory.newInstance(libraryOne, libraryTwo, parent); ruleResolver = new SingleThreadedBuildRuleResolver( targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); BuildRule libraryOneRule = ruleResolver.requireRule(libraryOneTarget); BuildRule libraryTwoRule = ruleResolver.requireRule(libraryTwoTarget); BuildRule parentRule = ruleResolver.requireRule(parentTarget); assertThat( ((HasClasspathEntries) parentRule).getTransitiveClasspathDeps(), equalTo( ImmutableSet.of( getJavaLibrary(libraryOneRule), getJavaLibrary(libraryTwoRule), getJavaLibrary(parentRule)))); } @Test public void testClasspathForJavacCommand() throws Exception { BuildTarget libraryOneTarget = BuildTargetFactory.newInstance("//:libone"); TargetNode<?, ?> libraryOne = createJavaLibraryBuilder(libraryOneTarget) .addSrc(Paths.get("java/src/com/libone/Bar.java")) .build(); BuildTarget libraryTwoTarget = BuildTargetFactory.newInstance("//:libtwo"); TargetNode<?, ?> libraryTwo = createJavaLibraryBuilder(libraryTwoTarget) .addSrc(Paths.get("java/src/com/libtwo/Foo.java")) .addDep(libraryOne.getBuildTarget()) .build(); TargetGraph targetGraph = TargetGraphFactory.newInstance(libraryOne, libraryTwo); ruleResolver = new SingleThreadedBuildRuleResolver( targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); DefaultJavaLibrary libraryOneRule = (DefaultJavaLibrary) ruleResolver.requireRule(libraryOneTarget); DefaultJavaLibrary libraryTwoRule = (DefaultJavaLibrary) ruleResolver.requireRule(libraryTwoTarget); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(ruleResolver)); List<Step> steps = libraryTwoRule.getBuildSteps( FakeBuildContext.withSourcePathResolver(pathResolver), new FakeBuildableContext()); ImmutableList<JavacStep> javacSteps = FluentIterable.from(steps).filter(JavacStep.class).toList(); assertEquals("There should be only one javac step.", 1, javacSteps.size()); JavacStep javacStep = javacSteps.get(0); final BuildRule expectedRule; if (compileAgainstAbis.equals(TRUE)) { expectedRule = ruleResolver.getRule(libraryOneRule.getAbiJar().get()); } else { expectedRule = libraryOneRule; } String expectedName = expectedRule.getFullyQualifiedName(); assertEquals( "The classpath for the javac step to compile //:libtwo should contain only " + expectedName, ImmutableSet.of(pathResolver.getAbsolutePath(expectedRule.getSourcePathToOutput())), javacStep.getClasspathEntries()); } @Test public void testDepFilePredicateForNoAnnotationProcessorDeps() throws Exception { BuildTarget annotationProcessorTarget = validJavaLibrary.createTarget(); BuildTarget annotationProcessorAbiTarget = validJavaLibraryAbi.createTarget(); validJavaLibrary.createRule(annotationProcessorTarget); BuildRule annotationProcessorAbiRule = validJavaLibraryAbi.createRule(annotationProcessorAbiTarget); BuildTarget libraryTwoTarget = BuildTargetFactory.newInstance("//:libone"); DefaultJavaLibrary libraryTwo = createJavaLibraryBuilder(libraryTwoTarget) .addSrc(Paths.get("java/src/com/libtwo/Foo.java")) .addAnnotationProcessorDep(annotationProcessorTarget) .build(ruleResolver); SourcePath sourcePath = annotationProcessorAbiRule.getSourcePathToOutput(); assertFalse( "The predicate for dep file shouldn't contain annotation processor deps", libraryTwo .getCoveredByDepFilePredicate( DefaultSourcePathResolver.from(new SourcePathRuleFinder(ruleResolver))) .test(sourcePath)); } /** Verify adding an annotation processor java binary with options. */ @Test public void testAddAnnotationProcessorWithOptions() throws Exception { AnnotationProcessingScenario scenario = new AnnotationProcessingScenario(); scenario.addAnnotationProcessorTarget(validJavaBinary); scenario .getAnnotationProcessingParamsBuilder() .setLegacyAnnotationProcessorNames(ImmutableList.of("MyProcessor")); scenario.getAnnotationProcessingParamsBuilder().addParameters("MyParameter"); scenario.getAnnotationProcessingParamsBuilder().addParameters("MyKey=MyValue"); scenario.getAnnotationProcessingParamsBuilder().setProcessOnly(true); ImmutableList<String> parameters = scenario.buildAndGetCompileParameters(); MoreAsserts.assertContainsOne(parameters, "-processorpath"); MoreAsserts.assertContainsOne(parameters, "-processor"); assertHasProcessor(parameters, "MyProcessor"); MoreAsserts.assertContainsOne(parameters, "-s"); MoreAsserts.assertContainsOne(parameters, annotationScenarioGenPath); MoreAsserts.assertContainsOne(parameters, "-proc:only"); assertEquals( "Expected '-processor MyProcessor' parameters", parameters.indexOf("-processor") + 1, parameters.indexOf("MyProcessor")); assertEquals( "Expected '-s " + annotationScenarioGenPath + "' parameters", parameters.indexOf("-s") + 1, parameters.indexOf(annotationScenarioGenPath)); MoreAsserts.assertContainsOne(parameters, "-AMyParameter"); MoreAsserts.assertContainsOne(parameters, "-AMyKey=MyValue"); } private void assertHasProcessor(List<String> params, String processor) { int index = params.indexOf("-processor"); if (index >= params.size()) { fail(String.format("No processor argument found in %s.", params)); } Set<String> processors = ImmutableSet.copyOf(Splitter.on(',').split(params.get(index + 1))); if (!processors.contains(processor)) { fail(String.format("Annotation processor %s not found in %s.", processor, params)); } } @Test public void testBuildDeps() throws Exception { BuildTarget sourceDepExportFileTarget = BuildTargetFactory.newInstance("//:source_dep"); TargetNode<?, ?> sourceDepExportFileNode = new ExportFileBuilder(sourceDepExportFileTarget).build(); BuildTarget depExportFileTarget = BuildTargetFactory.newInstance("//:dep_file"); TargetNode<?, ?> depExportFileNode = new ExportFileBuilder(depExportFileTarget).build(); BuildTarget depLibraryExportedDepTarget = BuildTargetFactory.newInstance("//:dep_library_exported_dep"); TargetNode<?, ?> depLibraryExportedDepNode = createJavaLibraryBuilder(depLibraryExportedDepTarget) .addSrc(Paths.get("DepExportedDep.java")) .build(); BuildTarget depLibraryTarget = BuildTargetFactory.newInstance("//:dep_library"); TargetNode<?, ?> depLibraryNode = createJavaLibraryBuilder(depLibraryTarget) .addSrc(Paths.get("Dep.java")) .addExportedDep(depLibraryExportedDepTarget) .build(); BuildTarget depProvidedDepLibraryTarget = BuildTargetFactory.newInstance("//:dep_provided_dep_library"); TargetNode<?, ?> depProvidedDepLibraryNode = createJavaLibraryBuilder(depProvidedDepLibraryTarget) .addSrc(Paths.get("DepProvidedDep.java")) .build(); BuildTarget exportedDepLibraryExportedDepTarget = BuildTargetFactory.newInstance("//:exported_dep_library_exported_dep"); TargetNode<?, ?> exportedDepLibraryExportedDepNode = createJavaLibraryBuilder(exportedDepLibraryExportedDepTarget) .addSrc(Paths.get("ExportedDepExportedDep.java")) .build(); BuildTarget exportedDepLibraryTarget = BuildTargetFactory.newInstance("//:exported_dep_library"); TargetNode<?, ?> exportedDepLibraryNode = createJavaLibraryBuilder(exportedDepLibraryTarget) .addSrc(Paths.get("ExportedDep.java")) .addExportedDep(exportedDepLibraryExportedDepTarget) .build(); BuildTarget exportedProvidedDepLibraryTarget = BuildTargetFactory.newInstance("//:exported_provided_dep_library"); TargetNode<?, ?> exportedProvidedDepLibraryNode = createJavaLibraryBuilder(exportedProvidedDepLibraryTarget) .addSrc(Paths.get("ExportedProvidedDep.java")) .build(); BuildTarget providedDepLibraryExportedDepTarget = BuildTargetFactory.newInstance("//:provided_dep_library_exported_dep"); TargetNode<?, ?> providedDepLibraryExportedDepNode = createJavaLibraryBuilder(providedDepLibraryExportedDepTarget) .addSrc(Paths.get("ProvidedDepExportedDep.java")) .build(); BuildTarget providedDepLibraryTarget = BuildTargetFactory.newInstance("//:provided_dep_library"); TargetNode<?, ?> providedDepLibraryNode = createJavaLibraryBuilder(providedDepLibraryTarget) .addSrc(Paths.get("ProvidedDep.java")) .addExportedDep(providedDepLibraryExportedDepTarget) .build(); BuildTarget resourceDepPrebuiltJarTarget = BuildTargetFactory.newInstance("//:resource_dep"); TargetNode<?, ?> resourceDepPrebuiltJarNode = PrebuiltJarBuilder.createBuilder(resourceDepPrebuiltJarTarget) .setBinaryJar(Paths.get("binary.jar")) .build(); BuildTarget libraryTarget = BuildTargetFactory.newInstance("//:lib"); TargetNode<?, ?> libraryNode = createJavaLibraryBuilder(libraryTarget) .addSrc(DefaultBuildTargetSourcePath.of(sourceDepExportFileTarget)) .addDep(depLibraryTarget) .addDep(depExportFileTarget) .addDep(depProvidedDepLibraryTarget) .addExportedDep(exportedDepLibraryTarget) .addExportedDep(exportedProvidedDepLibraryTarget) .addProvidedDep(providedDepLibraryTarget) .addProvidedDep(exportedProvidedDepLibraryTarget) .addProvidedDep(depProvidedDepLibraryTarget) .addResource(DefaultBuildTargetSourcePath.of(resourceDepPrebuiltJarTarget)) .build(); TargetGraph targetGraph = TargetGraphFactory.newInstance( libraryNode, sourceDepExportFileNode, depExportFileNode, depLibraryNode, depProvidedDepLibraryNode, depLibraryExportedDepNode, exportedDepLibraryNode, exportedProvidedDepLibraryNode, exportedDepLibraryExportedDepNode, providedDepLibraryNode, providedDepLibraryExportedDepNode, resourceDepPrebuiltJarNode); ruleResolver = new SingleThreadedBuildRuleResolver( targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); DefaultJavaLibrary library = (DefaultJavaLibrary) ruleResolver.requireRule(libraryTarget); Set<BuildRule> expectedDeps = new TreeSet<>(); addAbiAndMaybeFullJar(depLibraryTarget, expectedDeps); addAbiAndMaybeFullJar(depProvidedDepLibraryTarget, expectedDeps); expectedDeps.add(ruleResolver.getRule(depExportFileTarget)); addAbiAndMaybeFullJar(depLibraryExportedDepTarget, expectedDeps); addAbiAndMaybeFullJar(providedDepLibraryTarget, expectedDeps); addAbiAndMaybeFullJar(providedDepLibraryExportedDepTarget, expectedDeps); addAbiAndMaybeFullJar(exportedDepLibraryTarget, expectedDeps); addAbiAndMaybeFullJar(exportedProvidedDepLibraryTarget, expectedDeps); addAbiAndMaybeFullJar(exportedDepLibraryExportedDepTarget, expectedDeps); expectedDeps.add(ruleResolver.getRule(sourceDepExportFileTarget)); expectedDeps.add(ruleResolver.getRule(resourceDepPrebuiltJarTarget)); assertThat("Build deps mismatch!", library.getBuildDeps(), equalTo(expectedDeps)); assertThat( library.getExportedDeps(), equalTo( ImmutableSortedSet.of( ruleResolver.getRule(exportedDepLibraryTarget), ruleResolver.getRule(exportedProvidedDepLibraryTarget)))); assertThat( library.getDepsForTransitiveClasspathEntries(), equalTo( ImmutableSet.of( ruleResolver.getRule(depLibraryTarget), ruleResolver.getRule(depProvidedDepLibraryTarget), ruleResolver.getRule(exportedProvidedDepLibraryTarget), ruleResolver.getRule(depExportFileTarget), ruleResolver.getRule(exportedDepLibraryTarget)))); // In Java packageables, exported_dep overrides dep overrides provided_dep. In android // packageables, they are complementary (i.e. one can export provided deps by simply putting // the dep in both lists). This difference is probably accidental, but it's now depended upon // by at least a couple projects. assertThat( ImmutableSet.copyOf(library.getRequiredPackageables()), equalTo( ImmutableSet.of( ruleResolver.getRule(depLibraryTarget), ruleResolver.getRule(exportedDepLibraryTarget)))); } private void addAbiAndMaybeFullJar(BuildTarget target, Set<BuildRule> set) { BuildRule fullJar = ruleResolver.getRule(target); BuildRule abiJar = ruleResolver.requireRule(((HasJavaAbi) fullJar).getAbiJar().get()); set.add(abiJar); if (compileAgainstAbis.equals(FALSE)) { set.add(fullJar); } } @Test public void testExportedDeps() throws Exception { ProjectFilesystem filesystem = new FakeProjectFilesystem(); BuildTarget nonIncludedTarget = BuildTargetFactory.newInstance("//:not_included"); TargetNode<?, ?> notIncludedNode = createJavaLibraryBuilder(nonIncludedTarget) .addSrc(Paths.get("java/src/com/not_included/Raz.java")) .build(); BuildTarget includedTarget = BuildTargetFactory.newInstance("//:included"); TargetNode<?, ?> includedNode = createJavaLibraryBuilder(includedTarget) .addSrc(Paths.get("java/src/com/included/Rofl.java")) .build(); BuildTarget libraryOneTarget = BuildTargetFactory.newInstance("//:libone"); TargetNode<?, ?> libraryOneNode = createJavaLibraryBuilder(libraryOneTarget) .addDep(notIncludedNode.getBuildTarget()) .addDep(includedNode.getBuildTarget()) .addExportedDep(includedNode.getBuildTarget()) .addSrc(Paths.get("java/src/com/libone/Bar.java")) .build(); BuildTarget libraryTwoTarget = BuildTargetFactory.newInstance("//:libtwo"); TargetNode<?, ?> libraryTwoNode = createJavaLibraryBuilder(libraryTwoTarget) .addSrc(Paths.get("java/src/com/libtwo/Foo.java")) .addDep(libraryOneNode.getBuildTarget()) .addExportedDep(libraryOneNode.getBuildTarget()) .build(); BuildTarget parentTarget = BuildTargetFactory.newInstance("//:parent"); TargetNode<?, ?> parentNode = createJavaLibraryBuilder(parentTarget) .addSrc(Paths.get("java/src/com/parent/Meh.java")) .addDep(libraryTwoNode.getBuildTarget()) .build(); TargetGraph targetGraph = TargetGraphFactory.newInstance( notIncludedNode, includedNode, libraryOneNode, libraryTwoNode, parentNode); ruleResolver = new SingleThreadedBuildRuleResolver( targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(ruleResolver)); BuildRule notIncluded = ruleResolver.requireRule(notIncludedNode.getBuildTarget()); BuildRule included = ruleResolver.requireRule(includedNode.getBuildTarget()); BuildRule libraryOne = ruleResolver.requireRule(libraryOneTarget); BuildRule libraryTwo = ruleResolver.requireRule(libraryTwoTarget); BuildRule parent = ruleResolver.requireRule(parentTarget); Path root = parent.getProjectFilesystem().getRootPath(); assertEquals( "A java_library that depends on //:libone should include only libone.jar in its " + "classpath when compiling itself.", ImmutableSet.of( root.resolve(DefaultJavaLibrary.getOutputJarPath(nonIncludedTarget, filesystem))), resolve(getJavaLibrary(notIncluded).getOutputClasspaths(), pathResolver)); assertEquals( ImmutableSet.of( root.resolve(DefaultJavaLibrary.getOutputJarPath(includedTarget, filesystem))), resolve(getJavaLibrary(included).getOutputClasspaths(), pathResolver)); assertEquals( ImmutableSet.of( root.resolve(DefaultJavaLibrary.getOutputJarPath(includedTarget, filesystem)), root.resolve(DefaultJavaLibrary.getOutputJarPath(libraryOneTarget, filesystem)), root.resolve(DefaultJavaLibrary.getOutputJarPath(includedTarget, filesystem))), resolve(getJavaLibrary(libraryOne).getOutputClasspaths(), pathResolver)); assertEquals( "//:libtwo exports its deps, so a java_library that depends on //:libtwo should include " + "both libone.jar and libtwo.jar in its classpath when compiling itself.", ImmutableSet.of( root.resolve(DefaultJavaLibrary.getOutputJarPath(libraryOneTarget, filesystem)), root.resolve(DefaultJavaLibrary.getOutputJarPath(includedTarget, filesystem)), root.resolve(DefaultJavaLibrary.getOutputJarPath(libraryOneTarget, filesystem)), root.resolve(DefaultJavaLibrary.getOutputJarPath(libraryTwoTarget, filesystem)), root.resolve(DefaultJavaLibrary.getOutputJarPath(includedTarget, filesystem))), resolve(getJavaLibrary(libraryTwo).getOutputClasspaths(), pathResolver)); assertEquals( "A java_binary that depends on //:parent should include libone.jar, libtwo.jar and " + "parent.jar.", ImmutableSet.<Path>builder() .add( root.resolve(DefaultJavaLibrary.getOutputJarPath(includedTarget, filesystem)), root.resolve(DefaultJavaLibrary.getOutputJarPath(nonIncludedTarget, filesystem)), root.resolve(DefaultJavaLibrary.getOutputJarPath(libraryOneTarget, filesystem)), root.resolve(DefaultJavaLibrary.getOutputJarPath(libraryTwoTarget, filesystem)), root.resolve(DefaultJavaLibrary.getOutputJarPath(parentTarget, filesystem))) .build(), resolve(getJavaLibrary(parent).getTransitiveClasspaths(), pathResolver)); assertThat( getJavaLibrary(parent).getTransitiveClasspathDeps(), equalTo( ImmutableSet.<JavaLibrary>builder() .add(getJavaLibrary(included)) .add(getJavaLibrary(notIncluded)) .add(getJavaLibrary(libraryOne)) .add(getJavaLibrary(libraryTwo)) .add(getJavaLibrary(parent)) .build())); assertEquals( "A java_library that depends on //:parent should include only parent.jar in its " + "-classpath when compiling itself.", ImmutableSet.of( root.resolve(DefaultJavaLibrary.getOutputJarPath(parentTarget, filesystem))), resolve(getJavaLibrary(parent).getOutputClasspaths(), pathResolver)); } /** * Tests that an error is thrown when non-java library rules are listed in the exported deps * parameter. */ @Test public void testExportedDepsShouldOnlyContainJavaLibraryRules() throws Exception { BuildTarget genruleBuildTarget = BuildTargetFactory.newInstance("//generated:stuff"); BuildRule genrule = GenruleBuilder.newGenruleBuilder(genruleBuildTarget) .setBash("echo 'aha' > $OUT") .setOut("stuff.txt") .build(ruleResolver); BuildTarget buildTarget = BuildTargetFactory.newInstance("//:lib"); try { createDefaultJavaLibraryRuleWithAbiKey( buildTarget, /* srcs */ ImmutableSortedSet.of("foo/Bar.java"), /* deps */ ImmutableSortedSet.of(), /* exportedDeps */ ImmutableSortedSet.of(genrule), /* spoolMode */ Optional.empty(), /* postprocessClassesCommands */ ImmutableList.of()); fail("A non-java library listed as exported dep should have thrown."); } catch (HumanReadableException e) { String expected = buildTarget + ": exported dep " + genruleBuildTarget + " (" + genrule.getType() + ") " + "must be a type of java library."; assertEquals(expected, e.getMessage()); } } @Test public void testStepsPresenceForForDirectJarSpooling() throws NoSuchBuildTargetException { BuildTarget buildTarget = BuildTargetFactory.newInstance("//:lib"); DefaultJavaLibrary javaLibraryBuildRule = createDefaultJavaLibraryRuleWithAbiKey( buildTarget, /* srcs */ ImmutableSortedSet.of("foo/Bar.java"), /* deps */ ImmutableSortedSet.of(), /* exportedDeps */ ImmutableSortedSet.of(), Optional.of(AbstractJavacOptions.SpoolMode.DIRECT_TO_JAR), /* postprocessClassesCommands */ ImmutableList.of()); BuildContext buildContext = createBuildContext(); ImmutableList<Step> steps = javaLibraryBuildRule.getBuildSteps(buildContext, new FakeBuildableContext()); assertThat(steps, Matchers.hasItem(Matchers.instanceOf(JavacStep.class))); assertThat(steps, Matchers.not(Matchers.hasItem(Matchers.instanceOf(JarDirectoryStep.class)))); } @Test public void testJavacDirectToJarStepIsNotPresentWhenPostprocessClassesCommandsPresent() throws NoSuchBuildTargetException { BuildTarget buildTarget = BuildTargetFactory.newInstance("//:lib"); DefaultJavaLibrary javaLibraryBuildRule = createDefaultJavaLibraryRuleWithAbiKey( buildTarget, /* srcs */ ImmutableSortedSet.of("foo/Bar.java"), /* deps */ ImmutableSortedSet.of(), /* exportedDeps */ ImmutableSortedSet.of(), Optional.of(AbstractJavacOptions.SpoolMode.DIRECT_TO_JAR), /* postprocessClassesCommands */ ImmutableList.of("process_class_files.py")); BuildContext buildContext = createBuildContext(); ImmutableList<Step> steps = javaLibraryBuildRule.getBuildSteps(buildContext, new FakeBuildableContext()); assertThat(steps, Matchers.hasItem(Matchers.instanceOf(JavacStep.class))); assertThat(steps, Matchers.hasItem(Matchers.instanceOf(JarDirectoryStep.class))); } @Test public void testStepsPresenceForIntermediateOutputToDiskSpooling() throws NoSuchBuildTargetException { BuildTarget buildTarget = BuildTargetFactory.newInstance("//:lib"); DefaultJavaLibrary javaLibraryBuildRule = createDefaultJavaLibraryRuleWithAbiKey( buildTarget, /* srcs */ ImmutableSortedSet.of("foo/Bar.java"), /* deps */ ImmutableSortedSet.of(), /* exportedDeps */ ImmutableSortedSet.of(), Optional.of(AbstractJavacOptions.SpoolMode.INTERMEDIATE_TO_DISK), /* postprocessClassesCommands */ ImmutableList.of()); BuildContext buildContext = createBuildContext(); ImmutableList<Step> steps = javaLibraryBuildRule.getBuildSteps(buildContext, new FakeBuildableContext()); assertThat(steps, Matchers.hasItem(Matchers.instanceOf(JavacStep.class))); assertThat(steps, Matchers.hasItem(Matchers.instanceOf(JarDirectoryStep.class))); } /** Tests that input-based rule keys work properly with generated sources. */ @Test public void testInputBasedRuleKeySourceChange() throws Exception { ProjectFilesystem filesystem = new FakeProjectFilesystem(); SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(ruleResolver); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder); // Setup a Java library consuming a source generated by a genrule and grab its rule key. BuildRule genSrc = GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:gen_srcs")) .setOut("Test.java") .setCmd("something") .build(ruleResolver, filesystem); filesystem.writeContentsToPath( "class Test {}", pathResolver.getRelativePath(genSrc.getSourcePathToOutput())); JavaLibrary library = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//:lib")) .addSrc(genSrc.getSourcePathToOutput()) .build(ruleResolver, filesystem); FileHashCache originalHashCache = StackedFileHashCache.createDefaultHashCaches(filesystem, FileHashCacheMode.DEFAULT); InputBasedRuleKeyFactory factory = new TestInputBasedRuleKeyFactory(originalHashCache, pathResolver, ruleFinder); RuleKey originalRuleKey = factory.build(library); // Now change the genrule such that its rule key changes, but it's output stays the same (since // we don't change it). This should *not* affect the input-based rule key of the consuming // java library, since it only cares about the contents of the source. ruleResolver = new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); genSrc = GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:gen_srcs")) .setOut("Test.java") .setCmd("something else") .build(ruleResolver, filesystem); library = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//:lib")) .addSrc(genSrc.getSourcePathToOutput()) .build(ruleResolver, filesystem); FileHashCache unaffectedHashCache = StackedFileHashCache.createDefaultHashCaches(filesystem, FileHashCacheMode.DEFAULT); factory = new TestInputBasedRuleKeyFactory(unaffectedHashCache, pathResolver, ruleFinder); RuleKey unaffectedRuleKey = factory.build(library); assertThat(originalRuleKey, equalTo(unaffectedRuleKey)); // Now actually modify the source, which should make the input-based rule key change. ruleResolver = new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); genSrc = GenruleBuilder.newGenruleBuilder(BuildTargetFactory.newInstance("//:gen_srcs")) .setOut("Test.java") .setCmd("something else") .build(ruleResolver, filesystem); filesystem.writeContentsToPath( "class Test2 {}", pathResolver.getRelativePath(genSrc.getSourcePathToOutput())); library = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//:lib")) .addSrc(genSrc.getSourcePathToOutput()) .build(ruleResolver, filesystem); FileHashCache affectedHashCache = StackedFileHashCache.createDefaultHashCaches(filesystem, FileHashCacheMode.DEFAULT); factory = new TestInputBasedRuleKeyFactory(affectedHashCache, pathResolver, ruleFinder); RuleKey affectedRuleKey = factory.build(library); assertThat(originalRuleKey, Matchers.not(equalTo(affectedRuleKey))); } /** Tests that input-based rule keys work properly with simple Java library deps. */ @Test public void testInputBasedRuleKeyWithJavaLibraryDep() throws Exception { ProjectFilesystem filesystem = new FakeProjectFilesystem(); // Setup a Java library which builds against another Java library dep. TargetNode<JavaLibraryDescriptionArg, ?> depNode = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//:dep"), filesystem) .addSrc(Paths.get("Source.java")) .build(); TargetNode<?, ?> libraryNode = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//:lib"), filesystem) .addDep(depNode.getBuildTarget()) .build(); TargetGraph targetGraph = TargetGraphFactory.newInstance(depNode, libraryNode); ruleResolver = new SingleThreadedBuildRuleResolver( targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(ruleResolver); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder); JavaLibrary dep = (JavaLibrary) ruleResolver.requireRule(depNode.getBuildTarget()); JavaLibrary library = (JavaLibrary) ruleResolver.requireRule(libraryNode.getBuildTarget()); filesystem.writeContentsToPath( "JAR contents", pathResolver.getRelativePath(dep.getSourcePathToOutput())); writeAbiJar( filesystem, pathResolver.getRelativePath( ruleResolver.requireRule(dep.getAbiJar().get()).getSourcePathToOutput()), "Source.class", "ABI JAR contents"); FileHashCache originalHashCache = StackedFileHashCache.createDefaultHashCaches(filesystem, FileHashCacheMode.DEFAULT); InputBasedRuleKeyFactory factory = new TestInputBasedRuleKeyFactory(originalHashCache, pathResolver, ruleFinder); RuleKey originalRuleKey = factory.build(library); // Now change the Java library dependency such that its rule key changes, and change its JAR // contents, but keep its ABI JAR the same. This should *not* affect the input-based rule key // of the consuming java library, since it only cares about the contents of the ABI JAR. depNode = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//:dep")) .addSrc(Paths.get("Source.java")) .setResourcesRoot(Paths.get("some root that changes the rule key")) .build(); targetGraph = TargetGraphFactory.newInstance(depNode, libraryNode); ruleResolver = new SingleThreadedBuildRuleResolver( targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); ruleFinder = new SourcePathRuleFinder(ruleResolver); pathResolver = DefaultSourcePathResolver.from(ruleFinder); dep = (JavaLibrary) ruleResolver.requireRule(depNode.getBuildTarget()); library = (JavaLibrary) ruleResolver.requireRule(libraryNode.getBuildTarget()); filesystem.writeContentsToPath( "different JAR contents", pathResolver.getRelativePath(dep.getSourcePathToOutput())); FileHashCache unaffectedHashCache = StackedFileHashCache.createDefaultHashCaches(filesystem, FileHashCacheMode.DEFAULT); factory = new TestInputBasedRuleKeyFactory(unaffectedHashCache, pathResolver, ruleFinder); RuleKey unaffectedRuleKey = factory.build(library); assertThat(originalRuleKey, equalTo(unaffectedRuleKey)); // Now actually change the Java library dependency's ABI JAR. This *should* affect the // input-based rule key of the consuming java library. ruleResolver = new SingleThreadedBuildRuleResolver( targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); ruleFinder = new SourcePathRuleFinder(ruleResolver); pathResolver = DefaultSourcePathResolver.from(ruleFinder); dep = (JavaLibrary) ruleResolver.requireRule(depNode.getBuildTarget()); library = (JavaLibrary) ruleResolver.requireRule(libraryNode.getBuildTarget()); writeAbiJar( filesystem, pathResolver.getRelativePath( ruleResolver.requireRule(dep.getAbiJar().get()).getSourcePathToOutput()), "Source.class", "changed ABI JAR contents"); FileHashCache affectedHashCache = StackedFileHashCache.createDefaultHashCaches(filesystem, FileHashCacheMode.DEFAULT); factory = new TestInputBasedRuleKeyFactory(affectedHashCache, pathResolver, ruleFinder); RuleKey affectedRuleKey = factory.build(library); assertThat(originalRuleKey, Matchers.not(equalTo(affectedRuleKey))); } /** * Tests that input-based rule keys work properly with a Java library dep exported by a * first-order dep. */ @Test public void testInputBasedRuleKeyWithExportedDeps() throws Exception { ProjectFilesystem filesystem = new FakeProjectFilesystem(); // Setup a Java library which builds against another Java library dep exporting another Java // library dep. TargetNode<JavaLibraryDescriptionArg, ?> exportedDepNode = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//:edep"), filesystem) .addSrc(Paths.get("Source1.java")) .build(); TargetNode<?, ?> depNode = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//:dep"), filesystem) .addExportedDep(exportedDepNode.getBuildTarget()) .build(); TargetNode<?, ?> libraryNode = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//:lib"), filesystem) .addDep(depNode.getBuildTarget()) .build(); TargetGraph targetGraph = TargetGraphFactory.newInstance(exportedDepNode, depNode, libraryNode); ruleResolver = new SingleThreadedBuildRuleResolver( targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(ruleResolver); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder); JavaLibrary exportedDep = (JavaLibrary) ruleResolver.requireRule(BuildTargetFactory.newInstance("//:edep")); JavaLibrary library = (JavaLibrary) ruleResolver.requireRule(BuildTargetFactory.newInstance("//:lib")); filesystem.writeContentsToPath( "JAR contents", pathResolver.getRelativePath(exportedDep.getSourcePathToOutput())); writeAbiJar( filesystem, pathResolver.getRelativePath( ruleResolver.requireRule(exportedDep.getAbiJar().get()).getSourcePathToOutput()), "Source1.class", "ABI JAR contents"); FileHashCache originalHashCache = StackedFileHashCache.createDefaultHashCaches(filesystem, FileHashCacheMode.DEFAULT); InputBasedRuleKeyFactory factory = new TestInputBasedRuleKeyFactory(originalHashCache, pathResolver, ruleFinder); RuleKey originalRuleKey = factory.build(library); // Now change the exported Java library dependency such that its rule key changes, and change // its JAR contents, but keep its ABI JAR the same. This should *not* affect the input-based // rule key of the consuming java library, since it only cares about the contents of the ABI // JAR. exportedDepNode = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//:edep"), filesystem) .addSrc(Paths.get("Source1.java")) .setResourcesRoot(Paths.get("some root that changes the rule key")) .build(); targetGraph = TargetGraphFactory.newInstance(exportedDepNode, depNode, libraryNode); ruleResolver = new SingleThreadedBuildRuleResolver( targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); ruleFinder = new SourcePathRuleFinder(ruleResolver); pathResolver = DefaultSourcePathResolver.from(ruleFinder); exportedDep = (JavaLibrary) ruleResolver.requireRule(BuildTargetFactory.newInstance("//:edep")); library = (JavaLibrary) ruleResolver.requireRule(BuildTargetFactory.newInstance("//:lib")); filesystem.writeContentsToPath( "different JAR contents", pathResolver.getRelativePath(exportedDep.getSourcePathToOutput())); FileHashCache unaffectedHashCache = StackedFileHashCache.createDefaultHashCaches(filesystem, FileHashCacheMode.DEFAULT); factory = new TestInputBasedRuleKeyFactory(unaffectedHashCache, pathResolver, ruleFinder); RuleKey unaffectedRuleKey = factory.build(library); assertThat(originalRuleKey, equalTo(unaffectedRuleKey)); // Now actually change the exproted Java library dependency's ABI JAR. This *should* affect // the input-based rule key of the consuming java library. ruleResolver = new SingleThreadedBuildRuleResolver( targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); ruleFinder = new SourcePathRuleFinder(ruleResolver); pathResolver = DefaultSourcePathResolver.from(ruleFinder); exportedDep = (JavaLibrary) ruleResolver.requireRule(BuildTargetFactory.newInstance("//:edep")); library = (JavaLibrary) ruleResolver.requireRule(BuildTargetFactory.newInstance("//:lib")); writeAbiJar( filesystem, pathResolver.getRelativePath( ruleResolver.requireRule(exportedDep.getAbiJar().get()).getSourcePathToOutput()), "Source1.class", "changed ABI JAR contents"); FileHashCache affectedHashCache = StackedFileHashCache.createDefaultHashCaches(filesystem, FileHashCacheMode.DEFAULT); factory = new TestInputBasedRuleKeyFactory(affectedHashCache, pathResolver, ruleFinder); RuleKey affectedRuleKey = factory.build(library); assertThat(originalRuleKey, Matchers.not(equalTo(affectedRuleKey))); } /** * Tests that input-based rule keys work properly with a Java library dep exported through * multiple Java library dependencies. */ @Test public void testInputBasedRuleKeyWithRecursiveExportedDeps() throws Exception { ProjectFilesystem filesystem = new FakeProjectFilesystem(); // Setup a Java library which builds against another Java library dep exporting another Java // library dep. TargetNode<JavaLibraryDescriptionArg, ?> exportedDepNode = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//:edep"), filesystem) .addSrc(Paths.get("Source1.java")) .build(); TargetNode<?, ?> dep2Node = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//:dep2"), filesystem) .addExportedDep(exportedDepNode.getBuildTarget()) .build(); TargetNode<?, ?> dep1Node = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//:dep1"), filesystem) .addExportedDep(dep2Node.getBuildTarget()) .build(); TargetNode<?, ?> libraryNode = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//:lib"), filesystem) .addDep(dep1Node.getBuildTarget()) .build(); TargetGraph targetGraph = TargetGraphFactory.newInstance(exportedDepNode, dep2Node, dep1Node, libraryNode); ruleResolver = new SingleThreadedBuildRuleResolver( targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(ruleResolver); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder); JavaLibrary exportedDep = (JavaLibrary) ruleResolver.requireRule(BuildTargetFactory.newInstance("//:edep")); JavaLibrary library = (JavaLibrary) ruleResolver.requireRule(BuildTargetFactory.newInstance("//:lib")); filesystem.writeContentsToPath( "JAR contents", pathResolver.getRelativePath(exportedDep.getSourcePathToOutput())); writeAbiJar( filesystem, pathResolver.getRelativePath( ruleResolver.requireRule(exportedDep.getAbiJar().get()).getSourcePathToOutput()), "Source1.class", "ABI JAR contents"); FileHashCache originalHashCache = StackedFileHashCache.createDefaultHashCaches(filesystem, FileHashCacheMode.DEFAULT); InputBasedRuleKeyFactory factory = new TestInputBasedRuleKeyFactory(originalHashCache, pathResolver, ruleFinder); RuleKey originalRuleKey = factory.build(library); // Now change the exported Java library dependency such that its rule key changes, and change // its JAR contents, but keep its ABI JAR the same. This should *not* affect the input-based // rule key of the consuming java library, since it only cares about the contents of the ABI // JAR. exportedDepNode = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//:edep"), filesystem) .addSrc(Paths.get("Source1.java")) .setResourcesRoot(Paths.get("some root that changes the rule key")) .build(); targetGraph = TargetGraphFactory.newInstance(exportedDepNode, dep2Node, dep1Node, libraryNode); ruleResolver = new SingleThreadedBuildRuleResolver( targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); ruleFinder = new SourcePathRuleFinder(ruleResolver); pathResolver = DefaultSourcePathResolver.from(ruleFinder); exportedDep = (JavaLibrary) ruleResolver.requireRule(BuildTargetFactory.newInstance("//:edep")); library = (JavaLibrary) ruleResolver.requireRule(BuildTargetFactory.newInstance("//:lib")); filesystem.writeContentsToPath( "different JAR contents", pathResolver.getRelativePath(exportedDep.getSourcePathToOutput())); FileHashCache unaffectedHashCache = StackedFileHashCache.createDefaultHashCaches(filesystem, FileHashCacheMode.DEFAULT); factory = new TestInputBasedRuleKeyFactory(unaffectedHashCache, pathResolver, ruleFinder); RuleKey unaffectedRuleKey = factory.build(library); assertThat(originalRuleKey, equalTo(unaffectedRuleKey)); // Now actually change the exproted Java library dependency's ABI JAR. This *should* affect // the input-based rule key of the consuming java library. ruleResolver = new SingleThreadedBuildRuleResolver( targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); ruleFinder = new SourcePathRuleFinder(ruleResolver); pathResolver = DefaultSourcePathResolver.from(ruleFinder); exportedDep = (JavaLibrary) ruleResolver.requireRule(BuildTargetFactory.newInstance("//:edep")); library = (JavaLibrary) ruleResolver.requireRule(BuildTargetFactory.newInstance("//:lib")); writeAbiJar( filesystem, pathResolver.getRelativePath( ruleResolver.requireRule(exportedDep.getAbiJar().get()).getSourcePathToOutput()), "Source1.class", "changed ABI JAR contents"); FileHashCache affectedHashCache = StackedFileHashCache.createDefaultHashCaches(filesystem, FileHashCacheMode.DEFAULT); factory = new TestInputBasedRuleKeyFactory(affectedHashCache, pathResolver, ruleFinder); RuleKey affectedRuleKey = factory.build(library); assertThat(originalRuleKey, Matchers.not(equalTo(affectedRuleKey))); } private DefaultJavaLibrary createDefaultJavaLibraryRuleWithAbiKey( BuildTarget buildTarget, ImmutableSet<String> srcs, ImmutableSortedSet<BuildRule> deps, ImmutableSortedSet<BuildRule> exportedDeps, Optional<AbstractJavacOptions.SpoolMode> spoolMode, ImmutableList<String> postprocessClassesCommands) throws NoSuchBuildTargetException { ProjectFilesystem projectFilesystem = new FakeProjectFilesystem(); ImmutableSortedSet<SourcePath> srcsAsPaths = FluentIterable.from(srcs) .transform(Paths::get) .transform(p -> (SourcePath) PathSourcePath.of(projectFilesystem, p)) .toSortedSet(Ordering.natural()); BuildRuleParams buildRuleParams = TestBuildRuleParams.create().withDeclaredDeps(ImmutableSortedSet.copyOf(deps)); JavacOptions javacOptions = spoolMode.isPresent() ? JavacOptions.builder(DEFAULT_JAVAC_OPTIONS).setSpoolMode(spoolMode.get()).build() : DEFAULT_JAVAC_OPTIONS; JavaLibraryDeps.Builder depsBuilder = new JavaLibraryDeps.Builder(ruleResolver); exportedDeps .stream() .peek(ruleResolver::addToIndex) .map(BuildRule::getBuildTarget) .forEach(depsBuilder::addExportedDepTargets); ProjectFilesystem filesystem = new FakeProjectFilesystem(); DefaultJavaLibrary defaultJavaLibrary = DefaultJavaLibrary.rulesBuilder( buildTarget, filesystem, buildRuleParams, ruleResolver, TestCellBuilder.createCellRoots(filesystem), new JavaConfiguredCompilerFactory(testJavaBuckConfig), testJavaBuckConfig, null) .setJavacOptions(javacOptions) .setSrcs(srcsAsPaths) .setPostprocessClassesCommands(postprocessClassesCommands) .setDeps(depsBuilder.build()) .build() .buildLibrary(); ruleResolver.addToIndex(defaultJavaLibrary); return defaultJavaLibrary; } @Test public void testRuleKeyIsOrderInsensitiveForSourcesAndResources() throws Exception { // Note that these filenames were deliberately chosen to have identical hashes to maximize // the chance of order-sensitivity when being inserted into a HashMap. Just using // {foo,bar}.{java,txt} resulted in a passing test even for the old broken code. ProjectFilesystem filesystem = new AllExistingProjectFilesystem() { @Override public boolean isDirectory(Path path, LinkOption... linkOptionsk) { return false; } }; BuildRuleResolver resolver1 = new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); SourcePathRuleFinder ruleFinder1 = new SourcePathRuleFinder(resolver1); SourcePathResolver pathResolver1 = DefaultSourcePathResolver.from(ruleFinder1); DefaultJavaLibrary rule1 = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//lib:lib")) .addSrc(Paths.get("agifhbkjdec.java")) .addSrc(Paths.get("bdeafhkgcji.java")) .addSrc(Paths.get("bdehgaifjkc.java")) .addSrc(Paths.get("cfiabkjehgd.java")) .addResource(FakeSourcePath.of("becgkaifhjd.txt")) .addResource(FakeSourcePath.of("bkhajdifcge.txt")) .addResource(FakeSourcePath.of("cabfghjekid.txt")) .addResource(FakeSourcePath.of("chkdbafijge.txt")) .build(resolver1, filesystem); BuildRuleResolver resolver2 = new SingleThreadedBuildRuleResolver( TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()); SourcePathRuleFinder ruleFinder2 = new SourcePathRuleFinder(resolver2); SourcePathResolver pathResolver2 = DefaultSourcePathResolver.from(ruleFinder2); DefaultJavaLibrary rule2 = createJavaLibraryBuilder(BuildTargetFactory.newInstance("//lib:lib")) .addSrc(Paths.get("cfiabkjehgd.java")) .addSrc(Paths.get("bdehgaifjkc.java")) .addSrc(Paths.get("bdeafhkgcji.java")) .addSrc(Paths.get("agifhbkjdec.java")) .addResource(FakeSourcePath.of("chkdbafijge.txt")) .addResource(FakeSourcePath.of("cabfghjekid.txt")) .addResource(FakeSourcePath.of("bkhajdifcge.txt")) .addResource(FakeSourcePath.of("becgkaifhjd.txt")) .build(resolver2, filesystem); ImmutableMap.Builder<String, String> fileHashes = ImmutableMap.builder(); for (String filename : ImmutableList.of( "agifhbkjdec.java", "bdeafhkgcji.java", "bdehgaifjkc.java", "cfiabkjehgd.java", "becgkaifhjd.txt", "bkhajdifcge.txt", "cabfghjekid.txt", "chkdbafijge.txt")) { fileHashes.put(filename, Hashing.sha1().hashString(filename, Charsets.UTF_8).toString()); } DefaultRuleKeyFactory ruleKeyFactory = new TestDefaultRuleKeyFactory( FakeFileHashCache.createFromStrings(fileHashes.build()), pathResolver1, ruleFinder1); DefaultRuleKeyFactory ruleKeyFactory2 = new TestDefaultRuleKeyFactory( FakeFileHashCache.createFromStrings(fileHashes.build()), pathResolver2, ruleFinder2); RuleKey key1 = ruleKeyFactory.build(rule1); RuleKey key2 = ruleKeyFactory2.build(rule2); assertEquals(key1, key2); } @Test public void testWhenNoJavacIsProvidedAJavacInMemoryStepIsAdded() throws Exception { BuildTarget libraryOneTarget = BuildTargetFactory.newInstance("//:libone"); BuildRule rule = createJavaLibraryBuilder(libraryOneTarget) .addSrc(Paths.get("java/src/com/libone/Bar.java")) .build(ruleResolver); DefaultJavaLibrary buildRule = (DefaultJavaLibrary) rule; ImmutableList<Step> steps = buildRule.getBuildSteps( FakeBuildContext.withSourcePathResolver( DefaultSourcePathResolver.from(new SourcePathRuleFinder(ruleResolver))), new FakeBuildableContext()); assertEquals(12, steps.size()); assertTrue(((JavacStep) steps.get(8)).getJavac() instanceof Jsr199Javac); } @Test public void testWhenJavacJarIsProvidedAJavacInMemoryStepIsAdded() throws Exception { BuildTarget libraryOneTarget = BuildTargetFactory.newInstance("//:libone"); BuildTarget javacTarget = BuildTargetFactory.newInstance("//langtools:javac"); TargetNode<?, ?> javacNode = PrebuiltJarBuilder.createBuilder(javacTarget) .setBinaryJar(Paths.get("java/src/com/libone/JavacJar.jar")) .build(); TargetNode<?, ?> ruleNode = createJavaLibraryBuilder(libraryOneTarget) .addSrc(Paths.get("java/src/com/libone/Bar.java")) .setCompiler(DefaultBuildTargetSourcePath.of(javacTarget)) .build(); TargetGraph targetGraph = TargetGraphFactory.newInstance(javacNode, ruleNode); ruleResolver = new SingleThreadedBuildRuleResolver( targetGraph, new DefaultTargetNodeToBuildRuleTransformer()); SourcePathResolver pathResolver = DefaultSourcePathResolver.from(new SourcePathRuleFinder(ruleResolver)); BuildRule javac = ruleResolver.requireRule(javacTarget); BuildRule rule = ruleResolver.requireRule(libraryOneTarget); DefaultJavaLibrary buildable = (DefaultJavaLibrary) rule; ImmutableList<Step> steps = buildable.getBuildSteps( FakeBuildContext.withSourcePathResolver( DefaultSourcePathResolver.from(new SourcePathRuleFinder(ruleResolver))), new FakeBuildableContext()); assertEquals(12, steps.size()); Javac javacStep = ((JavacStep) steps.get(8)).getJavac(); assertTrue(javacStep instanceof Jsr199Javac); JarBackedJavac jsrJavac = ((JarBackedJavac) javacStep); assertEquals( RichStream.from(jsrJavac.getCompilerClassPath()) .map(pathResolver::getRelativePath) .collect(ImmutableSet.toImmutableSet()), ImmutableSet.of(pathResolver.getRelativePath(javac.getSourcePathToOutput()))); } // Utilities private JavaLibrary getJavaLibrary(BuildRule rule) { return (JavaLibrary) rule; } private JavaLibraryBuilder createJavaLibraryBuilder(BuildTarget target) { return JavaLibraryBuilder.createBuilder(target, testJavaBuckConfig); } private JavaLibraryBuilder createJavaLibraryBuilder( BuildTarget target, ProjectFilesystem projectFilesystem) { return JavaLibraryBuilder.createBuilder(target, testJavaBuckConfig, projectFilesystem); } private void writeAbiJar( ProjectFilesystem filesystem, Path abiJarPath, String fileName, String fileContents) throws IOException { try (CustomJarOutputStream jar = ZipOutputStreams.newJarOutputStream(filesystem.newFileOutputStream(abiJarPath))) { jar.setEntryHashingEnabled(true); jar.writeEntry( fileName, new ByteArrayInputStream(fileContents.getBytes(StandardCharsets.UTF_8))); } } // test. private BuildContext createBuildContext() { return FakeBuildContext.withSourcePathResolver( DefaultSourcePathResolver.from(new SourcePathRuleFinder(ruleResolver))); } private abstract static class AnnotationProcessorTarget { private final String targetName; private AnnotationProcessorTarget(String targetName) { this.targetName = targetName; } public BuildTarget createTarget() { return BuildTargetFactory.newInstance(targetName); } public abstract BuildRule createRule(BuildTarget target) throws NoSuchBuildTargetException; } private AnnotationProcessorTarget validPrebuiltJar = new AnnotationProcessorTarget("//tools/java/src/com/facebook/library:prebuilt-processors") { @Override public BuildRule createRule(BuildTarget target) throws NoSuchBuildTargetException { return PrebuiltJarBuilder.createBuilder(target) .setBinaryJar(Paths.get("MyJar")) .build(ruleResolver); } }; private AnnotationProcessorTarget validJavaBinary = new AnnotationProcessorTarget("//tools/java/src/com/facebook/annotations:custom-processors") { @Override public BuildRule createRule(BuildTarget target) throws NoSuchBuildTargetException { return new JavaBinaryRuleBuilder(target) .setMainClass("com.facebook.Main") .build(ruleResolver); } }; private AnnotationProcessorTarget validJavaLibrary = new AnnotationProcessorTarget("//tools/java/src/com/facebook/somejava:library") { @Override public BuildRule createRule(BuildTarget target) throws NoSuchBuildTargetException { return JavaLibraryBuilder.createBuilder(target, testJavaBuckConfig) .addSrc(Paths.get("MyClass.java")) .setProguardConfig(FakeSourcePath.of("MyProguardConfig")) .build(ruleResolver); } }; private AnnotationProcessorTarget validJavaLibraryAbi = new AnnotationProcessorTarget("//tools/java/src/com/facebook/somejava:library#class-abi") { @Override public BuildRule createRule(BuildTarget target) throws NoSuchBuildTargetException { return CalculateClassAbi.of( target, new SourcePathRuleFinder(ruleResolver), new FakeProjectFilesystem(), TestBuildRuleParams.create(), FakeSourcePath.of("java/src/com/facebook/somejava/library/library-abi.jar")); } }; // Captures all the common code between the different annotation processing test scenarios. private class AnnotationProcessingScenario { private final AnnotationProcessingParams.Builder annotationProcessingParamsBuilder; public AnnotationProcessingScenario() throws IOException { annotationProcessingParamsBuilder = AnnotationProcessingParams.builder() .setLegacySafeAnnotationProcessors(Collections.emptySet()); } public AnnotationProcessingParams.Builder getAnnotationProcessingParamsBuilder() { return annotationProcessingParamsBuilder; } public void addAnnotationProcessorTarget(AnnotationProcessorTarget processor) throws NoSuchBuildTargetException { BuildTarget target = processor.createTarget(); BuildRule rule = processor.createRule(target); annotationProcessingParamsBuilder.addLegacyAnnotationProcessorDeps(rule); } public ImmutableList<String> buildAndGetCompileParameters() throws InterruptedException, IOException, NoSuchBuildTargetException { ProjectFilesystem projectFilesystem = TestProjectFilesystems.createProjectFilesystem(tmp.getRoot().toPath()); DefaultJavaLibrary javaLibrary = createJavaLibraryRule(projectFilesystem); BuildContext buildContext = createBuildContext(); List<Step> steps = javaLibrary.getBuildSteps(buildContext, new FakeBuildableContext()); JavacStep javacCommand = lastJavacCommand(steps); ExecutionContext executionContext = TestExecutionContext.newBuilder() .setConsole(new Console(Verbosity.SILENT, System.out, System.err, Ansi.withoutTty())) .setDebugEnabled(true) .build(); ImmutableList<String> options = javacCommand.getOptions( executionContext, /* buildClasspathEntries */ ImmutableSortedSet.of()); return options; } private DefaultJavaLibrary createJavaLibraryRule(ProjectFilesystem projectFilesystem) throws IOException, NoSuchBuildTargetException { BuildTarget buildTarget = BuildTargetFactory.newInstance(ANNOTATION_SCENARIO_TARGET); annotationProcessingParamsBuilder.setProjectFilesystem(projectFilesystem); tmp.newFolder("android", "java", "src", "com", "facebook"); String src = "android/java/src/com/facebook/Main.java"; tmp.newFile(src); AnnotationProcessingParams params = annotationProcessingParamsBuilder.build(); JavacOptions options = JavacOptions.builder(DEFAULT_JAVAC_OPTIONS).setAnnotationProcessingParams(params).build(); BuildRuleParams buildRuleParams = TestBuildRuleParams.create(); DefaultJavaLibrary javaLibrary = DefaultJavaLibrary.rulesBuilder( buildTarget, projectFilesystem, buildRuleParams, ruleResolver, TestCellBuilder.createCellRoots(projectFilesystem), new JavaConfiguredCompilerFactory(testJavaBuckConfig), testJavaBuckConfig, null) .setJavacOptions(options) .setSrcs(ImmutableSortedSet.of(FakeSourcePath.of(src))) .setResources(ImmutableSortedSet.of()) .setDeps(new JavaLibraryDeps.Builder(ruleResolver).build()) .setProguardConfig(Optional.empty()) .setPostprocessClassesCommands(ImmutableList.of()) .setResourcesRoot(Optional.empty()) .setManifestFile(Optional.empty()) .setMavenCoords(Optional.empty()) .setTests(ImmutableSortedSet.of()) .build() .buildLibrary(); ruleResolver.addToIndex(javaLibrary); return javaLibrary; } private JavacStep lastJavacCommand(Iterable<Step> commands) { Step javac = null; for (Step step : commands) { if (step instanceof JavacStep) { javac = step; // Intentionally no break here, since we want the last one. } } assertNotNull("Expected a JavacStep in step list", javac); return (JavacStep) javac; } } private static ImmutableSet<Path> resolve( ImmutableSet<SourcePath> paths, SourcePathResolver resolver) { return paths.stream().map(resolver::getAbsolutePath).collect(ImmutableSet.toImmutableSet()); } }
/* * Copyright (C) 2014 Jan Seibert (jan.seibert@geo.uzh.ch) and * Marc Vis (marc.vis@geo.uzh.ch) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package plugins; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import whitebox.geospatialfiles.WhiteboxRaster; import whitebox.geospatialfiles.WhiteboxRasterBase; import whitebox.interfaces.WhiteboxPlugin; import whitebox.interfaces.WhiteboxPluginHost; /** * This tool computes for each stream cell the median value of the upslope areas of all cells that are located upstream (McGlynn et al., 2003). * @author Dr. John Lindsay email: jlindsay@uoguelph.ca */ public class MedianUpstreamArea implements WhiteboxPlugin { private WhiteboxPluginHost myHost = null; private String[] args; WhiteboxRaster dem; WhiteboxRaster upslopeAreaCreek; WhiteboxRaster medianUpstreamArea; WhiteboxRaster tmpDirectUpstreamCreekCellCount; double gridRes = 1; int[] xd = new int[]{0, -1, -1, -1, 0, 1, 1, 1}; int[] yd = new int[]{-1, -1, 0, 1, 1, 1, 0, -1}; double[] dd = new double[]{1, Math.sqrt(2), 1, Math.sqrt(2), 1, Math.sqrt(2), 1, Math.sqrt(2)}; private class StreamFlow implements Comparable<StreamFlow> { private int mFromX; private int mFromY; private int mToX; private int mToY; private double mToElevation; public StreamFlow(int fromX, int fromY, int toX, int toY, double toElevation) { mFromX = fromX; mFromY = fromY; mToX = toX; mToY = toY; mToElevation = toElevation; } public int GetFromX() { return mFromX; } public int GetFromY() { return mFromY; } public int GetToX() { return mToX; } public int GetToY() { return mToY; } public double GetToElevation() { return mToElevation; } @Override public int compareTo(StreamFlow o) { double diff = this.GetToElevation() - o.GetToElevation(); if (diff > 0) { return 1; } else if (diff < 0) { return -1; } else { return 0; } } } /** * Used to retrieve the plugin tool's name. This is a short, unique name containing no spaces. * @return String containing plugin name. */ @Override public String getName() { return "MedianUpstreamArea"; } /** * Used to retrieve the plugin tool's descriptive name. This can be a longer name (containing spaces) and is used in the interface to list the tool. * @return String containing the plugin descriptive name. */ @Override public String getDescriptiveName() { return "Median Upstream Area"; } /** * Used to retrieve a short description of what the plugin tool does. * @return String containing the plugin's description. */ @Override public String getToolDescription() { return "Computes the Median Upstream Area."; } /** * Used to identify which toolboxes this plugin tool should be listed in. * @return Array of Strings. */ @Override public String[] getToolbox() { String[] ret = { "RelativeLandscapePosition" }; return ret; } /** * Sets the WhiteboxPluginHost to which the plugin tool is tied. This is the class * that the plugin will send all feedback messages, progress updates, and return objects. * @param host The WhiteboxPluginHost that called the plugin tool. */ @Override public void setPluginHost(WhiteboxPluginHost host) { myHost = host; } /** * Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface. * @param feedback String containing the text to display. */ private void showFeedback(String message) { if (myHost != null) { myHost.showFeedback(message); } else { System.out.println(message); } } /** * Used to communicate a return object from a plugin tool to the main Whitebox user-interface. * @return Object, such as an output WhiteboxRaster. */ private void returnData(Object ret) { if (myHost != null) { myHost.returnData(ret); } } private int previousProgress = 0; private String previousProgressLabel = ""; /** * Used to communicate a progress update between a plugin tool and the main Whitebox user interface. * @param progressLabel A String to use for the progress label. * @param progress Float containing the progress value (between 0 and 100). */ private void updateProgress(String progressLabel, int progress) { if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) { myHost.updateProgress(progressLabel, progress); } previousProgress = progress; previousProgressLabel = progressLabel; } /** * Used to communicate a progress update between a plugin tool and the main Whitebox user interface. * @param progress Float containing the progress value (between 0 and 100). */ private void updateProgress(int progress) { if (myHost != null && progress != previousProgress) { myHost.updateProgress(progress); } previousProgress = progress; } /** * Sets the arguments (parameters) used by the plugin. * @param args An array of string arguments. */ @Override public void setArgs(String[] args) { this.args = args.clone(); } private boolean cancelOp = false; /** * Used to communicate a cancel operation from the Whitebox GUI. * @param cancel Set to true if the plugin should be canceled. */ @Override public void setCancelOp(boolean cancel) { cancelOp = cancel; } private void cancelOperation() { showFeedback("Operation cancelled."); updateProgress("Progress: ", 0); } private boolean amIActive = false; /** * Used by the Whitebox GUI to tell if this plugin is still running. * @return a boolean describing whether or not the plugin is actively being used. */ @Override public boolean isActive() { return amIActive; } /** * Used to execute this plugin tool. */ @Override public void run() { amIActive = true; String demHeader = null; String upslopeAreaCreekHeader = null; String outputHeader = null; int numRows; int numCols; double elevation, elevationNeighbour; int x, y; double slope, maxSlope; int flowDir; int i; List<StreamFlow> streamFlowList = new ArrayList<>(); List<StreamFlow> copyStreamFlowList; StreamFlow streamFlow2; List<Double> upstreamValues = new ArrayList<>(); float progress = 0; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } for (i = 0; i < args.length; i++) { if (i == 0) { demHeader = args[i]; } else if (i == 1) { upslopeAreaCreekHeader = args[i]; } else if (i == 2) { outputHeader = args[i]; } } // check to see that the inputHeader and outputHeader are not null. if ((demHeader == null) || (upslopeAreaCreekHeader == null) || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { dem = new WhiteboxRaster(demHeader, "r"); upslopeAreaCreek = new WhiteboxRaster(upslopeAreaCreekHeader, "r"); numRows = dem.getNumberRows(); numCols = dem.getNumberColumns(); gridRes = dem.getCellSizeX(); medianUpstreamArea = new WhiteboxRaster(outputHeader, "rw", demHeader, WhiteboxRaster.DataType.FLOAT, 0); medianUpstreamArea.setPreferredPalette("blueyellow.pal"); medianUpstreamArea.setDataScale(WhiteboxRasterBase.DataScale.CONTINUOUS); medianUpstreamArea.setZUnits("dimensionless"); tmpDirectUpstreamCreekCellCount = new WhiteboxRaster(outputHeader.replace(".dep", "_tmp1.dep"), "rw", demHeader, WhiteboxRaster.DataType.FLOAT, 0); tmpDirectUpstreamCreekCellCount.isTemporaryFile = true; // Initialize output grid values updateProgress("Loop 1 of 3:", 0); for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { if (upslopeAreaCreek.getValue(row, col) == upslopeAreaCreek.getNoDataValue()) { medianUpstreamArea.setValue(row, col, upslopeAreaCreek.getNoDataValue()); } } if (cancelOp) { cancelOperation(); return; } progress = (float) (100f * row / (numRows - 1)); updateProgress("Loop 1 of 3:", (int) progress); } // Create a list of StreamFlow objecten updateProgress("Loop 2 of 3:", 0); for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { // Initialize maxSlope = Double.MIN_VALUE; flowDir = -1; if (upslopeAreaCreek.getValue(row, col) > 0) { // If the cell is a creekcell elevation = dem.getValue(row, col); for (int c = 0; c < 8; c++){ // For each of the neighbouring cells x = col + xd[c]; y = row + yd[c]; elevationNeighbour = dem.getValue(y, x); if (upslopeAreaCreek.getValue(y, x) > 0 && elevationNeighbour < elevation) { // If the neighbour cell is a creekcell with a lower elevation slope = (elevation - elevationNeighbour) / dd[c]; if (slope > maxSlope) { // If the slope is larger then the max slope found so far maxSlope = slope; flowDir = c; } } } for (int c = 0; c < 8; c++){ // For each of the neighbouring cells if (c == flowDir) { // If it's the cell with the max slope x = col + xd[c]; y = row + yd[c]; tmpDirectUpstreamCreekCellCount.incrementValue(y, x, 1); streamFlowList.add(new StreamFlow(col, row, x, y, elevation)); // Add a new StreamFlow object to the list } } } } if (cancelOp) { cancelOperation(); return; } progress = (float) (100f * row / (numRows - 1)); updateProgress("Loop 2 of 3:", (int) progress); } // Order the StreamFlow objects (based on their elevation) streamFlowList = OrderStreamFlowList(streamFlowList); // Create a copy of the streamFlowList copyStreamFlowList = new ArrayList<>(streamFlowList.subList(0, streamFlowList.size())); // Loop through the streamFlowList updateProgress("Loop 3 of 3:", 0); for (StreamFlow streamFlow : streamFlowList) { i = streamFlowList.indexOf(streamFlow); // Only if the cell hasn't been computed yet and its value is not nothing if (medianUpstreamArea.getValue(streamFlow.GetToY(), streamFlow.GetToX()) == 0) { // Initialize list with upstream values upstreamValues = new ArrayList<>(); // Remove all StreamFlow objects with a lower elevation then that of the current StreamFlow (for performance reasons) FilterStreamFlowList(copyStreamFlowList, streamFlow); // Make a list with all upstream values MakeUpstreamList(copyStreamFlowList, streamFlow.GetToX(), streamFlow.GetToY(), upstreamValues); // Sort the upstream values Collections.sort(upstreamValues); // Get the median of the upstream values and apply that value to the MedianUpstreamArea output grid medianUpstreamArea.setValue(streamFlow.GetToY(), streamFlow.GetToX(), GetMedian(upstreamValues)); streamFlow2 = streamFlow; // If the current cell is receiving water from 1 cell AND there are more than 2 values in the 'upstreamValues' list (i.e. the previous cell in the stream is NOT the start of the creek (=> this situation is handled later on in an if-statement)) while ((tmpDirectUpstreamCreekCellCount.getValue(streamFlow2.GetToY(), streamFlow2.GetToX()) == 1) & (upstreamValues.size() > 2)) { // Remove the value of the current cell from the 'upstreamValues' list upstreamValues.remove(upslopeAreaCreek.getValue(streamFlow2.GetToY(), streamFlow2.GetToX())); // Compute the MedianUpstreamArea for the current 'from cell' medianUpstreamArea.setValue(streamFlow2.GetFromY(), streamFlow2.GetFromX(), GetMedian(upstreamValues)); x = streamFlow2.GetFromX(); y = streamFlow2.GetFromY(); // Find the streamFlow item whose water is flowing into the current 'from cell' for (StreamFlow tempStreamFlow : copyStreamFlowList) { if (tempStreamFlow.GetToX() == x && tempStreamFlow.GetToY() == y) { streamFlow2 = tempStreamFlow; break; } } } // If the cell from which water is flowing into the current cell is a starting point of the creek... if (tmpDirectUpstreamCreekCellCount.getValue(streamFlow2.GetFromY(), streamFlow2.GetFromX()) == 0) { x = streamFlow2.GetFromX(); y = streamFlow2.GetFromY(); medianUpstreamArea.setValue(y, x, upslopeAreaCreek.getValue(y, x)); } } if (cancelOp) { cancelOperation(); return; } progress = (float) (100f * (i + 1) / streamFlowList.size()); updateProgress("Loop 3 of 3:", (int) progress); } medianUpstreamArea.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); medianUpstreamArea.addMetadataEntry("Created on " + new Date()); dem.close(); upslopeAreaCreek.close(); medianUpstreamArea.close(); tmpDirectUpstreamCreekCellCount.close(); // returning a header file string displays the image. returnData(outputHeader); } catch (Exception e) { showFeedback(e.getMessage()); } finally { updateProgress("Progress: ", 0); // tells the main application that this process is completed. amIActive = false; myHost.pluginComplete(); } } private List<StreamFlow> OrderStreamFlowList(List<StreamFlow> streamFlowList) { // Orders the streamFlowList based on the elevation values Collections.sort(streamFlowList); return streamFlowList; } private void FilterStreamFlowList(List<StreamFlow> streamFlowList, StreamFlow streamFlow) { int index; index = streamFlowList.indexOf(streamFlow); streamFlowList.subList(0, index).clear(); } private void MakeUpstreamList(List<StreamFlow> streamFlowList, int x, int y, List<Double> upstreamValues) { // Recursive function which returns a list of cell values positioned upstream relative to (x,y) int counter = 0; int upstreamCellCount = (int)tmpDirectUpstreamCreekCellCount.getValue(y, x); upstreamValues.add(upslopeAreaCreek.getValue(y, x)); for (StreamFlow streamFlow : streamFlowList) { if (x == streamFlow.GetToX() & y == streamFlow.GetToY()) { counter = counter + 1; MakeUpstreamList(streamFlowList, streamFlow.GetFromX(), streamFlow.GetFromY(), upstreamValues); if (counter == upstreamCellCount) { break; } } } } /** * Used to return the median of the values in the list. */ public Double GetMedian(List<Double> values) { // Returns the median of the values in the list int count = values.size(); double median; double m1; double m2; if ((count % 2) == 1) { median = values.get((int)(count / 2)); } else if (count > 0) { m1 = values.get(count / 2); m2 = values.get((count / 2) - 1); median = (m1 + m2) / 2; } else { median = 0; } return median; } }
package net.dirtyfilthy.bouncycastle.crypto.macs; import net.dirtyfilthy.bouncycastle.crypto.BlockCipher; import net.dirtyfilthy.bouncycastle.crypto.CipherParameters; import net.dirtyfilthy.bouncycastle.crypto.DataLengthException; import net.dirtyfilthy.bouncycastle.crypto.Mac; import net.dirtyfilthy.bouncycastle.crypto.paddings.BlockCipherPadding; import net.dirtyfilthy.bouncycastle.crypto.params.ParametersWithIV; /** * implements a Cipher-FeedBack (CFB) mode on top of a simple cipher. */ class MacCFBBlockCipher { private byte[] IV; private byte[] cfbV; private byte[] cfbOutV; private int blockSize; private BlockCipher cipher = null; /** * Basic constructor. * * @param cipher the block cipher to be used as the basis of the * feedback mode. * @param blockSize the block size in bits (note: a multiple of 8) */ public MacCFBBlockCipher( BlockCipher cipher, int bitBlockSize) { this.cipher = cipher; this.blockSize = bitBlockSize / 8; this.IV = new byte[cipher.getBlockSize()]; this.cfbV = new byte[cipher.getBlockSize()]; this.cfbOutV = new byte[cipher.getBlockSize()]; } /** * Initialise the cipher and, possibly, the initialisation vector (IV). * If an IV isn't passed as part of the parameter, the IV will be all zeros. * An IV which is too short is handled in FIPS compliant fashion. * * @param param the key and other data required by the cipher. * @exception IllegalArgumentException if the params argument is * inappropriate. */ public void init( CipherParameters params) throws IllegalArgumentException { if (params instanceof ParametersWithIV) { ParametersWithIV ivParam = (ParametersWithIV)params; byte[] iv = ivParam.getIV(); if (iv.length < IV.length) { System.arraycopy(iv, 0, IV, IV.length - iv.length, iv.length); } else { System.arraycopy(iv, 0, IV, 0, IV.length); } reset(); cipher.init(true, ivParam.getParameters()); } else { reset(); cipher.init(true, params); } } /** * return the algorithm name and mode. * * @return the name of the underlying algorithm followed by "/CFB" * and the block size in bits. */ public String getAlgorithmName() { return cipher.getAlgorithmName() + "/CFB" + (blockSize * 8); } /** * return the block size we are operating at. * * @return the block size we are operating at (in bytes). */ public int getBlockSize() { return blockSize; } /** * Process one block of input from the array in and write it to * the out array. * * @param in the array containing the input data. * @param inOff offset into the in array the data starts at. * @param out the array the output data will be copied into. * @param outOff the offset into the out array the output will start at. * @exception DataLengthException if there isn't enough data in in, or * space in out. * @exception IllegalStateException if the cipher isn't initialised. * @return the number of bytes processed and produced. */ public int processBlock( byte[] in, int inOff, byte[] out, int outOff) throws DataLengthException, IllegalStateException { if ((inOff + blockSize) > in.length) { throw new DataLengthException("input buffer too short"); } if ((outOff + blockSize) > out.length) { throw new DataLengthException("output buffer too short"); } cipher.processBlock(cfbV, 0, cfbOutV, 0); // // XOR the cfbV with the plaintext producing the cipher text // for (int i = 0; i < blockSize; i++) { out[outOff + i] = (byte)(cfbOutV[i] ^ in[inOff + i]); } // // change over the input block. // System.arraycopy(cfbV, blockSize, cfbV, 0, cfbV.length - blockSize); System.arraycopy(out, outOff, cfbV, cfbV.length - blockSize, blockSize); return blockSize; } /** * reset the chaining vector back to the IV and reset the underlying * cipher. */ public void reset() { System.arraycopy(IV, 0, cfbV, 0, IV.length); cipher.reset(); } void getMacBlock( byte[] mac) { cipher.processBlock(cfbV, 0, mac, 0); } } public class CFBBlockCipherMac implements Mac { private byte[] mac; private byte[] buf; private int bufOff; private MacCFBBlockCipher cipher; private BlockCipherPadding padding = null; private int macSize; /** * create a standard MAC based on a CFB block cipher. This will produce an * authentication code half the length of the block size of the cipher, with * the CFB mode set to 8 bits. * * @param cipher the cipher to be used as the basis of the MAC generation. */ public CFBBlockCipherMac( BlockCipher cipher) { this(cipher, 8, (cipher.getBlockSize() * 8) / 2, null); } /** * create a standard MAC based on a CFB block cipher. This will produce an * authentication code half the length of the block size of the cipher, with * the CFB mode set to 8 bits. * * @param cipher the cipher to be used as the basis of the MAC generation. * @param padding the padding to be used. */ public CFBBlockCipherMac( BlockCipher cipher, BlockCipherPadding padding) { this(cipher, 8, (cipher.getBlockSize() * 8) / 2, padding); } /** * create a standard MAC based on a block cipher with the size of the * MAC been given in bits. This class uses CFB mode as the basis for the * MAC generation. * <p> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * * @param cipher the cipher to be used as the basis of the MAC generation. * @param cfbBitSize the size of an output block produced by the CFB mode. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. */ public CFBBlockCipherMac( BlockCipher cipher, int cfbBitSize, int macSizeInBits) { this(cipher, cfbBitSize, macSizeInBits, null); } /** * create a standard MAC based on a block cipher with the size of the * MAC been given in bits. This class uses CFB mode as the basis for the * MAC generation. * <p> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * * @param cipher the cipher to be used as the basis of the MAC generation. * @param cfbBitSize the size of an output block produced by the CFB mode. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8. * @param padding a padding to be used. */ public CFBBlockCipherMac( BlockCipher cipher, int cfbBitSize, int macSizeInBits, BlockCipherPadding padding) { if ((macSizeInBits % 8) != 0) { throw new IllegalArgumentException("MAC size must be multiple of 8"); } mac = new byte[cipher.getBlockSize()]; this.cipher = new MacCFBBlockCipher(cipher, cfbBitSize); this.padding = padding; this.macSize = macSizeInBits / 8; buf = new byte[this.cipher.getBlockSize()]; bufOff = 0; } public String getAlgorithmName() { return cipher.getAlgorithmName(); } public void init( CipherParameters params) { reset(); cipher.init(params); } public int getMacSize() { return macSize; } public void update( byte in) { if (bufOff == buf.length) { cipher.processBlock(buf, 0, mac, 0); bufOff = 0; } buf[bufOff++] = in; } public void update( byte[] in, int inOff, int len) { if (len < 0) { throw new IllegalArgumentException("Can't have a negative input length!"); } int blockSize = cipher.getBlockSize(); int resultLen = 0; int gapLen = blockSize - bufOff; if (len > gapLen) { System.arraycopy(in, inOff, buf, bufOff, gapLen); resultLen += cipher.processBlock(buf, 0, mac, 0); bufOff = 0; len -= gapLen; inOff += gapLen; while (len > blockSize) { resultLen += cipher.processBlock(in, inOff, mac, 0); len -= blockSize; inOff += blockSize; } } System.arraycopy(in, inOff, buf, bufOff, len); bufOff += len; } public int doFinal( byte[] out, int outOff) { int blockSize = cipher.getBlockSize(); // // pad with zeroes // if (this.padding == null) { while (bufOff < blockSize) { buf[bufOff] = 0; bufOff++; } } else { padding.addPadding(buf, bufOff); } cipher.processBlock(buf, 0, mac, 0); cipher.getMacBlock(mac); System.arraycopy(mac, 0, out, outOff, macSize); reset(); return macSize; } /** * Reset the mac generator. */ public void reset() { /* * clean the buffer. */ for (int i = 0; i < buf.length; i++) { buf[i] = 0; } bufOff = 0; /* * reset the underlying cipher. */ cipher.reset(); } }
package org.apache.hadoop.raid; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.EOFException; import java.io.IOException; import java.net.Socket; import java.util.Comparator; import java.util.Random; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.DFSClient; import org.apache.hadoop.hdfs.protocol.DataTransferProtocol; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.FSConstants; import org.apache.hadoop.hdfs.protocol.FSConstants.DatanodeReportType; import org.apache.hadoop.hdfs.protocol.LocatedBlock; import org.apache.hadoop.hdfs.server.common.HdfsConstants; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.Text; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.net.NetworkTopology; class BlockMover { public static final Log LOG = LogFactory.getLog(BlockMover.class); final private BlockingQueue<Runnable> movingQueue; final private int maxQueueSize; final private RaidNodeMetrics metrics; final private boolean simulate; final private Random rand; final private Configuration conf; final private int alwaysSubmitPriorityLevel; final ClusterInfo cluster; final Thread clusterUpdater; ExecutorService executor; BlockMover(int numMovingThreads, int maxQueueSize, boolean simulate, int alwaysSubmitPriorityLevel, Configuration conf) { this.movingQueue = new PriorityBlockingQueue<Runnable>( 1000, new BlockMoveActionComparator()); this.executor = new ThreadPoolExecutor(numMovingThreads, numMovingThreads, 0L, TimeUnit.MILLISECONDS, movingQueue); this.maxQueueSize = maxQueueSize; this.metrics = RaidNodeMetrics.getInstance(); this.cluster = new ClusterInfo(); this.clusterUpdater = new Thread(cluster); this.simulate = simulate; this.rand = new Random(); this.conf = conf; this.alwaysSubmitPriorityLevel = alwaysSubmitPriorityLevel; } public void start() { clusterUpdater.setDaemon(true); clusterUpdater.start(); } public void stop() { cluster.stop(); clusterUpdater.interrupt(); executor.shutdown(); } public int getQueueSize() { return movingQueue.size(); } public void move(LocatedBlock block, DatanodeInfo node, Set<DatanodeInfo> excludedNodes, int priority) { BlockMoveAction action = new BlockMoveAction( block, node, excludedNodes, priority); LOG.debug("Bad block placement: " + action); int movingQueueSize = movingQueue.size(); if (movingQueueSize < maxQueueSize || action.priority >= alwaysSubmitPriorityLevel) { executor.execute(action); metrics.blockMoveScheduled.inc(); } else { LOG.warn("Block move queue is full. Skip the action." + " size:" + movingQueueSize + " maxSize:" + maxQueueSize); metrics.blockMoveSkipped.inc(); } } /** * Sort BlockMoveAction based on the priority in descending order */ static class BlockMoveActionComparator implements Comparator<Runnable> { @Override public int compare(Runnable o1, Runnable o2) { BlockMoveAction a1 = (BlockMoveAction) o1; BlockMoveAction a2 = (BlockMoveAction) o2; if (a1.priority > a2.priority) { return -1; } if (a1.priority < a2.priority) { return 1; } // if tie, sort based on the time in ascending order return a1.createTime > a2.createTime ? 1 : -1; } } /** * Create one more replication of the block */ class BlockMoveAction implements Runnable { final LocatedBlock block; final Set<DatanodeInfo> excludedNodes; final DatanodeInfo source; // The datanode where this block will be removed DatanodeInfo target; // The destination for this block DatanodeInfo proxySource; // The datanode that copies this block to target final int priority; final long createTime; BlockMoveAction(LocatedBlock block, DatanodeInfo source, Set<DatanodeInfo> excludedNodes, int priority) { this.block = block; this.excludedNodes = excludedNodes; for (DatanodeInfo d : block.getLocations()) { // Also exclude the original locations excludedNodes.add(d); } this.source = source; this.createTime = System.currentTimeMillis(); this.priority = priority; } /** * Choose target, source and proxySource for the move * @throws IOException */ void chooseNodes() throws IOException { target = cluster.getRandomNode(excludedNodes); if (target == null) { throw new IOException("Error choose datanode"); } for (DatanodeInfo n : block.getLocations()) { if (cluster.isOnSameRack(target, n)) { proxySource = n; return; } } proxySource = block.getLocations()[rand.nextInt(block.getLocations().length)]; } @Override public void run() { Socket sock = null; DataOutputStream out = null; DataInputStream in = null; try { chooseNodes(); if (simulate) { LOG.debug("Simulate mode. Skip move target:" + target + " source:" + source + " proxySource:" + proxySource); metrics.blockMove.inc(); return; } sock = new Socket(); sock.connect(NetUtils.createSocketAddr( target.getName()), HdfsConstants.READ_TIMEOUT); sock.setKeepAlive(true); out = new DataOutputStream( new BufferedOutputStream( sock.getOutputStream(), FSConstants.BUFFER_SIZE)); sendRequest(out); in = new DataInputStream( new BufferedInputStream( sock.getInputStream(), FSConstants.BUFFER_SIZE)); receiveResponse(in); metrics.blockMove.inc(); LOG.debug( "Moving block " + block.getBlock().getBlockId() + " from "+ source.getName() + " to " + target.getName() + " through " + proxySource.getName() + " succeeded." ); } catch (IOException e) { LOG.warn("Error moving block " + block.getBlock().getBlockId() + " from " + source.getName() + " to " + target.getName() + " through " + proxySource.getName() + ": " + e.getMessage()); if (e instanceof EOFException) { LOG.warn("Moving block " + block.getBlock().getBlockId() + " was cancelled because the time exceeded the limit"); } } finally { IOUtils.closeStream(out); IOUtils.closeStream(in); IOUtils.closeSocket(sock); } } @Override public String toString() { StringBuilder ret = new StringBuilder(); ret.append("block:").append(block.getBlock()).append("\t"); ret.append("locations:"); boolean first = true; for (DatanodeInfo n : block.getLocations()) { if (first) { ret.append(n.getHostName()); first = false; continue; } ret.append(",").append(n.getHostName()); } ret.append("\t"); ret.append("priority:"); ret.append(priority); ret.append("\t"); ret.append("createTime:"); ret.append(createTime); ret.append("\t"); ret.append("excludeNodes:"); ret.append(excludedNodes.size()); return ret.toString(); } /** * Send a block replace request to the output stream */ private void sendRequest(DataOutputStream out) throws IOException { out.writeShort(DataTransferProtocol.DATA_TRANSFER_VERSION); out.writeByte(DataTransferProtocol.OP_REPLACE_BLOCK); out.writeLong(block.getBlock().getBlockId()); out.writeLong(block.getBlock().getGenerationStamp()); Text.writeString(out, source.getStorageID()); proxySource.write(out); out.flush(); } /** * Receive a block copy response from the input stream */ private void receiveResponse(DataInputStream in) throws IOException { short status = in.readShort(); if (status != DataTransferProtocol.OP_STATUS_SUCCESS) { throw new IOException("block move is failed"); } } } /** * Periodically obtain node information from the cluster */ class ClusterInfo implements Runnable { NetworkTopology topology = new NetworkTopology(); DatanodeInfo liveNodes[]; static final long UPDATE_PERIOD = 60000L; volatile boolean running = true; long lastUpdate = -1L; @Override public void run() { // Update the information about the datanodes in the cluster while (running) { try { long now = System.currentTimeMillis(); if (now - lastUpdate > UPDATE_PERIOD) { lastUpdate = now; synchronized (this) { // This obtain the datanodes from the HDFS cluster in config file. // If we need to support parity file in a different cluster, this // has to change. DFSClient client = new DFSClient(conf); liveNodes = client.namenode.getDatanodeReport(DatanodeReportType.LIVE); for (DatanodeInfo n : liveNodes) { topology.add(n); } } } Thread.sleep(UPDATE_PERIOD / 10); } catch (InterruptedException e) { LOG.warn("Error update datanodes ", e); } catch (IOException e) { LOG.warn("Error update datanodes ", e); } } } public void stop() { running = false; } public synchronized DatanodeInfo getRandomNode(Set<DatanodeInfo> excluded) { if (liveNodes == null || liveNodes.length == 0) { return null; } if (liveNodes.length <= excluded.size()) { return liveNodes[rand.nextInt(liveNodes.length)]; } for (;;) { DatanodeInfo target = liveNodes[rand.nextInt(liveNodes.length)]; if (!excluded.contains(target)) { return target; } } } public synchronized boolean isOnSameRack(DatanodeInfo n1, DatanodeInfo n2) { return topology.isOnSameRack(n1, n2); } } }
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * 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 io.netty.test.udt.util; import com.yammer.metrics.Metrics; import com.yammer.metrics.core.Clock; import com.yammer.metrics.core.Counter; import com.yammer.metrics.core.Gauge; import com.yammer.metrics.core.Histogram; import com.yammer.metrics.core.Metered; import com.yammer.metrics.core.Metric; import com.yammer.metrics.core.MetricName; import com.yammer.metrics.core.MetricPredicate; import com.yammer.metrics.core.MetricProcessor; import com.yammer.metrics.core.MetricsRegistry; import com.yammer.metrics.core.Timer; import com.yammer.metrics.reporting.AbstractPollingReporter; import com.yammer.metrics.stats.Snapshot; import java.io.PrintStream; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import java.util.Map.Entry; import java.util.SortedMap; import java.util.TimeZone; import java.util.concurrent.TimeUnit; /** * A simple reporters which prints out application metrics to a * {@link PrintStream} periodically. */ public class CustomReporter extends AbstractPollingReporter implements MetricProcessor<PrintStream> { private static final int CONSOLE_WIDTH = 80; /** * Enables the console reporter for the default metrics registry, and causes * it to print to STDOUT with the specified period. */ public static void enable(final long period, final TimeUnit unit) { enable(Metrics.defaultRegistry(), period, unit); } /** * Enables the console reporter for the given metrics registry, and causes * it to print to STDOUT with the specified period and unrestricted output. */ public static void enable(final MetricsRegistry metricsRegistry, final long period, final TimeUnit unit) { final CustomReporter reporter = new CustomReporter( metricsRegistry, System.out, MetricPredicate.ALL); reporter.start(period, unit); } private final PrintStream out; private final MetricPredicate predicate; private final Clock clock; private final TimeZone timeZone; private final Locale locale; /** * Creates a new {@link CustomReporter} for the default metrics * registry, with unrestricted output. */ public CustomReporter(final PrintStream out) { this(Metrics.defaultRegistry(), out, MetricPredicate.ALL); } /** * Creates a new {@link CustomReporter} for a given metrics registry. */ public CustomReporter(final MetricsRegistry metricsRegistry, final PrintStream out, final MetricPredicate predicate) { this(metricsRegistry, out, predicate, Clock.defaultClock(), TimeZone .getDefault()); } /** * Creates a new {@link CustomReporter} for a given metrics registry. */ public CustomReporter(final MetricsRegistry metricsRegistry, final PrintStream out, final MetricPredicate predicate, final Clock clock, final TimeZone timeZone) { this(metricsRegistry, out, predicate, clock, timeZone, Locale .getDefault()); } /** * Creates a new {@link CustomReporter} for a given metrics registry. */ public CustomReporter(final MetricsRegistry metricsRegistry, final PrintStream out, final MetricPredicate predicate, final Clock clock, final TimeZone timeZone, final Locale locale) { super(metricsRegistry, "console-reporter"); this.out = out; this.predicate = predicate; this.clock = clock; this.timeZone = timeZone; this.locale = locale; } @Override public void run() { try { final DateFormat format = DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.MEDIUM, locale); format.setTimeZone(timeZone); final String dateTime = format.format(new Date(clock.time())); out.print(dateTime); out.print(' '); for (int i = 0; i < CONSOLE_WIDTH - dateTime.length() - 1; i++) { out.print('='); } out.println(); for (final Entry<String, SortedMap<MetricName, Metric>> entry : getMetricsRegistry() .groupedMetrics(predicate).entrySet()) { out.print(entry.getKey()); out.println(':'); for (final Entry<MetricName, Metric> subEntry : entry .getValue().entrySet()) { out.print(" "); out.print(subEntry.getKey().getName()); out.println(':'); subEntry.getValue().processWith(this, subEntry.getKey(), out); out.println(); } out.println(); } out.println(); out.flush(); } catch (final Exception e) { e.printStackTrace(out); } } @Override public void processGauge(final MetricName name, final Gauge<?> gauge, final PrintStream stream) { stream.printf(locale, " value = %s\n", gauge.value()); } @Override public void processCounter(final MetricName name, final Counter counter, final PrintStream stream) { stream.printf(locale, " count = %,d\n", counter.count()); } @Override public void processMeter(final MetricName name, final Metered meter, final PrintStream stream) { final String unit = abbrev(meter.rateUnit()); stream.printf(locale, " count = %,d\n", meter.count()); stream.printf(locale, " mean rate = %,2.2f %s/%s\n", meter.meanRate(), meter.eventType(), unit); stream.printf(locale, " 1-minute rate = %,2.2f %s/%s\n", meter.oneMinuteRate(), meter.eventType(), unit); stream.printf(locale, " 5-minute rate = %,2.2f %s/%s\n", meter.fiveMinuteRate(), meter.eventType(), unit); stream.printf(locale, " 15-minute rate = %,2.2f %s/%s\n", meter.fifteenMinuteRate(), meter.eventType(), unit); } @Override public void processHistogram(final MetricName name, final Histogram histogram, final PrintStream stream) { final Snapshot snapshot = histogram.getSnapshot(); stream.printf(locale, " min = %,2.2f\n", histogram.min()); stream.printf(locale, " max = %,2.2f\n", histogram.max()); stream.printf(locale, " mean = %,2.2f\n", histogram.mean()); stream.printf(locale, " stddev = %,2.2f\n", histogram.stdDev()); stream.printf(locale, " median = %,2.2f\n", snapshot.getMedian()); stream.printf(locale, " 75%% <= %,2.2f\n", snapshot.get75thPercentile()); stream.printf(locale, " 95%% <= %,2.2f\n", snapshot.get95thPercentile()); stream.printf(locale, " 98%% <= %,2.2f\n", snapshot.get98thPercentile()); stream.printf(locale, " 99%% <= %,2.2f\n", snapshot.get99thPercentile()); stream.printf(locale, " 99.9%% <= %,2.2f\n", snapshot.get999thPercentile()); } @Override public void processTimer(final MetricName name, final Timer timer, final PrintStream stream) { processMeter(name, timer, stream); final String durationUnit = abbrev(timer.durationUnit()); final Snapshot snapshot = timer.getSnapshot(); stream.printf(locale, " min = %,2.2f %s\n", timer.min(), durationUnit); stream.printf(locale, " max = %,2.2f %s\n", timer.max(), durationUnit); stream.printf(locale, " mean = %,2.2f %s\n", timer.mean(), durationUnit); stream.printf(locale, " stddev = %,2.2f %s\n", timer.stdDev(), durationUnit); stream.printf(locale, " median = %,2.2f %s\n", snapshot.getMedian(), durationUnit); stream.printf(locale, " 75%% <= %,2.2f %s\n", snapshot.get75thPercentile(), durationUnit); stream.printf(locale, " 95%% <= %,2.2f %s\n", snapshot.get95thPercentile(), durationUnit); stream.printf(locale, " 98%% <= %,2.2f %s\n", snapshot.get98thPercentile(), durationUnit); stream.printf(locale, " 99%% <= %,2.2f %s\n", snapshot.get99thPercentile(), durationUnit); stream.printf(locale, " 99.9%% <= %,2.2f %s\n", snapshot.get999thPercentile(), durationUnit); } private static String abbrev(final TimeUnit unit) { switch (unit) { case NANOSECONDS: return "ns"; case MICROSECONDS: return "us"; case MILLISECONDS: return "ms"; case SECONDS: return "s"; case MINUTES: return "m"; case HOURS: return "h"; case DAYS: return "d"; default: throw new IllegalArgumentException("Unrecognized TimeUnit: " + unit); } } }
/* * Copyright 2016 Analytical Graphics, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.keycloak.authentication.authenticators.x509; import java.security.GeneralSecurityException; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import java.util.function.Function; import javax.security.auth.x500.X500Principal; import javax.ws.rs.core.Response; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.style.BCStyle; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; import org.bouncycastle.util.encoders.Hex; import org.keycloak.authentication.AuthenticationFlowContext; import org.keycloak.authentication.Authenticator; import org.keycloak.events.Details; import org.keycloak.forms.login.LoginFormsProvider; import org.keycloak.jose.jws.crypto.HashUtils; import org.keycloak.crypto.HashException; import org.keycloak.crypto.JavaAlgorithm; import org.keycloak.models.Constants; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; import org.keycloak.services.ServicesLogger; import org.keycloak.services.x509.X509ClientCertificateLookup; /** * @author <a href="mailto:pnalyvayko@agi.com">Peter Nalyvayko</a> * @version $Revision: 1 $ * @date 7/31/2016 */ public abstract class AbstractX509ClientCertificateAuthenticator implements Authenticator { public static final String DEFAULT_ATTRIBUTE_NAME = "usercertificate"; protected static ServicesLogger logger = ServicesLogger.LOGGER; public static final String REGULAR_EXPRESSION = "x509-cert-auth.regular-expression"; public static final String ENABLE_CRL = "x509-cert-auth.crl-checking-enabled"; public static final String ENABLE_OCSP = "x509-cert-auth.ocsp-checking-enabled"; public static final String ENABLE_CRLDP = "x509-cert-auth.crldp-checking-enabled"; public static final String CANONICAL_DN = "x509-cert-auth.canonical-dn-enabled"; public static final String SERIALNUMBER_HEX = "x509-cert-auth.serialnumber-hex-enabled"; public static final String CRL_RELATIVE_PATH = "x509-cert-auth.crl-relative-path"; public static final String OCSPRESPONDER_URI = "x509-cert-auth.ocsp-responder-uri"; public static final String OCSPRESPONDER_CERTIFICATE = "x509-cert-auth.ocsp-responder-certificate"; public static final String MAPPING_SOURCE_SELECTION = "x509-cert-auth.mapping-source-selection"; public static final String MAPPING_SOURCE_CERT_SUBJECTDN = "Match SubjectDN using regular expression"; public static final String MAPPING_SOURCE_CERT_SUBJECTDN_EMAIL = "Subject's e-mail"; public static final String MAPPING_SOURCE_CERT_SUBJECTALTNAME_EMAIL = "Subject's Alternative Name E-mail"; public static final String MAPPING_SOURCE_CERT_SUBJECTALTNAME_OTHERNAME = "Subject's Alternative Name otherName (UPN)"; public static final String MAPPING_SOURCE_CERT_SUBJECTDN_CN = "Subject's Common Name"; public static final String MAPPING_SOURCE_CERT_ISSUERDN = "Match IssuerDN using regular expression"; public static final String MAPPING_SOURCE_CERT_SERIALNUMBER = "Certificate Serial Number"; public static final String MAPPING_SOURCE_CERT_SHA256_THUMBPRINT = "SHA-256 Thumbprint"; public static final String MAPPING_SOURCE_CERT_SERIALNUMBER_ISSUERDN = "Certificate Serial Number and IssuerDN"; public static final String MAPPING_SOURCE_CERT_CERTIFICATE_PEM = "Full Certificate in PEM format"; public static final String USER_MAPPER_SELECTION = "x509-cert-auth.mapper-selection"; public static final String USER_ATTRIBUTE_MAPPER = "Custom Attribute Mapper"; public static final String USERNAME_EMAIL_MAPPER = "Username or Email"; public static final String CUSTOM_ATTRIBUTE_NAME = "x509-cert-auth.mapper-selection.user-attribute-name"; public static final String CERTIFICATE_KEY_USAGE = "x509-cert-auth.keyusage"; public static final String CERTIFICATE_EXTENDED_KEY_USAGE = "x509-cert-auth.extendedkeyusage"; static final String DEFAULT_MATCH_ALL_EXPRESSION = "(.*?)(?:$)"; public static final String CONFIRMATION_PAGE_DISALLOWED = "x509-cert-auth.confirmation-page-disallowed"; protected Response createInfoResponse(AuthenticationFlowContext context, String infoMessage, Object ... parameters) { LoginFormsProvider form = context.form(); return form.setInfo(infoMessage, parameters).createInfoPage(); } protected static class CertificateValidatorConfigBuilder { static CertificateValidator.CertificateValidatorBuilder fromConfig(KeycloakSession session, X509AuthenticatorConfigModel config) throws Exception { CertificateValidator.CertificateValidatorBuilder builder = new CertificateValidator.CertificateValidatorBuilder(); return builder .session(session) .keyUsage() .parse(config.getKeyUsage()) .extendedKeyUsage() .parse(config.getExtendedKeyUsage()) .revocation() .cRLEnabled(config.getCRLEnabled()) .cRLDPEnabled(config.getCRLDistributionPointEnabled()) .cRLrelativePath(config.getCRLRelativePath()) .oCSPEnabled(config.getOCSPEnabled()) .oCSPResponseCertificate(config.getOCSPResponderCertificate()) .oCSPResponderURI(config.getOCSPResponder()); } } // The method is purely for purposes of facilitating the unit testing public CertificateValidator.CertificateValidatorBuilder certificateValidationParameters(KeycloakSession session, X509AuthenticatorConfigModel config) throws Exception { return CertificateValidatorConfigBuilder.fromConfig(session, config); } protected static class UserIdentityExtractorBuilder { private static final Function<X509Certificate[],X500Name> subject = certs -> { try { return new JcaX509CertificateHolder(certs[0]).getSubject(); } catch (CertificateEncodingException e) { logger.warn("Unable to get certificate Subject", e); } return null; }; private static final Function<X509Certificate[],X500Name> issuer = certs -> { try { return new JcaX509CertificateHolder(certs[0]).getIssuer(); } catch (CertificateEncodingException e) { logger.warn("Unable to get certificate Issuer", e); } return null; }; private static final Function<X509Certificate[], String> getSerialnumberFunc(X509AuthenticatorConfigModel config) { return config.isSerialnumberHex() ? certs -> Hex.toHexString(certs[0].getSerialNumber().toByteArray()) : certs -> certs[0].getSerialNumber().toString(); } private static final Function<X509Certificate[], String> getIssuerDNFunc(X509AuthenticatorConfigModel config) { return config.isCanonicalDnEnabled() ? certs -> certs[0].getIssuerX500Principal().getName(X500Principal.CANONICAL) : certs -> certs[0].getIssuerDN().getName(); } static UserIdentityExtractor fromConfig(X509AuthenticatorConfigModel config) { X509AuthenticatorConfigModel.MappingSourceType userIdentitySource = config.getMappingSourceType(); String pattern = config.getRegularExpression(); UserIdentityExtractor extractor = null; Function<X509Certificate[], String> func = null; switch(userIdentitySource) { case SUBJECTDN: func = config.isCanonicalDnEnabled() ? certs -> certs[0].getSubjectX500Principal().getName(X500Principal.CANONICAL) : certs -> certs[0].getSubjectDN().getName(); extractor = UserIdentityExtractor.getPatternIdentityExtractor(pattern, func); break; case ISSUERDN: extractor = UserIdentityExtractor.getPatternIdentityExtractor(pattern, getIssuerDNFunc(config)); break; case SERIALNUMBER: extractor = UserIdentityExtractor.getPatternIdentityExtractor(DEFAULT_MATCH_ALL_EXPRESSION, getSerialnumberFunc(config)); break; case SHA256_THUMBPRINT: extractor = UserIdentityExtractor.getPatternIdentityExtractor(DEFAULT_MATCH_ALL_EXPRESSION, certs -> { try { return Hex.toHexString(HashUtils.hash(JavaAlgorithm.SHA256, certs[0].getEncoded())); } catch (CertificateEncodingException | HashException e) { logger.warn("Unable to get certificate's thumbprint", e); } return null; }); break; case SERIALNUMBER_ISSUERDN: func = certs -> getSerialnumberFunc(config).apply(certs) + Constants.CFG_DELIMITER + getIssuerDNFunc(config).apply(certs); extractor = UserIdentityExtractor.getPatternIdentityExtractor(DEFAULT_MATCH_ALL_EXPRESSION, func); break; case SUBJECTDN_CN: extractor = UserIdentityExtractor.getX500NameExtractor(BCStyle.CN, subject); break; case SUBJECTDN_EMAIL: extractor = UserIdentityExtractor .either(UserIdentityExtractor.getX500NameExtractor(BCStyle.EmailAddress, subject)) .or(UserIdentityExtractor.getX500NameExtractor(BCStyle.E, subject)); break; case SUBJECTALTNAME_EMAIL: extractor = UserIdentityExtractor.getSubjectAltNameExtractor(1); break; case SUBJECTALTNAME_OTHERNAME: extractor = UserIdentityExtractor.getSubjectAltNameExtractor(0); break; case CERTIFICATE_PEM: extractor = UserIdentityExtractor.getCertificatePemIdentityExtractor(config); break; default: logger.warnf("[UserIdentityExtractorBuilder:fromConfig] Unknown or unsupported user identity source: \"%s\"", userIdentitySource.getName()); break; } return extractor; } } protected static class UserIdentityToModelMapperBuilder { static UserIdentityToModelMapper fromConfig(X509AuthenticatorConfigModel config) { X509AuthenticatorConfigModel.IdentityMapperType mapperType = config.getUserIdentityMapperType(); String attributeName = config.getCustomAttributeName(); UserIdentityToModelMapper mapper = null; switch (mapperType) { case USER_ATTRIBUTE: mapper = UserIdentityToModelMapper.getUserIdentityToCustomAttributeMapper(attributeName); break; case USERNAME_EMAIL: mapper = UserIdentityToModelMapper.getUsernameOrEmailMapper(); break; default: logger.warnf("[UserIdentityToModelMapperBuilder:fromConfig] Unknown or unsupported user identity mapper: \"%s\"", mapperType.getName()); } return mapper; } } @Override public void close() { } protected X509Certificate[] getCertificateChain(AuthenticationFlowContext context) { try { // Get a x509 client certificate X509ClientCertificateLookup provider = context.getSession().getProvider(X509ClientCertificateLookup.class); if (provider == null) { logger.errorv("\"{0}\" Spi is not available, did you forget to update the configuration?", X509ClientCertificateLookup.class); return null; } X509Certificate[] certs = provider.getCertificateChain(context.getHttpRequest()); if (certs != null) { for (X509Certificate cert : certs) { logger.tracev("\"{0}\"", cert.getSubjectDN().getName()); } } return certs; } catch (GeneralSecurityException e) { logger.error(e.getMessage(), e); } return null; } // Saving some notes for audit to authSession as the event may not be necessarily triggered in this HTTP request where the certificate was parsed // For example if there is confirmation page enabled, it will be in the additional request protected void saveX509CertificateAuditDataToAuthSession(AuthenticationFlowContext context, X509Certificate cert) { context.getAuthenticationSession().setAuthNote(Details.X509_CERTIFICATE_SERIAL_NUMBER, cert.getSerialNumber().toString()); context.getAuthenticationSession().setAuthNote(Details.X509_CERTIFICATE_SUBJECT_DISTINGUISHED_NAME, cert.getSubjectDN().toString()); context.getAuthenticationSession().setAuthNote(Details.X509_CERTIFICATE_ISSUER_DISTINGUISHED_NAME, cert.getIssuerDN().toString()); } protected void recordX509CertificateAuditDataViaContextEvent(AuthenticationFlowContext context) { recordX509DetailFromAuthSessionToEvent(context, Details.X509_CERTIFICATE_SERIAL_NUMBER); recordX509DetailFromAuthSessionToEvent(context, Details.X509_CERTIFICATE_SUBJECT_DISTINGUISHED_NAME); recordX509DetailFromAuthSessionToEvent(context, Details.X509_CERTIFICATE_ISSUER_DISTINGUISHED_NAME); } private void recordX509DetailFromAuthSessionToEvent(AuthenticationFlowContext context, String detailName) { String detailValue = context.getAuthenticationSession().getAuthNote(detailName); context.getEvent().detail(detailName, detailValue); } // Purely for unit testing public UserIdentityExtractor getUserIdentityExtractor(X509AuthenticatorConfigModel config) { return UserIdentityExtractorBuilder.fromConfig(config); } // Purely for unit testing public UserIdentityToModelMapper getUserIdentityToModelMapper(X509AuthenticatorConfigModel config) { return UserIdentityToModelMapperBuilder.fromConfig(config); } @Override public boolean requiresUser() { return false; } @Override public boolean configuredFor(KeycloakSession session, RealmModel realm, UserModel user) { return true; } @Override public void setRequiredActions(KeycloakSession session, RealmModel realm, UserModel user) { } }
package org.docksidestage.sqlite.dbflute.bsbhv.pmbean; import java.util.*; import org.dbflute.outsidesql.typed.*; import org.dbflute.jdbc.*; import org.dbflute.outsidesql.PmbCustodial; import org.dbflute.util.DfTypeUtil; import org.docksidestage.sqlite.dbflute.allcommon.*; import org.docksidestage.sqlite.dbflute.exbhv.*; /** * The base class for typed parameter-bean of ResolvedPackageName. <br> * This is related to "<span style="color: #AD4747">various:pmbcheck:selectResolvedPackageName</span>" on MemberBhv. * @author DBFlute(AutoGenerator) */ public class BsResolvedPackageNamePmb implements ExecuteHandlingPmb<MemberBhv>, FetchBean { // =================================================================================== // Attribute // ========= /** The parameter of string1. */ protected String _string1; /** The parameter of integer1. */ protected Integer _integer1; /** The parameter of bigDecimal1. */ protected java.math.BigDecimal _bigDecimal1; /** The parameter of bigDecimal2. */ protected java.math.BigDecimal _bigDecimal2; /** The parameter of date1. */ protected java.time.LocalDate _date1; /** The parameter of date2. */ protected java.util.Date _date2; /** The parameter of date3. */ protected java.sql.Date _date3; /** The parameter of time1. */ protected java.sql.Time _time1; /** The parameter of time2. */ protected java.sql.Time _time2; /** The parameter of timestamp1. */ protected java.time.LocalDateTime _timestamp1; /** The parameter of timestamp2. */ protected java.sql.Timestamp _timestamp2; /** The parameter of list1. */ protected List<String> _list1; /** The parameter of list2. */ protected java.util.List<String> _list2; /** The parameter of map1. */ protected Map<String, String> _map1; /** The parameter of map2. */ protected java.util.Map<String, String> _map2; /** The parameter of cdef. */ protected org.docksidestage.sqlite.dbflute.allcommon.MaCDef _cdef; /** The parameter of cdefFlg. */ protected org.docksidestage.sqlite.dbflute.allcommon.MaCDef.Flg _cdefFlg; /** The parameter of bytes. */ protected byte[] _bytes; /** The max size of safety result. */ protected int _safetyMaxResultSize; /** The time-zone for filtering e.g. from-to. (NullAllowed: if null, default zone) */ protected TimeZone _timeZone; // =================================================================================== // Constructor // =========== /** * Constructor for the typed parameter-bean of ResolvedPackageName. <br> * This is related to "<span style="color: #AD4747">various:pmbcheck:selectResolvedPackageName</span>" on MemberBhv. */ public BsResolvedPackageNamePmb() { } // =================================================================================== // Typed Implementation // ==================== /** * {@inheritDoc} */ public String getOutsideSqlPath() { return "various:pmbcheck:selectResolvedPackageName"; } // =================================================================================== // Safety Result // ============= /** * {@inheritDoc} */ public void checkSafetyResult(int safetyMaxResultSize) { _safetyMaxResultSize = safetyMaxResultSize; } /** * {@inheritDoc} */ public int getSafetyMaxResultSize() { return _safetyMaxResultSize; } // =================================================================================== // Assist Helper // ============= // ----------------------------------------------------- // String // ------ protected String filterStringParameter(String value) { return isEmptyStringParameterAllowed() ? value : convertEmptyToNull(value); } protected boolean isEmptyStringParameterAllowed() { return MaDBFluteConfig.getInstance().isEmptyStringParameterAllowed(); } protected String convertEmptyToNull(String value) { return PmbCustodial.convertEmptyToNull(value); } // ----------------------------------------------------- // Date // ---- protected Date toUtilDate(Object date) { return PmbCustodial.toUtilDate(date, _timeZone); } protected <DATE> DATE toLocalDate(Date date, Class<DATE> localType) { return PmbCustodial.toLocalDate(date, localType, chooseRealTimeZone()); } protected TimeZone chooseRealTimeZone() { return PmbCustodial.chooseRealTimeZone(_timeZone); } /** * Set time-zone, basically for LocalDate conversion. <br> * Normally you don't need to set this, you can adjust other ways. <br> * (DBFlute system's time-zone is used as default) * @param timeZone The time-zone for filtering. (NullAllowed: if null, default zone) */ public void zone(TimeZone timeZone) { _timeZone = timeZone; } // ----------------------------------------------------- // by Option Handling // ------------------ // might be called by option handling protected <NUMBER extends Number> NUMBER toNumber(Object obj, Class<NUMBER> type) { return PmbCustodial.toNumber(obj, type); } protected Boolean toBoolean(Object obj) { return PmbCustodial.toBoolean(obj); } @SuppressWarnings("unchecked") protected <ELEMENT> ArrayList<ELEMENT> newArrayList(ELEMENT... elements) { return PmbCustodial.newArrayList(elements); } // =================================================================================== // Basic Override // ============== /** * @return The display string of all parameters. (NotNull) */ @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(DfTypeUtil.toClassTitle(this)).append(":"); sb.append(xbuildColumnString()); return sb.toString(); } protected String xbuildColumnString() { final String dm = ", "; final StringBuilder sb = new StringBuilder(); sb.append(dm).append(_string1); sb.append(dm).append(_integer1); sb.append(dm).append(_bigDecimal1); sb.append(dm).append(_bigDecimal2); sb.append(dm).append(_date1); sb.append(dm).append(PmbCustodial.formatUtilDate(_date2, _timeZone, "yyyy-MM-dd")); sb.append(dm).append(_date3); sb.append(dm).append(_time1); sb.append(dm).append(_time2); sb.append(dm).append(_timestamp1); sb.append(dm).append(_timestamp2); sb.append(dm).append(_list1); sb.append(dm).append(_list2); sb.append(dm).append(_map1); sb.append(dm).append(_map2); sb.append(dm).append(_cdef); sb.append(dm).append(_cdefFlg); sb.append(dm).append(PmbCustodial.formatByteArray(_bytes)); if (sb.length() > 0) { sb.delete(0, dm.length()); } sb.insert(0, "{").append("}"); return sb.toString(); } // =================================================================================== // Accessor // ======== /** * [get] string1 <br> * @return The value of string1. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public String getString1() { return filterStringParameter(_string1); } /** * [set] string1 <br> * @param string1 The value of string1. (NullAllowed) */ public void setString1(String string1) { _string1 = string1; } /** * [get] integer1 <br> * @return The value of integer1. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public Integer getInteger1() { return _integer1; } /** * [set] integer1 <br> * @param integer1 The value of integer1. (NullAllowed) */ public void setInteger1(Integer integer1) { _integer1 = integer1; } /** * [get] bigDecimal1 <br> * @return The value of bigDecimal1. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public java.math.BigDecimal getBigDecimal1() { return _bigDecimal1; } /** * [set] bigDecimal1 <br> * @param bigDecimal1 The value of bigDecimal1. (NullAllowed) */ public void setBigDecimal1(java.math.BigDecimal bigDecimal1) { _bigDecimal1 = bigDecimal1; } /** * [get] bigDecimal2 <br> * @return The value of bigDecimal2. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public java.math.BigDecimal getBigDecimal2() { return _bigDecimal2; } /** * [set] bigDecimal2 <br> * @param bigDecimal2 The value of bigDecimal2. (NullAllowed) */ public void setBigDecimal2(java.math.BigDecimal bigDecimal2) { _bigDecimal2 = bigDecimal2; } /** * [get] date1 <br> * @return The value of date1. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public java.time.LocalDate getDate1() { return _date1; } /** * [set] date1 <br> * @param date1 The value of date1. (NullAllowed) */ public void setDate1(java.time.LocalDate date1) { _date1 = date1; } /** * [get] date2 <br> * @return The value of date2. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public java.util.Date getDate2() { return toUtilDate(_date2); } /** * [set] date2 <br> * @param date2 The value of date2. (NullAllowed) */ public void setDate2(java.util.Date date2) { _date2 = date2; } /** * [get] date3 <br> * @return The value of date3. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public java.sql.Date getDate3() { return _date3; } /** * [set] date3 <br> * @param date3 The value of date3. (NullAllowed) */ public void setDate3(java.sql.Date date3) { _date3 = date3; } /** * [get] time1 <br> * @return The value of time1. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public java.sql.Time getTime1() { return _time1; } /** * [set] time1 <br> * @param time1 The value of time1. (NullAllowed) */ public void setTime1(java.sql.Time time1) { _time1 = time1; } /** * [get] time2 <br> * @return The value of time2. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public java.sql.Time getTime2() { return _time2; } /** * [set] time2 <br> * @param time2 The value of time2. (NullAllowed) */ public void setTime2(java.sql.Time time2) { _time2 = time2; } /** * [get] timestamp1 <br> * @return The value of timestamp1. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public java.time.LocalDateTime getTimestamp1() { return _timestamp1; } /** * [set] timestamp1 <br> * @param timestamp1 The value of timestamp1. (NullAllowed) */ public void setTimestamp1(java.time.LocalDateTime timestamp1) { _timestamp1 = timestamp1; } /** * [get] timestamp2 <br> * @return The value of timestamp2. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public java.sql.Timestamp getTimestamp2() { return _timestamp2; } /** * [set] timestamp2 <br> * @param timestamp2 The value of timestamp2. (NullAllowed) */ public void setTimestamp2(java.sql.Timestamp timestamp2) { _timestamp2 = timestamp2; } /** * [get] list1 <br> * @return The value of list1. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public List<String> getList1() { return _list1; } /** * [set] list1 <br> * @param list1 The value of list1. (NullAllowed) */ public void setList1(List<String> list1) { _list1 = list1; } /** * [get] list2 <br> * @return The value of list2. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public java.util.List<String> getList2() { return _list2; } /** * [set] list2 <br> * @param list2 The value of list2. (NullAllowed) */ public void setList2(java.util.List<String> list2) { _list2 = list2; } /** * [get] map1 <br> * @return The value of map1. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public Map<String, String> getMap1() { return _map1; } /** * [set] map1 <br> * @param map1 The value of map1. (NullAllowed) */ public void setMap1(Map<String, String> map1) { _map1 = map1; } /** * [get] map2 <br> * @return The value of map2. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public java.util.Map<String, String> getMap2() { return _map2; } /** * [set] map2 <br> * @param map2 The value of map2. (NullAllowed) */ public void setMap2(java.util.Map<String, String> map2) { _map2 = map2; } /** * [get] cdef <br> * @return The value of cdef. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public org.docksidestage.sqlite.dbflute.allcommon.MaCDef getCdef() { return _cdef; } /** * [set] cdef <br> * @param cdef The value of cdef. (NullAllowed) */ public void setCdef(org.docksidestage.sqlite.dbflute.allcommon.MaCDef cdef) { _cdef = cdef; } /** * [get] cdefFlg <br> * @return The value of cdefFlg. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public org.docksidestage.sqlite.dbflute.allcommon.MaCDef.Flg getCdefFlg() { return _cdefFlg; } /** * [set] cdefFlg <br> * @param cdefFlg The value of cdefFlg. (NullAllowed) */ public void setCdefFlg(org.docksidestage.sqlite.dbflute.allcommon.MaCDef.Flg cdefFlg) { _cdefFlg = cdefFlg; } /** * [get] bytes <br> * @return The value of bytes. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public byte[] getBytes() { return _bytes; } /** * [set] bytes <br> * @param bytes The value of bytes. (NullAllowed) */ public void setBytes(byte[] bytes) { _bytes = bytes; } }
/* * Copyright 2003 - 2013 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package org.efaps.db.store; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipOutputStream; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NameClassPair; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.transaction.xa.XAException; import javax.transaction.xa.Xid; import org.apache.commons.vfs2.FileContent; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemException; import org.apache.commons.vfs2.impl.DefaultFileSystemManager; import org.apache.commons.vfs2.provider.FileProvider; import org.efaps.db.Instance; import org.efaps.db.wrapper.SQLSelect; import org.efaps.util.EFapsException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>The class implements the {@link Resource} interface for Apache Jakarta * Commons Virtual File System.<p/> * <p> * All different virtual file systems could be used. The algorithm is: * <ol> * <li>check if the file already exists</li> * <li></li> * <li></li> * </ol> * The store implements the compress property setting on the type for * <code>ZIP</code> and <code>GZIP</code>.</p> * * For each file id a new VFS store resource must be created. * * @author The eFaps Team * @version $Id$ */ public class VFSStoreResource extends AbstractStoreResource { /** * Extension of the temporary file in the store used in the transaction * that the original file is not overwritten. */ private static final String EXTENSION_TEMP = ".tmp"; /** * Extension of a file in the store. */ private static final String EXTENSION_NORMAL = ""; /** * Extension of a bakup file in the store. */ private static final String EXTENSION_BACKUP = ".bak"; /** * Property Name of the number of sub directories. */ private static final String PROPERTY_NUMBER_SUBDIRS = "VFSNumberSubDirectories"; /** * Property Name to define if the type if is used to define a sub * directory. */ private static final String PROPERTY_USE_TYPE = "VFSUseTypeIdInPath"; /** * Property Name to define if the type if is used to define a sub * directory. */ private static final String PROPERTY_NUMBER_BACKUP = "VFSNumberBackups"; /** * Property Name to define the base name. */ private static final String PROPERTY_BASENAME = "VFSBaseName"; /** * Property Name for the class name of the Provider. */ private static final String PROPERTY_PROVIDER = "VFSProvider"; /** * Logging instance used in this class. */ private static final Logger LOG = LoggerFactory.getLogger(VFSStoreResource.class); /** * Buffer used to copy from the input stream to the output stream. * * @see #write(InputStream, int) */ private final byte[] buffer = new byte[1024]; /** * Stores the name of the file including the correct directory. */ private String storeFileName = null; /** * FilesystemManager for this VFSStoreResource. */ private DefaultFileSystemManager manager; /** * NUmber of backup files to be kept. */ private int numberBackup = 1; /** * Method called to initialize this StoreResource. * @param _instance Instance of the object this StoreResource is wanted * for * @param _store Store this resource belongs to * @throws EFapsException on error * @see Resource#initialize(Instance, Map, Compress) */ @Override public void initialize(final Instance _instance, final Store _store) throws EFapsException { super.initialize(_instance, _store); final StringBuilder fileNameTmp = new StringBuilder(); final String useTypeIdStr = getStore().getResourceProperties().get(VFSStoreResource.PROPERTY_USE_TYPE); if ("true".equalsIgnoreCase(useTypeIdStr)) { fileNameTmp.append(getInstance().getType().getId()).append("/"); } final String numberSubDirsStr = getStore().getResourceProperties().get( VFSStoreResource.PROPERTY_NUMBER_SUBDIRS); if (numberSubDirsStr != null) { final long numberSubDirs = Long.parseLong(numberSubDirsStr); final String pathFormat = "%0" + Math.round(Math.log10(numberSubDirs) + 0.5d) + "d"; fileNameTmp.append(String.format(pathFormat, getInstance().getId() % numberSubDirs)) .append("/"); } fileNameTmp.append(getInstance().getType().getId()).append(".").append(getInstance().getId()); this.storeFileName = fileNameTmp.toString(); final String numberBackupStr = getStore().getResourceProperties().get(VFSStoreResource.PROPERTY_NUMBER_BACKUP); if (numberBackupStr != null) { this.numberBackup = Integer.parseInt(numberBackupStr); } if (this.manager == null) { try { DefaultFileSystemManager tmpMan = null; if (getStore().getResourceProperties().containsKey(Store.PROPERTY_JNDINAME)) { final InitialContext initialContext = new InitialContext(); final Context context = (Context) initialContext.lookup("java:comp/env"); final NamingEnumeration<NameClassPair> nameEnum = context.list(""); while (nameEnum.hasMoreElements()) { final NameClassPair namePair = nameEnum.next(); if (namePair.getName().equals(getStore().getResourceProperties().get( Store.PROPERTY_JNDINAME))) { tmpMan = (DefaultFileSystemManager) context.lookup( getStore().getResourceProperties().get(Store.PROPERTY_JNDINAME)); break; } } } if (tmpMan == null && this.manager == null) { this.manager = evaluateFileSystemManager(); } } catch (final NamingException e) { throw new EFapsException(VFSStoreResource.class, "initialize.NamingException", e); } } } /** * @return DefaultFileSystemManager * @throws EFapsException on error */ private DefaultFileSystemManager evaluateFileSystemManager() throws EFapsException { final DefaultFileSystemManager ret = new DefaultFileSystemManager(); final String baseName = getProperties().get(VFSStoreResource.PROPERTY_BASENAME); final String provider = getProperties().get(VFSStoreResource.PROPERTY_PROVIDER); try { ret.init(); final FileProvider fileProvider = (FileProvider) Class.forName(provider).newInstance(); ret.addProvider(baseName, fileProvider); ret.setBaseFile(fileProvider.findFile(null, baseName, null)); } catch (final FileSystemException e) { throw new EFapsException(VFSStoreResource.class, "evaluateFileSystemManager.FileSystemException", e, provider, baseName); } catch (final InstantiationException e) { throw new EFapsException(VFSStoreResource.class, "evaluateFileSystemManager.InstantiationException", e, baseName, provider); } catch (final IllegalAccessException e) { throw new EFapsException(VFSStoreResource.class, "evaluateFileSystemManager.IllegalAccessException", e, provider); } catch (final ClassNotFoundException e) { throw new EFapsException(VFSStoreResource.class, "evaluateFileSystemManager.ClassNotFoundException", e, provider); } return ret; } /** * {@inheritDoc} */ @Override protected int add2Select(final SQLSelect _select) { return 0; } /** * The method writes the context (from the input stream) to a temporary file * (same file URL, but with extension {@link #EXTENSION_TEMP}). * * @param _in input stream defined the content of the file * @param _size length of the content (or negative meaning that the length * is not known; then the content gets the length of readable * bytes from the input stream) * @param _fileName name of the file * @return size of the created temporary file object * @throws EFapsException on error */ public long write(final InputStream _in, final long _size, final String _fileName) throws EFapsException { try { long size = _size; final FileObject tmpFile = this.manager.resolveFile(this.manager.getBaseFile(), this.storeFileName + VFSStoreResource.EXTENSION_TEMP); if (!tmpFile.exists()) { tmpFile.createFile(); } final FileContent content = tmpFile.getContent(); OutputStream out = content.getOutputStream(false); if (getCompress().equals(Compress.GZIP)) { out = new GZIPOutputStream(out); } else if (getCompress().equals(Compress.ZIP)) { out = new ZipOutputStream(out); } // if size is unkown! if (_size < 0) { int length = 1; size = 0; while (length > 0) { length = _in.read(this.buffer); if (length > 0) { out.write(this.buffer, 0, length); size += length; } } } else { Long length = _size; while (length > 0) { final int readLength = length.intValue() < this.buffer.length ? length.intValue() : this.buffer.length; _in.read(this.buffer, 0, readLength); out.write(this.buffer, 0, readLength); length -= readLength; } } if (getCompress().equals(Compress.GZIP) || getCompress().equals(Compress.ZIP)) { out.close(); } tmpFile.close(); setFileInfo(_fileName, size); return size; } catch (final IOException e) { VFSStoreResource.LOG.error("write of content failed", e); throw new EFapsException(VFSStoreResource.class, "write.IOException", e); } } /** * Deletes the file defined in {@link #fileId}. */ public void delete() { //Deletion is done on commit } /** * Returns for the file the input stream. * * @return input stream of the file with the content * @throws EFapsException on error */ public InputStream read() throws EFapsException { StoreResourceInputStream in = null; try { final FileObject file = this.manager.resolveFile(this.storeFileName + VFSStoreResource.EXTENSION_NORMAL); if (!file.isReadable()) { VFSStoreResource.LOG.error("file for " + this.storeFileName + " not readable"); throw new EFapsException(VFSStoreResource.class, "#####file not readable"); } in = new VFSStoreResourceInputStream(this, file); } catch (final FileSystemException e) { VFSStoreResource.LOG.error("read of " + this.storeFileName + " failed", e); throw new EFapsException(VFSStoreResource.class, "read.Throwable", e); } catch (final IOException e) { VFSStoreResource.LOG.error("read of " + this.storeFileName + " failed", e); throw new EFapsException(VFSStoreResource.class, "read.Throwable", e); } return in; } /** * Ask the resource manager to prepare for a transaction commit of the * transaction specified in xid (used for 2-phase commits). * * @param _xid Xid * @return always 0 */ public int prepare(final Xid _xid) { if (VFSStoreResource.LOG.isDebugEnabled()) { VFSStoreResource.LOG.debug("prepare (xid=" + _xid + ")"); } return 0; } /** * Method that deletes the oldest backup and moves the others one up. * * @param _backup file to backup * @param _number number of backup * @throws FileSystemException on error */ private void backup(final FileObject _backup, final int _number) throws FileSystemException { if (_number < this.numberBackup) { final FileObject backFile = this.manager.resolveFile(this.manager.getBaseFile(), this.storeFileName + VFSStoreResource.EXTENSION_BACKUP + _number); if (backFile.exists()) { backup(backFile, _number + 1); } _backup.moveTo(backFile); } else { _backup.delete(); } } /** * The method is called from the transaction manager if the complete * transaction is completed.<br/> * A file in the virtual file system is committed with the algorithms: * <ol> * <li>any existing backup fill will be moved to an older backup file. The * maximum number of backups can be defined by setting the property * {@link #PROPERTY_NUMBER_BACKUP}. Default is one. To disable the * property must be set to 0.</li> * <li>the current file is moved to the backup file (or deleted if property * {@link #PROPERTY_NUMBER_BACKUP} is 0)</li> * <li>the new file is moved to the original name</li> * </ol> * * @param _xid global transaction identifier (not used, because each * file with the file id gets a new VFS store resource * instance) * @param _onePhase <i>true</i> if it is a one phase commitment transaction * (not used) * @throws XAException if any exception occurs (catch on * {@link java.lang.Throwable}) */ public void commit(final Xid _xid, final boolean _onePhase) throws XAException { if (VFSStoreResource.LOG.isDebugEnabled()) { VFSStoreResource.LOG.debug("transaction commit"); } if (getStoreEvent() == VFSStoreResource.StoreEvent.WRITE) { try { final FileObject tmpFile = this.manager.resolveFile(this.manager.getBaseFile(), this.storeFileName + VFSStoreResource.EXTENSION_TEMP); final FileObject currentFile = this.manager.resolveFile(this.manager.getBaseFile(), this.storeFileName + VFSStoreResource.EXTENSION_NORMAL); final FileObject bakFile = this.manager.resolveFile(this.manager.getBaseFile(), this.storeFileName + VFSStoreResource.EXTENSION_BACKUP); if (bakFile.exists() && (this.numberBackup > 0)) { backup(bakFile, 0); } if (currentFile.exists()) { if (this.numberBackup > 0) { currentFile.moveTo(bakFile); } else { currentFile.delete(); } } tmpFile.moveTo(currentFile); tmpFile.close(); currentFile.close(); bakFile.close(); } catch (final FileSystemException e) { VFSStoreResource.LOG.error("transaction commit fails for " + _xid + " (one phase = " + _onePhase + ")", e); final XAException xa = new XAException(XAException.XA_RBCOMMFAIL); xa.initCause(e); throw xa; } } else if (getStoreEvent() == VFSStoreResource.StoreEvent.DELETE) { try { final FileObject curFile = this.manager.resolveFile(this.manager.getBaseFile(), this.storeFileName + VFSStoreResource.EXTENSION_NORMAL); final FileObject bakFile = this.manager.resolveFile(this.manager.getBaseFile(), this.storeFileName + VFSStoreResource.EXTENSION_BACKUP); if (bakFile.exists()) { bakFile.delete(); } if (curFile.exists()) { curFile.moveTo(bakFile); } bakFile.close(); curFile.close(); } catch (final FileSystemException e) { VFSStoreResource.LOG.error("transaction commit fails for " + _xid + " (one phase = " + _onePhase + ")", e); final XAException xa = new XAException(XAException.XA_RBCOMMFAIL); xa.initCause(e); throw xa; } } } /** * If the file written in the virtual file system must be rolled back, only * the created temporary file (created from method {@link #write}) is * deleted. * * @param _xid global transaction identifier (not used, because each * file with the file id gets a new VFS store resource * instance) * @throws XAException if any exception occurs (catch on * {@link java.lang.Throwable}) */ public void rollback(final Xid _xid) throws XAException { if (VFSStoreResource.LOG.isDebugEnabled()) { VFSStoreResource.LOG.debug("rollback (xid = " + _xid + ")"); } try { final FileObject tmpFile = this.manager.resolveFile(this.manager.getBaseFile(), this.storeFileName + VFSStoreResource.EXTENSION_TEMP); if (tmpFile.exists()) { tmpFile.delete(); } } catch (final FileSystemException e) { VFSStoreResource.LOG.error("transaction rollback fails for " + _xid, e); final XAException xa = new XAException(XAException.XA_RBCOMMFAIL); xa.initCause(e); throw xa; } } /** * Tells the resource manager to forget about a heuristically completed * transaction branch. * * @param _xid global transaction identifier (not used, because each file * with the file id gets a new VFS store resource instance) */ public void forget(final Xid _xid) { if (VFSStoreResource.LOG.isDebugEnabled()) { VFSStoreResource.LOG.debug("forget (xid = " + _xid + ")"); } } /** * Obtains the current transaction timeout value set for this XAResource * instance. * * @return always 0 */ public int getTransactionTimeout() { if (VFSStoreResource.LOG.isDebugEnabled()) { VFSStoreResource.LOG.debug("getTransactionTimeout"); } return 0; } /** * Obtains a list of prepared transaction branches from a resource manager. * * @param _flag flag * @return always <code>null</code> */ public Xid[] recover(final int _flag) { if (VFSStoreResource.LOG.isDebugEnabled()) { VFSStoreResource.LOG.debug("recover (flag = " + _flag + ")"); } return null; } /** * Sets the current transaction timeout value for this XAResource instance. * * @param _seconds number of seconds * @return always <i>true</i> */ public boolean setTransactionTimeout(final int _seconds) { if (VFSStoreResource.LOG.isDebugEnabled()) { VFSStoreResource.LOG.debug("setTransactionTimeout (seconds = " + _seconds + ")"); } return true; } /** * Input stream wrapper class. */ private class VFSStoreResourceInputStream extends StoreResourceInputStream { /** * File to be stored. */ private final FileObject file; /** * @param _storeRes storeresource * @param _file file to store * @throws IOException on error */ protected VFSStoreResourceInputStream(final AbstractStoreResource _storeRes, final FileObject _file) throws IOException { super(_storeRes, _file.getContent().getInputStream()); this.file = _file; } /** * The file object {@link #file} is closed. The method overwrites the * method to close the input stream, because if the file is closed, the * input stream is also closed. * * @throws IOException on error */ @Override protected void beforeClose() throws IOException { this.file.close(); } } }
package de.tr7zw.changeme.nbtapi.utils; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.bukkit.Bukkit; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.ServicePriority; import javax.net.ssl.HttpsURLConnection; import java.io.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import java.util.logging.Level; import java.util.zip.GZIPOutputStream; import static de.tr7zw.changeme.nbtapi.utils.MinecraftVersion.getLogger; /** * bStats collects some data for plugin authors. * <p> * Check out https://bStats.org/ to learn more about bStats! * * This class is modified by tr7zw to work when the api is shaded into other peoples plugins. */ public class ApiMetricsLite { private static final String PLUGINNAME = "ItemNBTAPI"; // DO NOT CHANGE THE NAME! else it won't link the data on bStats // The version of this bStats class public static final int B_STATS_VERSION = 1; // The version of the NBT-Api bStats public static final int NBT_BSTATS_VERSION = 1; // The url to which the data is sent private static final String URL = "https://bStats.org/submitData/bukkit"; // Is bStats enabled on this server? private boolean enabled; // Should failed requests be logged? private static boolean logFailedRequests; // Should the sent data be logged? private static boolean logSentData; // Should the response text be logged? private static boolean logResponseStatusText; // The uuid of the server private static String serverUUID; // The plugin private Plugin plugin; /** * Class constructor. * */ public ApiMetricsLite() { // The register method just uses any enabled plugin it can find to register. This *shouldn't* cause any problems, since the plugin isn't used any other way. // Register our service for(Plugin plug : Bukkit.getPluginManager().getPlugins()) { plugin = plug; if(plugin != null) break; } if(plugin == null) { return;// Didn't find any plugin that could work } // Get the config file File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); File configFile = new File(bStatsFolder, "config.yml"); YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); // Check if the config file exists if (!config.isSet("serverUuid")) { // Add default values config.addDefault("enabled", true); // Every server gets it's unique random id. config.addDefault("serverUuid", UUID.randomUUID().toString()); // Should failed request be logged? config.addDefault("logFailedRequests", false); // Should the sent data be logged? config.addDefault("logSentData", false); // Should the response text be logged? config.addDefault("logResponseStatusText", false); // Inform the server owners about bStats config.options().header( "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + "To honor their work, you should not disable it.\n" + "This has nearly no effect on the server performance!\n" + "Check out https://bStats.org/ to learn more :)" ).copyDefaults(true); try { config.save(configFile); } catch (IOException ignored) { } } // Load the data serverUUID = config.getString("serverUuid"); logFailedRequests = config.getBoolean("logFailedRequests", false); enabled = config.getBoolean("enabled", true); logSentData = config.getBoolean("logSentData", false); logResponseStatusText = config.getBoolean("logResponseStatusText", false); if (enabled) { boolean found = false; // Search for all other bStats Metrics classes to see if we are the first one for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) { try { service.getField("NBT_BSTATS_VERSION"); // Create only one instance of the nbt-api bstats. return; } catch (NoSuchFieldException ignored) { } try { service.getField("B_STATS_VERSION"); // Our identifier :) found = true; // We aren't the first break; } catch (NoSuchFieldException ignored) { } } boolean fFound = found; // Register our service if(Bukkit.isPrimaryThread()){ Bukkit.getServicesManager().register(ApiMetricsLite.class, this, plugin, ServicePriority.Normal); if (!fFound) { getLogger().info("[NBTAPI] Using the plugin '" + plugin.getName() + "' to create a bStats instance!"); // We are the first! startSubmitting(); } }else{ Bukkit.getScheduler().runTask(plugin, () -> { Bukkit.getServicesManager().register(ApiMetricsLite.class, this, plugin, ServicePriority.Normal); if (!fFound) { getLogger().info("[NBTAPI] Using the plugin '" + plugin.getName() + "' to create a bStats instance!"); // We are the first! startSubmitting(); } }); } } } /** * Checks if bStats is enabled. * * @return Whether bStats is enabled or not. */ public boolean isEnabled() { return enabled; } /** * Starts the Scheduler which submits our data every 30 minutes. */ private void startSubmitting() { final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (!plugin.isEnabled()) { // Plugin was disabled timer.cancel(); return; } // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) Bukkit.getScheduler().runTask(plugin, () -> submitData()); } }, 1000l * 60l * 5l, 1000l * 60l * 30l); // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! // WARNING: Just don't do it! } /** * Gets the plugin specific data. * This method is called using Reflection. * * @return The plugin specific data. */ public JsonObject getPluginData() { JsonObject data = new JsonObject(); data.addProperty("pluginName", PLUGINNAME); // Append the name of the plugin data.addProperty("pluginVersion", MinecraftVersion.VERSION); // Append the version of the plugin data.add("customCharts", new JsonArray()); return data; } /** * Gets the server specific data. * * @return The server specific data. */ private JsonObject getServerData() { // Minecraft specific data int playerAmount; try { // Around MC 1.8 the return type was changed to a collection from an array, // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) ? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size() : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; } catch (Exception e) { playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed } int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; String bukkitVersion = Bukkit.getVersion(); String bukkitName = Bukkit.getName(); // OS/Java specific data String javaVersion = System.getProperty("java.version"); String osName = System.getProperty("os.name"); String osArch = System.getProperty("os.arch"); String osVersion = System.getProperty("os.version"); int coreCount = Runtime.getRuntime().availableProcessors(); JsonObject data = new JsonObject(); data.addProperty("serverUUID", serverUUID); data.addProperty("playerAmount", playerAmount); data.addProperty("onlineMode", onlineMode); data.addProperty("bukkitVersion", bukkitVersion); data.addProperty("bukkitName", bukkitName); data.addProperty("javaVersion", javaVersion); data.addProperty("osName", osName); data.addProperty("osArch", osArch); data.addProperty("osVersion", osVersion); data.addProperty("coreCount", coreCount); return data; } /** * Collects the data and sends it afterwards. */ private void submitData() { final JsonObject data = getServerData(); JsonArray pluginData = new JsonArray(); // Search for all other bStats Metrics classes to get their plugin data for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) { try { service.getField("B_STATS_VERSION"); // Our identifier :) for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) { try { Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); if (plugin instanceof JsonObject) { pluginData.add((JsonObject) plugin); } else { // old bstats version compatibility try { Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); jsonStringGetter.setAccessible(true); String jsonString = (String) jsonStringGetter.invoke(plugin); JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); pluginData.add(object); } } catch (ClassNotFoundException e) { // minecraft version 1.14+ if (logFailedRequests) { getLogger().log(Level.WARNING, "[NBTAPI][BSTATS] Encountered exception while posting request!", e); // Not using the plugins logger since the plugin isn't the plugin containing the NBT-Api most of the time //this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception ", e); } continue; // continue looping since we cannot do any other thing. } } } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } } } catch (NoSuchFieldException ignored) { } } data.add("plugins", pluginData); // Create a new thread for the connection to the bStats server new Thread(new Runnable() { @Override public void run() { try { // Send the data sendData(plugin, data); } catch (Exception e) { // Something went wrong! :( if (logFailedRequests) { getLogger().log(Level.WARNING, "[NBTAPI][BSTATS] Could not submit plugin stats of " + plugin.getName(), e); // Not using the plugins logger since the plugin isn't the plugin containing the NBT-Api most of the time //plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); } } } }).start(); } /** * Sends the data to the bStats server. * * @param plugin Any plugin. It's just used to get a logger instance. * @param data The data to send. * @throws Exception If the request failed. */ private static void sendData(Plugin plugin, JsonObject data) throws Exception { if (data == null) { throw new IllegalArgumentException("Data cannot be null!"); } if (Bukkit.isPrimaryThread()) { throw new IllegalAccessException("This method must not be called from the main thread!"); } if (logSentData) { MinecraftVersion.getLogger().info("[NBTAPI][BSTATS] Sending data to bStats: " + data.toString()); // Not using the plugins logger since the plugin isn't the plugin containing the NBT-Api most of the time //plugin.getLogger().info("Sending data to bStats: " + data.toString()); } HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); // Compress the data to save bandwidth byte[] compressedData = compress(data.toString()); // Add headers connection.setRequestMethod("POST"); connection.addRequestProperty("Accept", "application/json"); connection.addRequestProperty("Connection", "close"); connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); // Send data connection.setDoOutput(true); DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.write(compressedData); outputStream.flush(); outputStream.close(); InputStream inputStream = connection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder builder = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { builder.append(line); } bufferedReader.close(); if (logResponseStatusText) { getLogger().info("[NBTAPI][BSTATS] Sent data to bStats and received response: " + builder.toString()); // Not using the plugins logger since the plugin isn't the plugin containing the NBT-Api most of the time //plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString()); } } /** * Gzips the given String. * * @param str The string to gzip. * @return The gzipped String. * @throws IOException If the compression failed. */ private static byte[] compress(final String str) throws IOException { if (str == null) { return new byte[0]; } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(outputStream); gzip.write(str.getBytes(StandardCharsets.UTF_8)); gzip.close(); return outputStream.toByteArray(); } }
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alex.develop.cache; import android.annotation.TargetApi; import android.os.Handler; import android.os.Message; import android.os.Process; import java.util.ArrayDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * ************************************* * Copied from JB release framework: * https://android.googlesource.com/platform/frameworks/base/+/jb-release/core/java/android/os/AsyncTask.java * * so that threading behavior on all OS versions is the same and we can tweak behavior by using * executeOnExecutor() if needed. * * There are 3 changes in this copy of AsyncTask: * -pre-HC a single thread executor is used for serial operation * (Executors.newSingleThreadExecutor) and is the default * -the default THREAD_POOL_EXECUTOR was changed to use DiscardOldestPolicy * -a new fixed thread pool called DUAL_THREAD_EXECUTOR was added * ************************************* * * <p>AsyncTask enables proper and easy use of the UI thread. This class allows to * perform background operations and publish results on the UI thread without * having to manipulate threads and/or handlers.</p> * * <p>AsyncTask is designed to be a helper class around {@link Thread} and {@link Handler} * and does not constitute a generic threading framework. AsyncTasks should ideally be * used for short operations (a few seconds at the most.) If you need to keep threads * running for long periods of time, it is highly recommended you use the various APIs * provided by the <code>java.util.concurrent</code> pacakge such as {@link Executor}, * {@link ThreadPoolExecutor} and {@link FutureTask}.</p> * * <p>An asynchronous task is defined by a computation that runs on a background thread and * whose result is published on the UI thread. An asynchronous task is defined by 3 generic * types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>, * and 4 steps, called <code>onPreExecute</code>, <code>doInBackground</code>, * <code>onProgressUpdate</code> and <code>onPostExecute</code>.</p> * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For more information about using tasks and threads, read the * <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and * Threads</a> developer guide.</p> * </div> * * <h2>Usage</h2> * <p>AsyncTask must be subclassed to be used. The subclass will override at least * one method ({@link #doInBackground}), and most often will override a * second one ({@link #onPostExecute}.)</p> * * <p>Here is an example of subclassing:</p> * <pre class="prettyprint"> * private class DownloadFilesTask extends AsyncTask&lt;URL, Integer, Long&gt; { * protected Long doInBackground(URL... urls) { * int count = urls.length; * long totalSize = 0; * for (int i = 0; i < count; i++) { * totalSize += Downloader.downloadFile(urls[i]); * publishProgress((int) ((i / (float) count) * 100)); * // Escape early if cancel() is called * if (isCancelled()) break; * } * return totalSize; * } * * protected void onProgressUpdate(Integer... progress) { * setProgressPercent(progress[0]); * } * * protected void onPostExecute(Long result) { * showDialog("Downloaded " + result + " bytes"); * } * } * </pre> * * <p>Once created, a task is executed very simply:</p> * <pre class="prettyprint"> * new DownloadFilesTask().execute(url1, url2, url3); * </pre> * * <h2>AsyncTask's generic types</h2> * <p>The three types used by an asynchronous task are the following:</p> * <ol> * <li><code>Params</code>, the type of the parameters sent to the task upon * execution.</li> * <li><code>Progress</code>, the type of the progress units published during * the background computation.</li> * <li><code>Result</code>, the type of the result of the background * computation.</li> * </ol> * <p>Not all types are always used by an asynchronous task. To mark a type as unused, * simply use the type {@link Void}:</p> * <pre> * private class MyTask extends AsyncTask&lt;Void, Void, Void&gt; { ... } * </pre> * * <h2>The 4 steps</h2> * <p>When an asynchronous task is executed, the task goes through 4 steps:</p> * <ol> * <li>{@link #onPreExecute()}, invoked on the UI thread immediately after the task * is executed. This step is normally used to setup the task, for instance by * showing a progress bar in the user interface.</li> * <li>{@link #doInBackground}, invoked on the background thread * immediately after {@link #onPreExecute()} finishes executing. This step is used * to perform background computation that can take a long time. The parameters * of the asynchronous task are passed to this step. The result of the computation must * be returned by this step and will be passed back to the last step. This step * can also use {@link #publishProgress} to publish one or more units * of progress. These values are published on the UI thread, in the * {@link #onProgressUpdate} step.</li> * <li>{@link #onProgressUpdate}, invoked on the UI thread after a * call to {@link #publishProgress}. The timing of the execution is * undefined. This method is used to display any form of progress in the user * interface while the background computation is still executing. For instance, * it can be used to animate a progress bar or show logs in a text field.</li> * <li>{@link #onPostExecute}, invoked on the UI thread after the background * computation finishes. The result of the background computation is passed to * this step as a parameter.</li> * </ol> * * <h2>Cancelling a task</h2> * <p>A task can be cancelled at any time by invoking {@link #cancel(boolean)}. Invoking * this method will cause subsequent calls to {@link #isCancelled()} to return true. * After invoking this method, {@link #onCancelled(Object)}, instead of * {@link #onPostExecute(Object)} will be invoked after {@link #doInBackground(Object[])} * returns. To ensure that a task is cancelled as quickly as possible, you should always * check the return value of {@link #isCancelled()} periodically from * {@link #doInBackground(Object[])}, if possible (inside a loop for instance.)</p> * * <h2>Threading rules</h2> * <p>There are a few threading rules that must be followed for this class to * work properly:</p> * <ul> * <li>The AsyncTask class must be loaded on the UI thread. This is done * automatically as of {@link android.os.Build.VERSION_CODES#JELLY_BEAN}.</li> * <li>The task instance must be created on the UI thread.</li> * <li>{@link #execute} must be invoked on the UI thread.</li> * <li>Do not call {@link #onPreExecute()}, {@link #onPostExecute}, * {@link #doInBackground}, {@link #onProgressUpdate} manually.</li> * <li>The task can be executed only once (an exception will be thrown if * a second execution is attempted.)</li> * </ul> * * <h2>Memory observability</h2> * <p>AsyncTask guarantees that all callback calls are synchronized in such a way that the following * operations are safe without explicit synchronizations.</p> * <ul> * <li>Set member fields in the constructor or {@link #onPreExecute}, and refer to them * in {@link #doInBackground}. * <li>Set member fields in {@link #doInBackground}, and refer to them in * {@link #onProgressUpdate} and {@link #onPostExecute}. * </ul> * * <h2>Order of execution</h2> * <p>When first introduced, AsyncTasks were executed serially on a single background * thread. Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed * to a pool of threads allowing multiple tasks to operate in parallel. Starting with * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are executed on a single * thread to avoid common application errors caused by parallel execution.</p> * <p>If you truly want parallel execution, you can invoke * {@link #executeOnExecutor(Executor, Object[])} with * {@link #THREAD_POOL_EXECUTOR}.</p> */ public abstract class AsyncTask<Params, Progress, Result> { private static final String LOG_TAG = "AsyncTask"; private static final int CORE_POOL_SIZE = 5; private static final int MAXIMUM_POOL_SIZE = 128; private static final int KEEP_ALIVE = 1; private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); } }; private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(10); /** * An {@link Executor} that can be used to execute tasks in parallel. */ public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory, new ThreadPoolExecutor.DiscardOldestPolicy()); /** * An {@link Executor} that executes tasks one at a time in serial * order. This serialization is global to a particular process. */ public static final Executor SERIAL_EXECUTOR = Utils.hasHoneycomb() ? new SerialExecutor() : Executors.newSingleThreadExecutor(sThreadFactory); public static final Executor DUAL_THREAD_EXECUTOR = Executors.newFixedThreadPool(2, sThreadFactory); private static final int MESSAGE_POST_RESULT = 0x1; private static final int MESSAGE_POST_PROGRESS = 0x2; private static final InternalHandler sHandler = new InternalHandler(); private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR; private final WorkerRunnable<Params, Result> mWorker; private final FutureTask<Result> mFuture; private volatile Status mStatus = Status.PENDING; private final AtomicBoolean mCancelled = new AtomicBoolean(); private final AtomicBoolean mTaskInvoked = new AtomicBoolean(); @TargetApi(11) private static class SerialExecutor implements Executor { final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>(); Runnable mActive; public synchronized void execute(final Runnable r) { mTasks.offer(new Runnable() { public void run() { try { r.run(); } finally { scheduleNext(); } } }); if (mActive == null) { scheduleNext(); } } protected synchronized void scheduleNext() { if ((mActive = mTasks.poll()) != null) { THREAD_POOL_EXECUTOR.execute(mActive); } } } /** * Indicates the current status of the task. Each status will be set only once * during the lifetime of a task. */ public enum Status { /** * Indicates that the task has not been executed yet. */ PENDING, /** * Indicates that the task is running. */ RUNNING, /** * Indicates that {@link AsyncTask#onPostExecute} has finished. */ FINISHED, } /** @hide Used to force static handler to be created. */ public static void init() { sHandler.getLooper(); } /** @hide */ public static void setDefaultExecutor(Executor exec) { sDefaultExecutor = exec; } /** * Creates a new asynchronous task. This constructor must be invoked on the UI thread. */ public AsyncTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { mTaskInvoked.set(true); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); //noinspection unchecked return postResult(doInBackground(mParams)); } }; mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { try { postResultIfNotInvoked(get()); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch (ExecutionException e) { throw new RuntimeException("An error occured while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } }; } private void postResultIfNotInvoked(Result result) { final boolean wasTaskInvoked = mTaskInvoked.get(); if (!wasTaskInvoked) { postResult(result); } } private Result postResult(Result result) { @SuppressWarnings("unchecked") Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(this, result)); message.sendToTarget(); return result; } /** * Returns the current status of this task. * * @return The current status. */ public final Status getStatus() { return mStatus; } /** * Override this method to perform a computation on a background thread. The * specified parameters are the parameters passed to {@link #execute} * by the caller of this task. * * This method can call {@link #publishProgress} to publish updates * on the UI thread. * * @param params The parameters of the task. * * @return A result, defined by the subclass of this task. * * @see #onPreExecute() * @see #onPostExecute * @see #publishProgress */ protected abstract Result doInBackground(Params... params); /** * Runs on the UI thread before {@link #doInBackground}. * * @see #onPostExecute * @see #doInBackground */ protected void onPreExecute() { } /** * <p>Runs on the UI thread after {@link #doInBackground}. The * specified result is the value returned by {@link #doInBackground}.</p> * * <p>This method won't be invoked if the task was cancelled.</p> * * @param result The result of the operation computed by {@link #doInBackground}. * * @see #onPreExecute * @see #doInBackground * @see #onCancelled(Object) */ @SuppressWarnings({"UnusedDeclaration"}) protected void onPostExecute(Result result) { } /** * Runs on the UI thread after {@link #publishProgress} is invoked. * The specified values are the values passed to {@link #publishProgress}. * * @param values The values indicating progress. * * @see #publishProgress * @see #doInBackground */ @SuppressWarnings({"UnusedDeclaration"}) protected void onProgressUpdate(Progress... values) { } /** * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and * {@link #doInBackground(Object[])} has finished.</p> * * <p>The default implementation simply invokes {@link #onCancelled()} and * ignores the result. If you write your own implementation, do not call * <code>super.onCancelled(result)</code>.</p> * * @param result The result, if any, computed in * {@link #doInBackground(Object[])}, can be null * * @see #cancel(boolean) * @see #isCancelled() */ @SuppressWarnings({"UnusedParameters"}) protected void onCancelled(Result result) { onCancelled(); } /** * <p>Applications should preferably override {@link #onCancelled(Object)}. * This method is invoked by the default implementation of * {@link #onCancelled(Object)}.</p> * * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and * {@link #doInBackground(Object[])} has finished.</p> * * @see #onCancelled(Object) * @see #cancel(boolean) * @see #isCancelled() */ protected void onCancelled() { } /** * Returns <tt>true</tt> if this task was cancelled before it completed * normally. If you are calling {@link #cancel(boolean)} on the task, * the value returned by this method should be checked periodically from * {@link #doInBackground(Object[])} to end the task as soon as possible. * * @return <tt>true</tt> if task was cancelled before it completed * * @see #cancel(boolean) */ public final boolean isCancelled() { return mCancelled.get(); } /** * <p>Attempts to cancel execution of this task. This attempt will * fail if the task has already completed, already been cancelled, * or could not be cancelled for some other reason. If successful, * and this task has not started when <tt>cancel</tt> is called, * this task should never run. If the task has already started, * then the <tt>mayInterruptIfRunning</tt> parameter determines * whether the thread executing this task should be interrupted in * an attempt to stop the task.</p> * * <p>Calling this method will result in {@link #onCancelled(Object)} being * invoked on the UI thread after {@link #doInBackground(Object[])} * returns. Calling this method guarantees that {@link #onPostExecute(Object)} * is never invoked. After invoking this method, you should check the * value returned by {@link #isCancelled()} periodically from * {@link #doInBackground(Object[])} to finish the task as early as * possible.</p> * * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this * task should be interrupted; otherwise, in-progress tasks are allowed * to complete. * * @return <tt>false</tt> if the task could not be cancelled, * typically because it has already completed normally; * <tt>true</tt> otherwise * * @see #isCancelled() * @see #onCancelled(Object) */ public final boolean cancel(boolean mayInterruptIfRunning) { mCancelled.set(true); return mFuture.cancel(mayInterruptIfRunning); } /** * Waits if necessary for the computation to complete, and then * retrieves its result. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. */ public final Result get() throws InterruptedException, ExecutionException { return mFuture.get(); } /** * Waits if necessary for at most the given time for the computation * to complete, and then retrieves its result. * * @param timeout Time to wait before cancelling the operation. * @param unit The time unit for the timeout. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. * @throws TimeoutException If the wait timed out. */ public final Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return mFuture.get(timeout, unit); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * <p>Note: this function schedules the task on a queue for a single background * thread or pool of threads depending on the platform version. When first * introduced, AsyncTasks were executed serially on a single background thread. * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed * to a pool of threads allowing multiple tasks to operate in parallel. Starting * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being * executed on a single thread to avoid common application errors caused * by parallel execution. If you truly want parallel execution, you can use * the {@link #executeOnExecutor} version of this method * with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings * on its use. * * <p>This method must be invoked on the UI thread. * * @param params The parameters of the task. * * @return This instance of AsyncTask. * * @throws IllegalStateException If {@link #getStatus()} returns either * {@link Status#RUNNING} or {@link Status#FINISHED}. * * @see #executeOnExecutor(Executor, Object[]) * @see #execute(Runnable) */ public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to * allow multiple tasks to run in parallel on a pool of threads managed by * AsyncTask, however you can also use your own {@link Executor} for custom * behavior. * * <p><em>Warning:</em> Allowing multiple tasks to run in parallel from * a thread pool is generally <em>not</em> what one wants, because the order * of their operation is not defined. For example, if these tasks are used * to modify any state in common (such as writing a file due to a button click), * there are no guarantees on the order of the modifications. * Without careful work it is possible in rare cases for the newer version * of the data to be over-written by an older one, leading to obscure data * loss and stability issues. Such changes are best * executed in serial; to guarantee such work is serialized regardless of * platform version you can use this function with {@link #SERIAL_EXECUTOR}. * * <p>This method must be invoked on the UI thread. * * @param exec The executor to use. {@link #THREAD_POOL_EXECUTOR} is available as a * convenient process-wide thread pool for tasks that are loosely coupled. * @param params The parameters of the task. * * @return This instance of AsyncTask. * * @throws IllegalStateException If {@link #getStatus()} returns either * {@link Status#RUNNING} or {@link Status#FINISHED}. * * @see #execute(Object[]) */ public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params) { if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: throw new IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED: throw new IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); } } mStatus = Status.RUNNING; onPreExecute(); mWorker.mParams = params; exec.execute(mFuture); return this; } /** * Convenience version of {@link #execute(Object...)} for use with * a simple Runnable object. See {@link #execute(Object[])} for more * information on the order of execution. * * @see #execute(Object[]) * @see #executeOnExecutor(Executor, Object[]) */ public static void execute(Runnable runnable) { sDefaultExecutor.execute(runnable); } /** * This method can be invoked from {@link #doInBackground} to * publish updates on the UI thread while the background computation is * still running. Each call to this method will trigger the execution of * {@link #onProgressUpdate} on the UI thread. * * {@link #onProgressUpdate} will note be called if the task has been * canceled. * * @param values The progress values to update the UI with. * * @see #onProgressUpdate * @see #doInBackground */ protected final void publishProgress(Progress... values) { if (!isCancelled()) { sHandler.obtainMessage(MESSAGE_POST_PROGRESS, new AsyncTaskResult<Progress>(this, values)).sendToTarget(); } } private void finish(Result result) { if (isCancelled()) { onCancelled(result); } else { onPostExecute(result); } mStatus = Status.FINISHED; } private static class InternalHandler extends Handler { @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override public void handleMessage(Message msg) { AsyncTaskResult result = (AsyncTaskResult) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS: result.mTask.onProgressUpdate(result.mData); break; } } } private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { Params[] mParams; } @SuppressWarnings({"RawUseOfParameterizedType"}) private static class AsyncTaskResult<Data> { final AsyncTask mTask; final Data[] mData; AsyncTaskResult(AsyncTask task, Data... data) { mTask = task; mData = data; } } }
/* * Copyright (c) 2006-2017 DMDirc Developers * * 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.dmdirc.util.collections; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import javax.annotation.Nonnull; /** * Decorates a {@link List} to add observable functionality. * * @param <T> The type of object the list contains */ public class ObservableListDecorator<T> implements ObservableList<T> { /** The list being decorated. */ private final List<T> list; /** The listeners for this list. */ private final ListenerList listeners = new ListenerList(); /** * Creates a new {@link ObservableListDecorator} which will decorate the * given list. * * @param list The list to be decorated */ @SuppressWarnings("AssignmentToCollectionOrArrayFieldFromParameter") public ObservableListDecorator(final List<T> list) { this.list = list; } @Override public void addListListener(final ListObserver listener) { listeners.add(ListObserver.class, listener); } @Override public void removeListListener(final ListObserver listener) { listeners.remove(ListObserver.class, listener); } @Override public int size() { return list.size(); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public boolean contains(final Object o) { return list.contains(o); } @Nonnull @Override public Iterator<T> iterator() { return list.iterator(); } @Nonnull @Override public Object[] toArray() { return list.toArray(); } @Nonnull @Override public <S> S[] toArray(@Nonnull final S[] a) { return list.toArray(a); } @Override public boolean add(final T e) { list.add(e); listeners.getCallable(ListObserver.class).onItemsAdded(this, list.size() - 1, list.size() - 1); return true; } @Override public boolean remove(final Object o) { final int index = list.indexOf(o); if (list.remove(o)) { listeners.getCallable(ListObserver.class).onItemsRemoved(this, index, index); return true; } return false; } @Override public boolean containsAll(@Nonnull final Collection<?> c) { return list.containsAll(c); } @Override public boolean addAll(@Nonnull final Collection<? extends T> c) { if (list.addAll(c)) { listeners.getCallable(ListObserver.class).onItemsAdded(this, list.size() - c.size(), list.size() - 1); return true; } return false; } @Override public boolean addAll(final int index, @Nonnull final Collection<? extends T> c) { if (list.addAll(index, c)) { listeners.getCallable(ListObserver.class).onItemsAdded(this, index, index + c.size()); return true; } return false; } @Override public boolean removeAll(@Nonnull final Collection<?> c) { final int length = list.size(); if (list.removeAll(c)) { listeners.getCallable(ListObserver.class).onItemsChanged(this, 0, length - 1); return true; } return false; } @Override public boolean retainAll(@Nonnull final Collection<?> c) { final int length = list.size(); if (list.retainAll(c)) { listeners.getCallable(ListObserver.class).onItemsChanged(this, 0, length - 1); return true; } return false; } @Override public void clear() { final int length = list.size(); list.clear(); if (length > 0) { listeners.getCallable(ListObserver.class).onItemsRemoved(this, 0, length - 1); } } @Override public T get(final int index) { return list.get(index); } @Override public T set(final int index, final T element) { final T res = list.set(index, element); listeners.getCallable(ListObserver.class).onItemsChanged(this, index, index); return res; } @Override public void add(final int index, final T element) { list.add(index, element); listeners.getCallable(ListObserver.class).onItemsAdded(this, index, index); } @Override public T remove(final int index) { final T res = list.remove(index); listeners.getCallable(ListObserver.class).onItemsRemoved(this, index, index); return res; } @Override public int indexOf(final Object o) { return list.indexOf(o); } @Override public int lastIndexOf(final Object o) { return list.lastIndexOf(o); } @Nonnull @Override public ListIterator<T> listIterator() { return list.listIterator(); } @Nonnull @Override public ListIterator<T> listIterator(final int index) { return list.listIterator(index); } @Nonnull @Override public List<T> subList(final int fromIndex, final int toIndex) { return list.subList(fromIndex, toIndex); } }
package org.drip.sample.credithistorical; import java.util.*; import org.drip.analytics.date.JulianDate; import org.drip.feed.loader.*; import org.drip.historical.state.CreditCurveMetrics; import org.drip.service.env.EnvManager; import org.drip.service.state.CreditCurveAPI; /* * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /*! * Copyright (C) 2017 Lakshmi Krishnamurthy * Copyright (C) 2016 Lakshmi Krishnamurthy * * This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model * libraries targeting analysts and developers * https://lakshmidrip.github.io/DRIP/ * * DRIP is composed of four main libraries: * * - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/ * - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/ * - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/ * - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/ * * - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options, * Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA * Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV * Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM * Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics. * * - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy * Incorporator, Holdings Constraint, and Transaction Costs. * * - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality. * * - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ /** * CDXNAIGS165YMetrics generates the Historical Credit Survival/Recovery Metrics for the Index Contract CDX * NA IG S16 5Y. * * @author Lakshmi Krishnamurthy */ public class CDXNAIGS165YMetrics { public static final void main ( final String[] astrArgs) throws Exception { EnvManager.InitEnv (""); int iSeries = 16; String strClosesLocation = "C:\\DRIP\\CreditAnalytics\\Daemons\\Transforms\\CreditCDXMarks\\CDXNAIGS" + iSeries + "5YReconstitutor.csv"; String[] astrForTenor = new String[] { "1Y", "2Y", "3Y", "4Y", "5Y", "6Y", "7Y", "8Y", "9Y", "10Y", "11Y", "12Y", "15Y", "20Y", "25Y", }; String[] astrFundingFixingMaturityTenor = new String[] { "1Y", "2Y", "3Y", "4Y", "5Y", "6Y", "7Y", "8Y", "9Y", "10Y", "11Y", "12Y", "15Y", "20Y", "25Y", "30Y", "40Y", "50Y" }; CSVGrid csvGrid = CSVParser.StringGrid ( strClosesLocation, true ); JulianDate[] adtClose = csvGrid.dateArrayAtColumn (0); double[] adblFundingFixingQuote1Y = csvGrid.doubleArrayAtColumn (1); double[] adblFundingFixingQuote2Y = csvGrid.doubleArrayAtColumn (2); double[] adblFundingFixingQuote3Y = csvGrid.doubleArrayAtColumn (3); double[] adblFundingFixingQuote4Y = csvGrid.doubleArrayAtColumn (4); double[] adblFundingFixingQuote5Y = csvGrid.doubleArrayAtColumn (5); double[] adblFundingFixingQuote6Y = csvGrid.doubleArrayAtColumn (6); double[] adblFundingFixingQuote7Y = csvGrid.doubleArrayAtColumn (7); double[] adblFundingFixingQuote8Y = csvGrid.doubleArrayAtColumn (8); double[] adblFundingFixingQuote9Y = csvGrid.doubleArrayAtColumn (9); double[] adblFundingFixingQuote10Y = csvGrid.doubleArrayAtColumn (10); double[] adblFundingFixingQuote11Y = csvGrid.doubleArrayAtColumn (11); double[] adblFundingFixingQuote12Y = csvGrid.doubleArrayAtColumn (12); double[] adblFundingFixingQuote15Y = csvGrid.doubleArrayAtColumn (13); double[] adblFundingFixingQuote20Y = csvGrid.doubleArrayAtColumn (14); double[] adblFundingFixingQuote25Y = csvGrid.doubleArrayAtColumn (15); double[] adblFundingFixingQuote30Y = csvGrid.doubleArrayAtColumn (16); double[] adblFundingFixingQuote40Y = csvGrid.doubleArrayAtColumn (17); double[] adblFundingFixingQuote50Y = csvGrid.doubleArrayAtColumn (18); String[] astrFullCreditIndexName = csvGrid.stringArrayAtColumn (19); double[] adblCreditIndexQuotedSpread = csvGrid.doubleArrayAtColumn (20); int iNumClose = adtClose.length; JulianDate[] adtSpot = new JulianDate[iNumClose]; double[][] aadblFundingFixingQuote = new double[iNumClose][18]; for (int i = 0; i < iNumClose; ++i) { adtSpot[i] = adtClose[i]; aadblFundingFixingQuote[i][0] = adblFundingFixingQuote1Y[i]; aadblFundingFixingQuote[i][1] = adblFundingFixingQuote2Y[i]; aadblFundingFixingQuote[i][2] = adblFundingFixingQuote3Y[i]; aadblFundingFixingQuote[i][3] = adblFundingFixingQuote4Y[i]; aadblFundingFixingQuote[i][4] = adblFundingFixingQuote5Y[i]; aadblFundingFixingQuote[i][5] = adblFundingFixingQuote6Y[i]; aadblFundingFixingQuote[i][6] = adblFundingFixingQuote7Y[i]; aadblFundingFixingQuote[i][7] = adblFundingFixingQuote8Y[i]; aadblFundingFixingQuote[i][8] = adblFundingFixingQuote9Y[i]; aadblFundingFixingQuote[i][9] = adblFundingFixingQuote10Y[i]; aadblFundingFixingQuote[i][10] = adblFundingFixingQuote11Y[i]; aadblFundingFixingQuote[i][11] = adblFundingFixingQuote12Y[i]; aadblFundingFixingQuote[i][12] = adblFundingFixingQuote15Y[i]; aadblFundingFixingQuote[i][13] = adblFundingFixingQuote20Y[i]; aadblFundingFixingQuote[i][14] = adblFundingFixingQuote25Y[i]; aadblFundingFixingQuote[i][15] = adblFundingFixingQuote30Y[i]; aadblFundingFixingQuote[i][16] = adblFundingFixingQuote40Y[i]; aadblFundingFixingQuote[i][17] = adblFundingFixingQuote50Y[i]; adblCreditIndexQuotedSpread[i] *= 10000.; } int i = 0; String strDump = "Date,QuotedSpread"; for (String strForTenor : astrForTenor) strDump += ",SURVIVAL::" + strForTenor + ",RECOVERY::" + strForTenor; System.out.println (strDump); TreeMap<JulianDate, CreditCurveMetrics> mapCCM = CreditCurveAPI.HorizonMetrics ( adtSpot, astrFundingFixingMaturityTenor, aadblFundingFixingQuote, astrFullCreditIndexName, adblCreditIndexQuotedSpread, astrForTenor ); Set<JulianDate> setSpotDate = mapCCM.keySet(); for (JulianDate dtSpot : setSpotDate) { strDump = dtSpot.toString() + "," + adblCreditIndexQuotedSpread[i++]; CreditCurveMetrics ccmSpot = mapCCM.get (dtSpot); for (String strForTenor : astrForTenor) { JulianDate dtFor = dtSpot.addTenor (strForTenor); strDump += "," + ccmSpot.survivalProbability (dtFor) + "," + ccmSpot.recoveryRate (dtFor); } System.out.println (strDump); } } }
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.runtime; import com.google.common.base.Preconditions; import com.google.common.collect.Comparators; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.google.common.eventbus.AllowConcurrentEvents; import com.google.common.eventbus.Subscribe; import com.google.common.flogger.GoogleLogger; import com.google.common.flogger.StackSize; import com.google.devtools.build.lib.actions.Action; import com.google.devtools.build.lib.actions.ActionAnalysisMetadata; import com.google.devtools.build.lib.actions.ActionCompletionEvent; import com.google.devtools.build.lib.actions.ActionKeyContext; import com.google.devtools.build.lib.actions.ActionMiddlemanEvent; import com.google.devtools.build.lib.actions.ActionRewoundEvent; import com.google.devtools.build.lib.actions.ActionStartedEvent; import com.google.devtools.build.lib.actions.Actions; import com.google.devtools.build.lib.actions.AggregatedSpawnMetrics; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.CachedActionEvent; import com.google.devtools.build.lib.actions.DiscoveredInputsEvent; import com.google.devtools.build.lib.actions.SpawnExecutedEvent; import com.google.devtools.build.lib.actions.SpawnMetrics; import com.google.devtools.build.lib.actions.SpawnResult; import com.google.devtools.build.lib.clock.Clock; import java.time.Duration; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BinaryOperator; import java.util.stream.Stream; import javax.annotation.concurrent.ThreadSafe; /** * Computes the critical path in the action graph based on events published to the event bus. * * <p>After instantiation, this object needs to be registered on the event bus to work. */ @ThreadSafe public class CriticalPathComputer { private static final GoogleLogger logger = GoogleLogger.forEnclosingClass(); /** Number of top actions to record. */ static final int SLOWEST_COMPONENTS_SIZE = 30; private static final int LARGEST_MEMORY_COMPONENTS_SIZE = 20; private static final int LARGEST_INPUT_SIZE_COMPONENTS_SIZE = 20; /** Selects and returns the longer of two components (the first may be {@code null}). */ private static final BinaryOperator<CriticalPathComponent> SELECT_LONGER_COMPONENT = (a, b) -> a == null || a.getAggregatedElapsedTime().compareTo(b.getAggregatedElapsedTime()) < 0 ? b : a; private final AtomicInteger idGenerator = new AtomicInteger(); // outputArtifactToComponent is accessed from multiple event handlers. private final ConcurrentMap<Artifact, CriticalPathComponent> outputArtifactToComponent = Maps.newConcurrentMap(); private final ActionKeyContext actionKeyContext; /** Maximum critical path found. */ private final AtomicReference<CriticalPathComponent> maxCriticalPath; private final Clock clock; private final boolean checkCriticalPathInconsistencies; public CriticalPathComputer( ActionKeyContext actionKeyContext, Clock clock, boolean checkCriticalPathInconsistencies) { this.actionKeyContext = actionKeyContext; this.clock = clock; maxCriticalPath = new AtomicReference<>(); this.checkCriticalPathInconsistencies = checkCriticalPathInconsistencies; } public CriticalPathComputer(ActionKeyContext actionKeyContext, Clock clock) { this(actionKeyContext, clock, /*checkCriticalPathInconsistencies=*/ true); } /** * Creates a critical path component for an action. * * @param action the action for the critical path component * @param relativeStartNanos time when the action started to run in nanos. Only meant to be used * for computing time differences. */ private CriticalPathComponent createComponent(Action action, long relativeStartNanos) { return new CriticalPathComponent(idGenerator.getAndIncrement(), action, relativeStartNanos); } /** * Return the critical path stats for the current command execution. * * <p>This method allows us to calculate lazily the aggregate statistics of the critical path, * avoiding the memory and cpu penalty for doing it for all the actions executed. */ public AggregatedCriticalPath aggregate() { CriticalPathComponent criticalPath = getMaxCriticalPath(); if (criticalPath == null) { return AggregatedCriticalPath.EMPTY; } ImmutableList.Builder<CriticalPathComponent> components = ImmutableList.builder(); AggregatedSpawnMetrics.Builder metricsBuilder = new AggregatedSpawnMetrics.Builder(); CriticalPathComponent child = criticalPath; while (child != null) { AggregatedSpawnMetrics childSpawnMetrics = child.getSpawnMetrics(); if (childSpawnMetrics != null) { metricsBuilder.addDurations(childSpawnMetrics); metricsBuilder.addNonDurations(childSpawnMetrics); } components.add(child); child = child.getChild(); } return new AggregatedCriticalPath( criticalPath.getAggregatedElapsedTime(), metricsBuilder.build(), components.build()); } public Map<Artifact, CriticalPathComponent> getCriticalPathComponentsMap() { return outputArtifactToComponent; } /** Changes the phase of the action */ @Subscribe @AllowConcurrentEvents public void nextCriticalPathPhase(SpawnExecutedEvent.ChangePhase phase) { CriticalPathComponent stats = outputArtifactToComponent.get(phase.getAction().getPrimaryOutput()); if (stats != null) { stats.changePhase(); } } /** Adds spawn metrics to the action stats. */ @Subscribe @AllowConcurrentEvents public void spawnExecuted(SpawnExecutedEvent event) { ActionAnalysisMetadata action = event.getActionMetadata(); Artifact primaryOutput = action.getPrimaryOutput(); if (primaryOutput == null) { // Despite the documentation to the contrary, the SpawnIncludeScanner creates an // ActionExecutionMetadata instance that returns a null primary output. That said, this // class is incorrect wrt. multiple Spawns in a single action. See b/111583707. return; } CriticalPathComponent stats = Preconditions.checkNotNull(outputArtifactToComponent.get(primaryOutput)); SpawnResult spawnResult = event.getSpawnResult(); stats.addSpawnResult( spawnResult.getMetrics(), spawnResult.getRunnerName(), spawnResult.getRunnerSubtype(), spawnResult.wasRemote()); } /** Returns the list of components using the most memory. */ public List<CriticalPathComponent> getLargestMemoryComponents() { return uniqueActions() .collect( Comparators.greatest( LARGEST_MEMORY_COMPONENTS_SIZE, Comparator.comparingLong( (c) -> c.getSpawnMetrics().getMaxNonDuration(0, SpawnMetrics::memoryEstimate)))); } /** Returns the list of components with the largest input sizes. */ public List<CriticalPathComponent> getLargestInputSizeComponents() { return uniqueActions() .collect( Comparators.greatest( LARGEST_INPUT_SIZE_COMPONENTS_SIZE, Comparator.comparingLong( (c) -> c.getSpawnMetrics().getMaxNonDuration(0, SpawnMetrics::inputBytes)))); } /** Returns the list of slowest components. */ public List<CriticalPathComponent> getSlowestComponents() { return uniqueActions() .collect( Comparators.greatest( SLOWEST_COMPONENTS_SIZE, Comparator.comparingLong(CriticalPathComponent::getElapsedTimeNanos))); } private Stream<CriticalPathComponent> uniqueActions() { return outputArtifactToComponent.entrySet().stream() .filter((e) -> e.getValue().isPrimaryOutput(e.getKey())) .map((e) -> e.getValue()); } /** Creates a CriticalPathComponent and adds the duration of input discovery and changes phase. */ @Subscribe @AllowConcurrentEvents public void discoverInputs(DiscoveredInputsEvent event) throws InterruptedException { CriticalPathComponent stats = tryAddComponent(createComponent(event.getAction(), event.getStartTimeNanos())); stats.addSpawnResult(event.getMetrics(), null, "", /* wasRemote=*/ false); stats.changePhase(); } /** * Record an action that has started to run. If the CriticalPathComponent has not been created, * initialize it and then start running. * * @param event information about the started action */ @Subscribe @AllowConcurrentEvents public void actionStarted(ActionStartedEvent event) throws InterruptedException { Action action = event.getAction(); tryAddComponent(createComponent(action, event.getNanoTimeStart())).startRunning(); } /** * Record a middleman action execution. Even if middleman are almost instant, we record them * because they depend on other actions and we need them for constructing the critical path. * * <p>For some rules with incorrect configuration transitions we might get notified several times * for the same middleman. This should only happen if the actions are shared. */ @Subscribe @AllowConcurrentEvents public void middlemanAction(ActionMiddlemanEvent event) throws InterruptedException { Action action = event.getAction(); CriticalPathComponent component = tryAddComponent(createComponent(action, event.getNanoTimeStart())); finalizeActionStat(event.getNanoTimeStart(), action, component); } /** * Try to add the component to the map of critical path components. If there is an existing * component for its primary output it uses that to update the rest of the outputs. * * @return The component to be used for updating the time stats. */ @SuppressWarnings("ReferenceEquality") private CriticalPathComponent tryAddComponent(CriticalPathComponent newComponent) throws InterruptedException { Action newAction = newComponent.getAction(); Artifact primaryOutput = newAction.getPrimaryOutput(); CriticalPathComponent storedComponent = outputArtifactToComponent.putIfAbsent(primaryOutput, newComponent); if (storedComponent != null) { Action oldAction = storedComponent.getAction(); // TODO(b/120663721) Replace this fragile reference equality check with something principled. if (oldAction != newAction && !Actions.canBeShared(actionKeyContext, newAction, oldAction)) { throw new IllegalStateException( "Duplicate output artifact found for unsharable actions." + "This can happen if a previous event registered the action.\n" + "Old action: " + oldAction + "\n\nNew action: " + newAction + "\n\nArtifact: " + primaryOutput + "\n"); } } else { storedComponent = newComponent; } // Try to insert the existing component for the rest of the outputs even if we failed to be // the ones inserting the component so that at the end of this method we guarantee that all the // outputs have a component. for (Artifact output : newAction.getOutputs()) { if (output == primaryOutput) { continue; } CriticalPathComponent old = outputArtifactToComponent.putIfAbsent(output, storedComponent); // If two actions run concurrently maybe we find a component by primary output but we are // the first updating the rest of the outputs. Preconditions.checkState( old == null || old == storedComponent, "Inconsistent state for %s", newAction); } return storedComponent; } /** * Record an action that was not executed because it was in the (disk) cache. This is needed so * that we can calculate correctly the dependencies tree if we have some cached actions in the * middle of the critical path. */ @Subscribe @AllowConcurrentEvents public void actionCached(CachedActionEvent event) throws InterruptedException { Action action = event.getAction(); CriticalPathComponent component = tryAddComponent(createComponent(action, event.getNanoTimeStart())); finalizeActionStat(event.getNanoTimeStart(), action, component); } /** * Records the elapsed time stats for the action. For each input artifact, it finds the real * dependent artifacts and records the critical path stats. */ @Subscribe @AllowConcurrentEvents public void actionComplete(ActionCompletionEvent event) { Action action = event.getAction(); CriticalPathComponent component = Preconditions.checkNotNull( outputArtifactToComponent.get(action.getPrimaryOutput()), action); finalizeActionStat(event.getRelativeActionStartTime(), action, component); } /** * Record that the failed rewound action is no longer running. The action may or may not start * again later. */ @Subscribe @AllowConcurrentEvents public void actionRewound(ActionRewoundEvent event) { Action action = event.getFailedRewoundAction(); CriticalPathComponent component = Preconditions.checkNotNull(outputArtifactToComponent.get(action.getPrimaryOutput())); component.finishActionExecution(event.getRelativeActionStartTime(), clock.nanoTime()); } /** Maximum critical path component found during the build. */ protected CriticalPathComponent getMaxCriticalPath() { return maxCriticalPath.get(); } private void finalizeActionStat( long startTimeNanos, Action action, CriticalPathComponent component) { long finishTimeNanos = clock.nanoTime(); for (Artifact input : action.getInputs().toList()) { addArtifactDependency(component, input, finishTimeNanos); } if (Duration.ofNanos(finishTimeNanos - startTimeNanos).compareTo(Duration.ofMillis(-5)) < 0) { // See note in {@link Clock#nanoTime} about non increasing subsequent #nanoTime calls. logger.atWarning().withStackTrace(StackSize.MEDIUM).log( "Negative duration time for [%s] %s with start: %s, finish: %s.", action.getMnemonic(), action.getPrimaryOutput(), startTimeNanos, finishTimeNanos); } component.finishActionExecution(startTimeNanos, finishTimeNanos); maxCriticalPath.accumulateAndGet(component, SELECT_LONGER_COMPONENT); } /** If "input" is a generated artifact, link its critical path to the one we're building. */ private void addArtifactDependency( CriticalPathComponent actionStats, Artifact input, long componentFinishNanos) { CriticalPathComponent depComponent = outputArtifactToComponent.get(input); if (depComponent != null) { if (depComponent.isRunning()) { checkCriticalPathInconsistency( (Artifact.DerivedArtifact) input, depComponent.getAction(), actionStats); return; } actionStats.addDepInfo(depComponent, componentFinishNanos); } } private void checkCriticalPathInconsistency( Artifact.DerivedArtifact input, Action dependencyAction, CriticalPathComponent actionStats) { if (!checkCriticalPathInconsistencies) { return; } // Rare case that an action depending on a previously-cached shared action sees a different // shared action that is in the midst of being an action cache hit. for (Artifact actionOutput : dependencyAction.getOutputs()) { if (input.equals(actionOutput) && input .getGeneratingActionKey() .equals(((Artifact.DerivedArtifact) actionOutput).getGeneratingActionKey())) { // This (currently running) dependency action is the same action that produced the input for // the finished actionStats CriticalPathComponent. This should be impossible. throw new IllegalStateException( String.format( "Cannot add critical path stats when the dependency action is not finished. " + "%s. %s. %s.", input, actionStats.prettyPrintAction(), dependencyAction)); } } } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.sql.planner; import com.facebook.presto.block.BlockSerdeUtil; import com.facebook.presto.metadata.FunctionRegistry; import com.facebook.presto.metadata.Signature; import com.facebook.presto.operator.scalar.VarbinaryFunctions; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.block.BlockEncodingSerde; import com.facebook.presto.spi.type.CharType; import com.facebook.presto.spi.type.DecimalType; import com.facebook.presto.spi.type.Decimals; import com.facebook.presto.spi.type.SqlDate; import com.facebook.presto.spi.type.StandardTypes; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.VarcharType; import com.facebook.presto.sql.tree.ArithmeticUnaryExpression; import com.facebook.presto.sql.tree.BooleanLiteral; import com.facebook.presto.sql.tree.Cast; import com.facebook.presto.sql.tree.DecimalLiteral; import com.facebook.presto.sql.tree.DoubleLiteral; import com.facebook.presto.sql.tree.Expression; import com.facebook.presto.sql.tree.FunctionCall; import com.facebook.presto.sql.tree.GenericLiteral; import com.facebook.presto.sql.tree.LongLiteral; import com.facebook.presto.sql.tree.NullLiteral; import com.facebook.presto.sql.tree.QualifiedName; import com.facebook.presto.sql.tree.StringLiteral; import com.google.common.collect.ImmutableList; import com.google.common.primitives.Primitives; import io.airlift.slice.DynamicSliceOutput; import io.airlift.slice.Slice; import io.airlift.slice.SliceOutput; import io.airlift.slice.SliceUtf8; import java.util.List; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.DateType.DATE; import static com.facebook.presto.spi.type.Decimals.isShortDecimal; import static com.facebook.presto.spi.type.DoubleType.DOUBLE; import static com.facebook.presto.spi.type.IntegerType.INTEGER; import static com.facebook.presto.spi.type.RealType.REAL; import static com.facebook.presto.type.UnknownType.UNKNOWN; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.Float.intBitsToFloat; import static java.lang.Math.toIntExact; import static java.util.Objects.requireNonNull; public final class LiteralEncoder { private final BlockEncodingSerde blockEncodingSerde; public LiteralEncoder(BlockEncodingSerde blockEncodingSerde) { this.blockEncodingSerde = requireNonNull(blockEncodingSerde, "blockEncodingSerde is null"); } public List<Expression> toExpressions(List<?> objects, List<? extends Type> types) { requireNonNull(objects, "objects is null"); requireNonNull(types, "types is null"); checkArgument(objects.size() == types.size(), "objects and types do not have the same size"); ImmutableList.Builder<Expression> expressions = ImmutableList.builder(); for (int i = 0; i < objects.size(); i++) { Object object = objects.get(i); Type type = types.get(i); expressions.add(toExpression(object, type)); } return expressions.build(); } public Expression toExpression(Object object, Type type) { requireNonNull(type, "type is null"); if (object instanceof Expression) { return (Expression) object; } if (object == null) { if (type.equals(UNKNOWN)) { return new NullLiteral(); } return new Cast(new NullLiteral(), type.getTypeSignature().toString(), false, true); } if (type.equals(INTEGER)) { return new LongLiteral(object.toString()); } if (type.equals(BIGINT)) { LongLiteral expression = new LongLiteral(object.toString()); if (expression.getValue() >= Integer.MIN_VALUE && expression.getValue() <= Integer.MAX_VALUE) { return new GenericLiteral("BIGINT", object.toString()); } return new LongLiteral(object.toString()); } checkArgument(Primitives.wrap(type.getJavaType()).isInstance(object), "object.getClass (%s) and type.getJavaType (%s) do not agree", object.getClass(), type.getJavaType()); if (type.equals(DOUBLE)) { Double value = (Double) object; // WARNING: the ORC predicate code depends on NaN and infinity not appearing in a tuple domain, so // if you remove this, you will need to update the TupleDomainOrcPredicate // When changing this, don't forget about similar code for REAL below if (value.isNaN()) { return new FunctionCall(QualifiedName.of("nan"), ImmutableList.of()); } if (value.equals(Double.NEGATIVE_INFINITY)) { return ArithmeticUnaryExpression.negative(new FunctionCall(QualifiedName.of("infinity"), ImmutableList.of())); } if (value.equals(Double.POSITIVE_INFINITY)) { return new FunctionCall(QualifiedName.of("infinity"), ImmutableList.of()); } return new DoubleLiteral(object.toString()); } if (type.equals(REAL)) { Float value = intBitsToFloat(((Long) object).intValue()); // WARNING for ORC predicate code as above (for double) if (value.isNaN()) { return new Cast(new FunctionCall(QualifiedName.of("nan"), ImmutableList.of()), StandardTypes.REAL); } if (value.equals(Float.NEGATIVE_INFINITY)) { return ArithmeticUnaryExpression.negative(new Cast(new FunctionCall(QualifiedName.of("infinity"), ImmutableList.of()), StandardTypes.REAL)); } if (value.equals(Float.POSITIVE_INFINITY)) { return new Cast(new FunctionCall(QualifiedName.of("infinity"), ImmutableList.of()), StandardTypes.REAL); } return new GenericLiteral("REAL", value.toString()); } if (type instanceof DecimalType) { String string; if (isShortDecimal(type)) { string = Decimals.toString((long) object, ((DecimalType) type).getScale()); } else { string = Decimals.toString((Slice) object, ((DecimalType) type).getScale()); } return new Cast(new DecimalLiteral(string), type.getDisplayName()); } if (type instanceof VarcharType) { VarcharType varcharType = (VarcharType) type; Slice value = (Slice) object; StringLiteral stringLiteral = new StringLiteral(value.toStringUtf8()); if (!varcharType.isUnbounded() && varcharType.getLengthSafe() == SliceUtf8.countCodePoints(value)) { return stringLiteral; } return new Cast(stringLiteral, type.getDisplayName(), false, true); } if (type instanceof CharType) { StringLiteral stringLiteral = new StringLiteral(((Slice) object).toStringUtf8()); return new Cast(stringLiteral, type.getDisplayName(), false, true); } if (type.equals(BOOLEAN)) { return new BooleanLiteral(object.toString()); } if (type.equals(DATE)) { return new GenericLiteral("DATE", new SqlDate(toIntExact((Long) object)).toString()); } if (object instanceof Block) { SliceOutput output = new DynamicSliceOutput(toIntExact(((Block) object).getSizeInBytes())); BlockSerdeUtil.writeBlock(blockEncodingSerde, output, (Block) object); object = output.slice(); // This if condition will evaluate to true: object instanceof Slice && !type.equals(VARCHAR) } if (object instanceof Slice) { // HACK: we need to serialize VARBINARY in a format that can be embedded in an expression to be // able to encode it in the plan that gets sent to workers. // We do this by transforming the in-memory varbinary into a call to from_base64(<base64-encoded value>) FunctionCall fromBase64 = new FunctionCall(QualifiedName.of("from_base64"), ImmutableList.of(new StringLiteral(VarbinaryFunctions.toBase64((Slice) object).toStringUtf8()))); Signature signature = FunctionRegistry.getMagicLiteralFunctionSignature(type); return new FunctionCall(QualifiedName.of(signature.getName()), ImmutableList.of(fromBase64)); } Signature signature = FunctionRegistry.getMagicLiteralFunctionSignature(type); Expression rawLiteral = toExpression(object, FunctionRegistry.typeForMagicLiteral(type)); return new FunctionCall(QualifiedName.of(signature.getName()), ImmutableList.of(rawLiteral)); } }
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** 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 ETH Zurich 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 javaImportTool; import java.util.HashMap; import java.util.Map; /** * The NodeDescriptors class contains a description of all Envision nodes and their possible child nodes. * * This class is used to create all children of a node when that node is newly created. The initializers should not * include attributes which are not required. */ public class NodeDescriptors { public static void initialize(Node node, String initializeAsType) { NodeInitializer initializer = initializerMap.get(initializeAsType); if (initializer != null) initializer.initialize(node); else { assert initializeAsType.startsWith("TypedListOf"); } } public static boolean isPersistenceUnit(Node node) { NodeInitializer ni = initializerMap.get(node.tag()); return ni != null ? ni.isPersistenceUnit() : false; } private static Map<String, NodeInitializer> initializerMap = new HashMap<String, NodeInitializer> (); private static void add(NodeInitializer ni) { initializerMap.put(ni.nodeType(), ni); } static { // Declarations add( new NodeInitializer("Declaration", new String[][] { {"NameText","name"}, {"Modifier","modifiers"}, {"StatementItemList","annotations"}, {"TypedListOfDeclaration","subDeclarations"} })); add( new NodeInitializer("-class-level-container", "Declaration", new String[][] { {"TypedListOfClass","classes"}, {"TypedListOfMethod","methods"}, {"TypedListOfField","fields"}, })); add( new NodeInitializer("Project", true, "-class-level-container", new String[][]{ {"TypedListOfProject","projects"}, {"TypedListOfModule","modules"}, {"TypedListOfUsedLibrary","libraries"} })); add( new NodeInitializer("Module", true, "-class-level-container", new String[][]{ {"TypedListOfModule","modules"}, {"TypedListOfUsedLibrary","libraries"} })); add( new NodeInitializer("Class", "-class-level-container", new String[][]{ {"TypedListOfExpression","baseClasses"}, {"TypedListOfEnumerator","enumerators"}, {"TypedListOfFormalTypeArgument","typeArguments"}, {"TypedListOfExpression","friends"}, {"Integer","cKind"} })); add( new NodeInitializer("Method", "Declaration", new String[][]{ {"StatementItemList","items"}, {"TypedListOfFormalTypeArgument","typeArguments"}, {"TypedListOfFormalArgument","arguments"}, {"TypedListOfFormalResult","results"}, {"TypedListOfMemberInitializer","memberInitializers"}, {"TypedListOfExpression","throws"}, {"Integer","mthKind"} })); add( new NodeInitializer("VariableDeclaration", "Declaration", new String[][]{ {"Expression","typeExpression"} })); add( new NodeInitializer("Field", "VariableDeclaration", null)); add( new NodeInitializer("NameImport", "Declaration", new String[][]{ {"ReferenceExpression","importedName"}, {"Boolean","importAll"} })); // Elements add( new NodeInitializer("FormalTypeArgument", new String[][]{ {"NameText","name"} })); add( new NodeInitializer("FormalArgument", "VariableDeclaration", new String[][]{ {"Integer","directionInt"} })); add( new NodeInitializer("FormalResult", new String[][]{ {"NameText","name"}, {"Expression","typeExpression"} })); add( new NodeInitializer("Modifier", "Integer", null)); add( new NodeInitializer("Enumerator", new String[][]{ {"NameText","name"} })); // Statements add( new NodeInitializer("Block", new String[][]{ {"StatementItemList","items"} })); add( new NodeInitializer("ExpressionStatement", new String[][]{ {"Expression","expression"} })); add( new NodeInitializer("LoopStatement", new String[][]{ {"StatementItemList","body"}, {"Integer","lpKind"} })); add( new NodeInitializer("ForEachStatement", new String[][]{ {"NameText","varName"}, {"Expression","collection"}, {"StatementItemList","body"} })); add( new NodeInitializer("IfStatement", new String[][]{ {"Expression","condition"}, {"StatementItemList","thenBranch"}, {"StatementItemList","elseBranch"} })); add( new NodeInitializer("ReturnStatement", new String[][]{ {"TypedListOfExpression","values"} })); add( new NodeInitializer("CaseStatement", new String[][]{ {"StatementItemList","body"} })); add( new NodeInitializer("SwitchStatement", new String[][]{ {"Expression","switchExpression"}, {"StatementItemList","body"} })); add( new NodeInitializer("TryCatchFinallyStatement", new String[][]{ {"StatementItemList","tryBody"}, {"TypedListOfCatchClause","catchClauses"}, {"StatementItemList","finallyBody"} })); add( new NodeInitializer("CatchClause", new String[][]{ {"StatementItemList","body"} })); add( new NodeInitializer("AssertStatement", new String[][]{ {"Expression","expression"} })); add( new NodeInitializer("SynchronizedStatement", new String[][]{ {"Expression","expression"}, {"StatementItemList","body"} })); // Expressions add( new NodeInitializer("ReferenceExpression", new String[][]{ {"OOReference","ref"}, {"TypedListOfExpression","typeArguments"} })); add( new NodeInitializer("CommaExpression", new String[][]{ {"Expression","left"}, {"Expression","right"} })); add( new NodeInitializer("ThrowExpression", new String[][]{ {"Expression","expr"} })); add( new NodeInitializer("VariableDeclarationExpression", new String[][]{ {"VariableDeclaration","decl"} })); add( new NodeInitializer("BinaryOperation", new String[][]{ {"Expression","left"}, {"Expression","right"}, {"Integer","opr"} })); add( new NodeInitializer("UnaryOperation", new String[][]{ {"Expression","operand"}, {"Integer","opr"} })); add( new NodeInitializer("NewExpression", new String[][]{ {"Expression","newType"}, {"TypedListOfExpression","dimensions"} })); add( new NodeInitializer("ArrayInitializer", new String[][]{ {"TypedListOfExpression","values"} })); add( new NodeInitializer("AssignmentExpression", new String[][]{ {"Expression","left"}, {"Expression","right"}, {"Integer","opr"} })); add( new NodeInitializer("CastExpression", new String[][]{ {"Expression","castType"}, {"Expression","expr"}, {"Integer","cKind"} })); add( new NodeInitializer("InstanceOfExpression", new String[][]{ {"Expression","expr"}, {"Expression","typeExpression"} })); add( new NodeInitializer("MethodCallExpression", new String[][]{ {"Expression","callee"}, {"TypedListOfExpression","arguments"} })); add( new NodeInitializer("ConditionalExpression", new String[][]{ {"Expression","condition"}, {"Expression","trueExpression"}, {"Expression","falseExpression"} })); // Literals add( new NodeInitializer("BooleanLiteral", new String[][]{ {"Boolean","value"} })); add( new NodeInitializer("CharacterLiteral", new String[][]{ {"Character","value"} })); add( new NodeInitializer("IntegerLiteral", new String[][]{ {"Integer","value"} })); add( new NodeInitializer("FloatLiteral", new String[][]{ {"Float","value"} })); add( new NodeInitializer("StringLiteral", new String[][]{ {"Text","value"} })); // Type expressions add( new NodeInitializer("PrimitiveTypeExpression", new String[][]{ {"Integer","val"} })); add( new NodeInitializer("ClassTypeExpression", new String[][]{ {"ReferenceExpression","typeExpression"} })); add( new NodeInitializer("ArrayTypeExpression", new String[][]{ {"Expression","typeExpression"} })); // Primitive types add( new NodeInitializer("Boolean", 0)); add( new NodeInitializer("Character", "x")); add( new NodeInitializer("Integer", 0)); add( new NodeInitializer("Float", 0.0)); add( new NodeInitializer("Text", "")); add( new NodeInitializer("NameText", "")); // Misc add( new NodeInitializer("UsedLibrary", new String[][]{ {"Text","name"} })); // Comments add( new NodeInitializer("CommentStatementItem", new String[][]{ {"CommentNode","commentNode"} })); add( new NodeInitializer("CommentNode", new String[][]{ {"TypedListOfText","lines"}, {"TypedListOfCommentDiagram","diagrams"}, {"TypedListOfCommentFreeNode","codes"}, {"TypedListOfCommentTable","tables"} })); } }
/* * Copyright 2012-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.condition; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * A message associated with a {@link ConditionOutcome}. Provides a fluent builder style * API to encourage consistency across all condition messages. * * @author Phillip Webb * @since 1.4.1 */ public final class ConditionMessage { private final String message; private ConditionMessage() { this(null); } private ConditionMessage(String message) { this.message = message; } private ConditionMessage(ConditionMessage prior, String message) { this.message = prior.isEmpty() ? message : prior + "; " + message; } /** * Return {@code true} if the message is empty. * @return if the message is empty */ public boolean isEmpty() { return !StringUtils.hasLength(this.message); } @Override public boolean equals(Object obj) { if (!(obj instanceof ConditionMessage)) { return false; } if (obj == this) { return true; } return ObjectUtils.nullSafeEquals(((ConditionMessage) obj).message, this.message); } @Override public int hashCode() { return ObjectUtils.nullSafeHashCode(this.message); } @Override public String toString() { return (this.message != null) ? this.message : ""; } /** * Return a new {@link ConditionMessage} based on the instance and an appended * message. * @param message the message to append * @return a new {@link ConditionMessage} instance */ public ConditionMessage append(String message) { if (!StringUtils.hasLength(message)) { return this; } if (!StringUtils.hasLength(this.message)) { return new ConditionMessage(message); } return new ConditionMessage(this.message + " " + message); } /** * Return a new builder to construct a new {@link ConditionMessage} based on the * instance and a new condition outcome. * @param condition the condition * @param details details of the condition * @return a {@link Builder} builder * @see #andCondition(String, Object...) * @see #forCondition(Class, Object...) */ public Builder andCondition(Class<? extends Annotation> condition, Object... details) { Assert.notNull(condition, "Condition must not be null"); return andCondition("@" + ClassUtils.getShortName(condition), details); } /** * Return a new builder to construct a new {@link ConditionMessage} based on the * instance and a new condition outcome. * @param condition the condition * @param details details of the condition * @return a {@link Builder} builder * @see #andCondition(Class, Object...) * @see #forCondition(String, Object...) */ public Builder andCondition(String condition, Object... details) { Assert.notNull(condition, "Condition must not be null"); String detail = StringUtils.arrayToDelimitedString(details, " "); if (StringUtils.hasLength(detail)) { return new Builder(condition + " " + detail); } return new Builder(condition); } /** * Factory method to return a new empty {@link ConditionMessage}. * @return a new empty {@link ConditionMessage} */ public static ConditionMessage empty() { return new ConditionMessage(); } /** * Factory method to create a new {@link ConditionMessage} with a specific message. * @param message the source message (may be a format string if {@code args} are * specified) * @param args format arguments for the message * @return a new {@link ConditionMessage} instance */ public static ConditionMessage of(String message, Object... args) { if (ObjectUtils.isEmpty(args)) { return new ConditionMessage(message); } return new ConditionMessage(String.format(message, args)); } /** * Factory method to create a new {@link ConditionMessage} comprised of the specified * messages. * @param messages the source messages (may be {@code null}) * @return a new {@link ConditionMessage} instance */ public static ConditionMessage of(Collection<? extends ConditionMessage> messages) { ConditionMessage result = new ConditionMessage(); if (messages != null) { for (ConditionMessage message : messages) { result = new ConditionMessage(result, message.toString()); } } return result; } /** * Factory method for a builder to construct a new {@link ConditionMessage} for a * condition. * @param condition the condition * @param details details of the condition * @return a {@link Builder} builder * @see #forCondition(String, Object...) * @see #andCondition(String, Object...) */ public static Builder forCondition(Class<? extends Annotation> condition, Object... details) { return new ConditionMessage().andCondition(condition, details); } /** * Factory method for a builder to construct a new {@link ConditionMessage} for a * condition. * @param condition the condition * @param details details of the condition * @return a {@link Builder} builder * @see #forCondition(Class, Object...) * @see #andCondition(String, Object...) */ public static Builder forCondition(String condition, Object... details) { return new ConditionMessage().andCondition(condition, details); } /** * Builder used to create a {@link ConditionMessage} for a condition. */ public final class Builder { private final String condition; private Builder(String condition) { this.condition = condition; } /** * Indicate that an exact result was found. For example * {@code foundExactly("foo")} results in the message "found foo". * @param result the result that was found * @return a built {@link ConditionMessage} */ public ConditionMessage foundExactly(Object result) { return found("").items(result); } /** * Indicate that one or more results were found. For example * {@code found("bean").items("x")} results in the message "found bean x". * @param article the article found * @return an {@link ItemsBuilder} */ public ItemsBuilder found(String article) { return found(article, article); } /** * Indicate that one or more results were found. For example * {@code found("bean", "beans").items("x", "y")} results in the message "found * beans x, y". * @param singular the article found in singular form * @param plural the article found in plural form * @return an {@link ItemsBuilder} */ public ItemsBuilder found(String singular, String plural) { return new ItemsBuilder(this, "found", singular, plural); } /** * Indicate that one or more results were not found. For example * {@code didNotFind("bean").items("x")} results in the message "did not find bean * x". * @param article the article found * @return an {@link ItemsBuilder} */ public ItemsBuilder didNotFind(String article) { return didNotFind(article, article); } /** * Indicate that one or more results were found. For example * {@code didNotFind("bean", "beans").items("x", "y")} results in the message "did * not find beans x, y". * @param singular the article found in singular form * @param plural the article found in plural form * @return an {@link ItemsBuilder} */ public ItemsBuilder didNotFind(String singular, String plural) { return new ItemsBuilder(this, "did not find", singular, plural); } /** * Indicates a single result. For example {@code resultedIn("yes")} results in the * message "resulted in yes". * @param result the result * @return a built {@link ConditionMessage} */ public ConditionMessage resultedIn(Object result) { return because("resulted in " + result); } /** * Indicates something is available. For example {@code available("money")} * results in the message "money is available". * @param item the item that is available * @return a built {@link ConditionMessage} */ public ConditionMessage available(String item) { return because(item + " is available"); } /** * Indicates something is not available. For example {@code notAvailable("time")} * results in the message "time is not available". * @param item the item that is not available * @return a built {@link ConditionMessage} */ public ConditionMessage notAvailable(String item) { return because(item + " is not available"); } /** * Indicates the reason. For example {@code because("running Linux")} results in * the message "running Linux". * @param reason the reason for the message * @return a built {@link ConditionMessage} */ public ConditionMessage because(String reason) { if (StringUtils.hasLength(reason)) { return new ConditionMessage(ConditionMessage.this, StringUtils.hasLength(this.condition) ? this.condition + " " + reason : reason); } return new ConditionMessage(ConditionMessage.this, this.condition); } } /** * Builder used to create an {@link ItemsBuilder} for a condition. */ public final class ItemsBuilder { private final Builder condition; private final String reason; private final String singular; private final String plural; private ItemsBuilder(Builder condition, String reason, String singular, String plural) { this.condition = condition; this.reason = reason; this.singular = singular; this.plural = plural; } /** * Used when no items are available. For example * {@code didNotFind("any beans").atAll()} results in the message "did not find * any beans". * @return a built {@link ConditionMessage} */ public ConditionMessage atAll() { return items(Collections.emptyList()); } /** * Indicate the items. For example * {@code didNotFind("bean", "beans").items("x", "y")} results in the message "did * not find beans x, y". * @param items the items (may be {@code null}) * @return a built {@link ConditionMessage} */ public ConditionMessage items(Object... items) { return items(Style.NORMAL, items); } /** * Indicate the items. For example * {@code didNotFind("bean", "beans").items("x", "y")} results in the message "did * not find beans x, y". * @param style the render style * @param items the items (may be {@code null}) * @return a built {@link ConditionMessage} */ public ConditionMessage items(Style style, Object... items) { return items(style, (items != null) ? Arrays.asList(items) : null); } /** * Indicate the items. For example * {@code didNotFind("bean", "beans").items(Collections.singleton("x")} results in * the message "did not find bean x". * @param items the source of the items (may be {@code null}) * @return a built {@link ConditionMessage} */ public ConditionMessage items(Collection<?> items) { return items(Style.NORMAL, items); } /** * Indicate the items with a {@link Style}. For example * {@code didNotFind("bean", "beans").items(Style.QUOTE, Collections.singleton("x")} * results in the message "did not find bean 'x'". * @param style the render style * @param items the source of the items (may be {@code null}) * @return a built {@link ConditionMessage} */ public ConditionMessage items(Style style, Collection<?> items) { Assert.notNull(style, "Style must not be null"); StringBuilder message = new StringBuilder(this.reason); items = style.applyTo(items); if ((this.condition == null || items == null || items.size() <= 1) && StringUtils.hasLength(this.singular)) { message.append(" ").append(this.singular); } else if (StringUtils.hasLength(this.plural)) { message.append(" ").append(this.plural); } if (items != null && !items.isEmpty()) { message.append(" ").append(StringUtils.collectionToDelimitedString(items, ", ")); } return this.condition.because(message.toString()); } } /** * Render styles. */ public enum Style { /** * Render with normal styling. */ NORMAL { @Override protected Object applyToItem(Object item) { return item; } }, /** * Render with the item surrounded by quotes. */ QUOTE { @Override protected String applyToItem(Object item) { return (item != null) ? "'" + item + "'" : null; } }; public Collection<?> applyTo(Collection<?> items) { if (items == null) { return null; } List<Object> result = new ArrayList<>(items.size()); for (Object item : items) { result.add(applyToItem(item)); } return result; } protected abstract Object applyToItem(Object item); } }
/* * 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.transport.messages; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.CodecException; import com.google.common.base.Predicate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.db.ConsistencyLevel; import org.apache.cassandra.db.WriteType; import org.apache.cassandra.exceptions.*; import org.apache.cassandra.transport.CBUtil; import org.apache.cassandra.transport.Message; import org.apache.cassandra.transport.ProtocolException; import org.apache.cassandra.transport.ServerError; import org.apache.cassandra.utils.MD5Digest; /** * Message to indicate an error to the client. */ public class ErrorMessage extends Message.Response { private static final Logger logger = LoggerFactory.getLogger(ErrorMessage.class); public static final Message.Codec<ErrorMessage> codec = new Message.Codec<ErrorMessage>() { public ErrorMessage decode(ByteBuf body, int version) { ExceptionCode code = ExceptionCode.fromValue(body.readInt()); String msg = CBUtil.readString(body); TransportException te = null; switch (code) { case SERVER_ERROR: te = new ServerError(msg); break; case PROTOCOL_ERROR: te = new ProtocolException(msg); break; case BAD_CREDENTIALS: te = new AuthenticationException(msg); break; case UNAVAILABLE: { ConsistencyLevel cl = CBUtil.readConsistencyLevel(body); int required = body.readInt(); int alive = body.readInt(); te = new UnavailableException(cl, required, alive); } break; case OVERLOADED: te = new OverloadedException(msg); break; case IS_BOOTSTRAPPING: te = new IsBootstrappingException(); break; case TRUNCATE_ERROR: te = new TruncateException(msg); break; case WRITE_TIMEOUT: case READ_TIMEOUT: ConsistencyLevel cl = CBUtil.readConsistencyLevel(body); int received = body.readInt(); int blockFor = body.readInt(); if (code == ExceptionCode.WRITE_TIMEOUT) { WriteType writeType = Enum.valueOf(WriteType.class, CBUtil.readString(body)); te = new WriteTimeoutException(writeType, cl, received, blockFor); } else { byte dataPresent = body.readByte(); te = new ReadTimeoutException(cl, received, blockFor, dataPresent != 0); } break; case UNPREPARED: { MD5Digest id = MD5Digest.wrap(CBUtil.readBytes(body)); te = new PreparedQueryNotFoundException(id); } break; case SYNTAX_ERROR: te = new SyntaxException(msg); break; case UNAUTHORIZED: te = new UnauthorizedException(msg); break; case INVALID: te = new InvalidRequestException(msg); break; case CONFIG_ERROR: te = new ConfigurationException(msg); break; case ALREADY_EXISTS: String ksName = CBUtil.readString(body); String cfName = CBUtil.readString(body); if (cfName.isEmpty()) te = new AlreadyExistsException(ksName); else te = new AlreadyExistsException(ksName, cfName); break; } return new ErrorMessage(te); } public void encode(ErrorMessage msg, ByteBuf dest, int version) { dest.writeInt(msg.error.code().value); CBUtil.writeString(msg.error.getMessage(), dest); switch (msg.error.code()) { case UNAVAILABLE: UnavailableException ue = (UnavailableException)msg.error; CBUtil.writeConsistencyLevel(ue.consistency, dest); dest.writeInt(ue.required); dest.writeInt(ue.alive); break; case WRITE_TIMEOUT: case READ_TIMEOUT: RequestTimeoutException rte = (RequestTimeoutException)msg.error; boolean isWrite = msg.error.code() == ExceptionCode.WRITE_TIMEOUT; CBUtil.writeConsistencyLevel(rte.consistency, dest); dest.writeInt(rte.received); dest.writeInt(rte.blockFor); if (isWrite) CBUtil.writeString(((WriteTimeoutException)rte).writeType.toString(), dest); else dest.writeByte((byte)(((ReadTimeoutException)rte).dataPresent ? 1 : 0)); break; case UNPREPARED: PreparedQueryNotFoundException pqnfe = (PreparedQueryNotFoundException)msg.error; CBUtil.writeBytes(pqnfe.id.bytes, dest); break; case ALREADY_EXISTS: AlreadyExistsException aee = (AlreadyExistsException)msg.error; CBUtil.writeString(aee.ksName, dest); CBUtil.writeString(aee.cfName, dest); break; } } public int encodedSize(ErrorMessage msg, int version) { int size = 4 + CBUtil.sizeOfString(msg.error.getMessage()); switch (msg.error.code()) { case UNAVAILABLE: UnavailableException ue = (UnavailableException)msg.error; size += CBUtil.sizeOfConsistencyLevel(ue.consistency) + 8; break; case WRITE_TIMEOUT: case READ_TIMEOUT: RequestTimeoutException rte = (RequestTimeoutException)msg.error; boolean isWrite = msg.error.code() == ExceptionCode.WRITE_TIMEOUT; size += CBUtil.sizeOfConsistencyLevel(rte.consistency) + 8; size += isWrite ? CBUtil.sizeOfString(((WriteTimeoutException)rte).writeType.toString()) : 1; break; case UNPREPARED: PreparedQueryNotFoundException pqnfe = (PreparedQueryNotFoundException)msg.error; size += CBUtil.sizeOfBytes(pqnfe.id.bytes); break; case ALREADY_EXISTS: AlreadyExistsException aee = (AlreadyExistsException)msg.error; size += CBUtil.sizeOfString(aee.ksName); size += CBUtil.sizeOfString(aee.cfName); break; } return size; } }; // We need to figure error codes out (#3979) public final TransportException error; private ErrorMessage(TransportException error) { super(Message.Type.ERROR); this.error = error; } private ErrorMessage(TransportException error, int streamId) { this(error); setStreamId(streamId); } public static ErrorMessage fromException(Throwable e) { return fromException(e, null); } /** * @param e the exception * @param unexpectedExceptionHandler a callback for handling unexpected exceptions. If null, or if this * returns false, the error is logged at ERROR level via sl4fj */ public static ErrorMessage fromException(Throwable e, Predicate<Throwable> unexpectedExceptionHandler) { int streamId = 0; // Netty will wrap exceptions during decoding in a CodecException. If the cause was one of our ProtocolExceptions // or some other internal exception, extract that and use it. if (e instanceof CodecException) { Throwable cause = e.getCause(); if (cause != null && cause instanceof WrappedException) { streamId = ((WrappedException)cause).streamId; e = cause.getCause(); } } else if (e instanceof WrappedException) { streamId = ((WrappedException)e).streamId; e = e.getCause(); } if (e instanceof TransportException) return new ErrorMessage((TransportException)e, streamId); // Unexpected exception if (unexpectedExceptionHandler == null || !unexpectedExceptionHandler.apply(e)) logger.error("Unexpected exception during request", e); return new ErrorMessage(new ServerError(e), streamId); } @Override public String toString() { return "ERROR " + error.code() + ": " + error.getMessage(); } public static RuntimeException wrap(Throwable t, int streamId) { return new WrappedException(t, streamId); } private static class WrappedException extends RuntimeException { private final int streamId; public WrappedException(Throwable cause, int streamId) { super(cause); this.streamId = streamId; } } }
/* * 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.service; import java.net.InetAddress; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; import com.google.common.collect.Iterables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.cassandra.concurrent.Stage; import org.apache.cassandra.concurrent.StageManager; import org.apache.cassandra.config.CFMetaData.SpeculativeRetry.RetryType; import org.apache.cassandra.config.Schema; import org.apache.cassandra.config.ReadRepairDecision; import org.apache.cassandra.db.ColumnFamilyStore; import org.apache.cassandra.db.ConsistencyLevel; import org.apache.cassandra.db.ReadCommand; import org.apache.cassandra.db.ReadResponse; import org.apache.cassandra.db.Row; import org.apache.cassandra.db.Keyspace; import org.apache.cassandra.exceptions.ReadTimeoutException; import org.apache.cassandra.exceptions.UnavailableException; import org.apache.cassandra.metrics.ReadRepairMetrics; import org.apache.cassandra.net.MessageOut; import org.apache.cassandra.net.MessagingService; import org.apache.cassandra.service.StorageProxy.LocalReadRunnable; import org.apache.cassandra.utils.FBUtilities; /** * Sends a read request to the replicas needed to satisfy a given ConsistencyLevel. * * Optionally, may perform additional requests to provide redundancy against replica failure: * AlwaysSpeculatingReadExecutor will always send a request to one extra replica, while * SpeculatingReadExecutor will wait until it looks like the original request is in danger * of timing out before performing extra reads. */ public abstract class AbstractReadExecutor { private static final Logger logger = LoggerFactory.getLogger(AbstractReadExecutor.class); protected final ReadCommand command; protected final List<InetAddress> targetReplicas; protected final RowDigestResolver resolver; protected final ReadCallback<ReadResponse, Row> handler; AbstractReadExecutor(ReadCommand command, ConsistencyLevel consistencyLevel, List<InetAddress> targetReplicas) { this.command = command; this.targetReplicas = targetReplicas; resolver = new RowDigestResolver(command.ksName, command.key, targetReplicas.size()); handler = new ReadCallback<>(resolver, consistencyLevel, command, targetReplicas); } private static boolean isLocalRequest(InetAddress replica) { return replica.equals(FBUtilities.getBroadcastAddress()) && StorageProxy.OPTIMIZE_LOCAL_REQUESTS; } protected void makeDataRequests(Iterable<InetAddress> endpoints) { boolean readLocal = false; for (InetAddress endpoint : endpoints) { if (isLocalRequest(endpoint)) { readLocal = true; } else { logger.trace("reading data from {}", endpoint); logger.info("reading data from {}", endpoint); //@daidong I just 'assumed' that this remote request will be handled in the similar fashion //@daidong Actually, this assumption is true. All the requests are processed using StageManager. //listed below. MessagingService.instance().sendRR(command.createMessage(), endpoint, handler); } } if (readLocal) { logger.trace("reading data locally"); logger.info("reading data locally"); //@daidong Here is the code how we execute the Read request. There are several stages for each command. //@daidong For read, the Stage implementation is "multiThreadedLowSignalStage", which is a TracingAwareExecutorService logger.info("@daidong debug: " + "read data from local"); StageManager.getStage(Stage.READ).maybeExecuteImmediately(new LocalReadRunnable(command, handler)); } } protected void makeDigestRequests(Iterable<InetAddress> endpoints) { ReadCommand digestCommand = command.copy(); digestCommand.setDigestQuery(true); MessageOut<?> message = digestCommand.createMessage(); for (InetAddress endpoint : endpoints) { if (isLocalRequest(endpoint)) { logger.trace("reading digest locally"); StageManager.getStage(Stage.READ).execute(new LocalReadRunnable(digestCommand, handler)); } else { logger.trace("reading digest from {}", endpoint); MessagingService.instance().sendRR(message, endpoint, handler); } } } /** * Perform additional requests if it looks like the original will time out. May block while it waits * to see if the original requests are answered first. */ public abstract void maybeTryAdditionalReplicas(); /** * Get the replicas involved in the [finished] request. * * @return target replicas + the extra replica, *IF* we speculated. */ public abstract Collection<InetAddress> getContactedReplicas(); /** * send the initial set of requests */ public abstract void executeAsync(); /** * wait for an answer. Blocks until success or timeout, so it is caller's * responsibility to call maybeTryAdditionalReplicas first. */ public Row get() throws ReadTimeoutException, DigestMismatchException { return handler.get(); } /** * @return an executor appropriate for the configured speculative read policy */ public static AbstractReadExecutor getReadExecutor(ReadCommand command, ConsistencyLevel consistencyLevel) throws UnavailableException { Keyspace keyspace = Keyspace.open(command.ksName); List<InetAddress> allReplicas = StorageProxy.getLiveSortedEndpoints(keyspace, command.key); ReadRepairDecision repairDecision = Schema.instance.getCFMetaData(command.ksName, command.cfName).newReadRepairDecision(); List<InetAddress> targetReplicas = consistencyLevel.filterForQuery(keyspace, allReplicas, repairDecision); // Throw UAE early if we don't have enough replicas. consistencyLevel.assureSufficientLiveNodes(keyspace, targetReplicas); // Fat client. Speculating read executors need access to cfs metrics and sampled latency, and fat clients // can't provide that. So, for now, fat clients will always use NeverSpeculatingReadExecutor. if (StorageService.instance.isClientMode()) return new NeverSpeculatingReadExecutor(command, consistencyLevel, targetReplicas); if (repairDecision != ReadRepairDecision.NONE) ReadRepairMetrics.attempted.mark(); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(command.cfName); RetryType retryType = cfs.metadata.getSpeculativeRetry().type; //@daidong For a single cluster, it will fall into PERCENTILE category. //logger.info("@daidong debug: " + "RetryType: " + retryType.name()); // Speculative retry is disabled *OR* there are simply no extra replicas to speculate. if (retryType == RetryType.NONE || consistencyLevel.blockFor(keyspace) == allReplicas.size()) return new NeverSpeculatingReadExecutor(command, consistencyLevel, targetReplicas); if (targetReplicas.size() == allReplicas.size()) { // CL.ALL, RRD.GLOBAL or RRD.DC_LOCAL and a single-DC. // We are going to contact every node anyway, so ask for 2 full data requests instead of 1, for redundancy // (same amount of requests in total, but we turn 1 digest request into a full blown data request). return new AlwaysSpeculatingReadExecutor(cfs, command, consistencyLevel, targetReplicas); } // RRD.NONE or RRD.DC_LOCAL w/ multiple DCs. InetAddress extraReplica = allReplicas.get(targetReplicas.size()); // With repair decision DC_LOCAL all replicas/target replicas may be in different order, so // we might have to find a replacement that's not already in targetReplicas. if (repairDecision == ReadRepairDecision.DC_LOCAL && targetReplicas.contains(extraReplica)) { for (InetAddress address : allReplicas) { if (!targetReplicas.contains(address)) { extraReplica = address; break; } } } targetReplicas.add(extraReplica); if (retryType == RetryType.ALWAYS) return new AlwaysSpeculatingReadExecutor(cfs, command, consistencyLevel, targetReplicas); else // PERCENTILE or CUSTOM. @daidong: return a speculatingReadExecutor. return new SpeculatingReadExecutor(cfs, command, consistencyLevel, targetReplicas); } private static class NeverSpeculatingReadExecutor extends AbstractReadExecutor { public NeverSpeculatingReadExecutor(ReadCommand command, ConsistencyLevel consistencyLevel, List<InetAddress> targetReplicas) { super(command, consistencyLevel, targetReplicas); } public void executeAsync() { makeDataRequests(targetReplicas.subList(0, 1)); if (targetReplicas.size() > 1) makeDigestRequests(targetReplicas.subList(1, targetReplicas.size())); } public void maybeTryAdditionalReplicas() { // no-op } public Collection<InetAddress> getContactedReplicas() { return targetReplicas; } } private static class SpeculatingReadExecutor extends AbstractReadExecutor { private final ColumnFamilyStore cfs; private volatile boolean speculated = false; public SpeculatingReadExecutor(ColumnFamilyStore cfs, ReadCommand command, ConsistencyLevel consistencyLevel, List<InetAddress> targetReplicas) { super(command, consistencyLevel, targetReplicas); this.cfs = cfs; } /* * @author daidong. This is where the real read/query happens. */ public void executeAsync() { // if CL + RR result in covering all replicas, getReadExecutor forces AlwaysSpeculating. So we know // that the last replica in our list is "extra." List<InetAddress> initialReplicas = targetReplicas.subList(0, targetReplicas.size() - 1); if (handler.blockfor < initialReplicas.size()) { // We're hitting additional targets for read repair. Since our "extra" replica is the least- // preferred by the snitch, we do an extra data read to start with against a replica more // likely to reply; better to let RR fail than the entire query. makeDataRequests(initialReplicas.subList(0, 2)); if (initialReplicas.size() > 2) makeDigestRequests(initialReplicas.subList(2, initialReplicas.size())); } else { // not doing read repair; all replies are important, so it doesn't matter which nodes we // perform data reads against vs digest. // @daidong. We just make request to the first replica. and then make digest requests to all the remained replicas makeDataRequests(initialReplicas.subList(0, 1)); if (initialReplicas.size() > 1) makeDigestRequests(initialReplicas.subList(1, initialReplicas.size())); } } public void maybeTryAdditionalReplicas() { // no latency information, or we're overloaded if (cfs.sampleLatencyNanos > TimeUnit.MILLISECONDS.toNanos(command.getTimeout())) return; if (!handler.await(cfs.sampleLatencyNanos, TimeUnit.NANOSECONDS)) { // Could be waiting on the data, or on enough digests. ReadCommand retryCommand = command; if (resolver.getData() != null) { retryCommand = command.copy(); retryCommand.setDigestQuery(true); } InetAddress extraReplica = Iterables.getLast(targetReplicas); logger.trace("speculating read retry on {}", extraReplica); MessagingService.instance().sendRR(retryCommand.createMessage(), extraReplica, handler); speculated = true; cfs.metric.speculativeRetries.inc(); } } public Collection<InetAddress> getContactedReplicas() { return speculated ? targetReplicas : targetReplicas.subList(0, targetReplicas.size() - 1); } } private static class AlwaysSpeculatingReadExecutor extends AbstractReadExecutor { private final ColumnFamilyStore cfs; public AlwaysSpeculatingReadExecutor(ColumnFamilyStore cfs, ReadCommand command, ConsistencyLevel consistencyLevel, List<InetAddress> targetReplicas) { super(command, consistencyLevel, targetReplicas); this.cfs = cfs; } public void maybeTryAdditionalReplicas() { // no-op } public Collection<InetAddress> getContactedReplicas() { return targetReplicas; } @Override public void executeAsync() { makeDataRequests(targetReplicas.subList(0, targetReplicas.size() > 1 ? 2 : 1)); if (targetReplicas.size() > 2) makeDigestRequests(targetReplicas.subList(2, targetReplicas.size())); cfs.metric.speculativeRetries.inc(); } } }
/* * The MIT License (MIT) * * Copyright (c) 2013 Marek Mikuliszyn * * 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 sr; import com.dukascopy.api.Instrument; import com.dukascopy.api.Period; import helper.Helpers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import trade.TradeManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import java.util.List; public class Generator { protected static final Logger LOGGER = LoggerFactory.getLogger(Generator.class); public Generator() { } public static Level loadZZ(Instrument pair, Period tf, Date time) { try { String sql = String.format("SELECT dir, level_high, level_low, id FROM zz WHERE pair = '%s' AND tf = '%s' AND time = '%s'", pair.name(), Helpers.tfToString(tf), Helpers.formatDateTime(time) ); LOGGER.debug(sql); Statement st = (Statement) TradeManager.getInstance().getCon().createStatement(); ResultSet rs = st.executeQuery(sql); while (rs.next()) { String dir = rs.getString(1); double levelHigh = rs.getDouble(2); double levelLow = rs.getDouble(3); int rowId = rs.getInt(4); Level lvl = new Level(pair, tf, dir, time, levelHigh, levelLow); lvl.setRowId(rowId); return lvl; } } catch (SQLException ex) { LOGGER.error("SQL Error: " + ex.getMessage()); } return null; } public static Level loadNextZZ(Instrument pair, Period tf, Date time) { try { String sql = String.format("SELECT dir, level_high, level_low, time FROM zz WHERE pair = '%s' AND tf = '%s' AND time > '%s' ORDER BY time LIMIT 1", pair.name(), Helpers.tfToString(tf), Helpers.formatDateTime(time) ); LOGGER.debug(sql); Statement st = (Statement) TradeManager.getInstance().getCon().createStatement(); ResultSet rs = st.executeQuery(sql); while (rs.next()) { String dir = rs.getString(1); double levelHigh = rs.getDouble(2); double levelLow = rs.getDouble(3); time = rs.getTimestamp(4); return new Level(pair, tf, dir, time, levelHigh, levelLow); } } catch (SQLException ex) { LOGGER.error("SQL Error: " + ex.getMessage()); } return null; } public void runAll() { for (Instrument pair : TradeManager.defaultInstruments()) { for (Period tf : TradeManager.defaultPeriods()) { runPairTF(pair, tf); } } System.exit(0); } public void runPairTF(Instrument pair, Period tf) { LevelList openLevels = new LevelList(); List<Level> levelsToClose = new ArrayList<Level>(); LOGGER.info("Running " + pair.name() + "/" + Helpers.tfToString(tf)); try { String sql = String.format("SELECT close, is_zz, time FROM bar WHERE pair = '%s' AND tf = '%s' ORDER BY time", pair.name(), Helpers.tfToString(tf) ); LOGGER.debug(sql); Statement s = (Statement) TradeManager.getInstance().getCon().createStatement(); ResultSet rs = s.executeQuery(sql); while (rs.next()) { double close = rs.getDouble(1); boolean isZZ = rs.getBoolean(2); Date time = rs.getTimestamp(3); for (Level level : openLevels.getList()) { if (level.getDir().equals(Type.SUPPORT) && close < level.getLevelBoundry()) { levelsToClose.add(level); } else if (level.getDir().equals(Type.RESISTANCE) && close > level.getLevelBoundry()) { levelsToClose.add(level); } } if (isZZ) { Level zz = loadZZ(pair, tf, time); if (zz == null) { LOGGER.error("Cannot find ZZ for " + time.toString()); continue; } openLevels.addLevel(zz); } for (Level level : levelsToClose) { level.setEndDate(time); level.save(); openLevels.remove(level); } levelsToClose = new ArrayList<Level>(); } openLevels.save(); generateMW(pair, tf); } catch (SQLException ex) { LOGGER.error("SQL Error: " + ex.getMessage()); } catch (Exception ex) { ex.printStackTrace(); LOGGER.error(ex.getMessage()); } } private void generateMW(Instrument pair, Period tf) { try { String sql = String.format("SELECT sr.id, COUNT(*) AS levels FROM sr JOIN sr_touch AS touch ON touch.sr_id = sr.id WHERE pair = '%s' AND tf = '%s' GROUP BY sr.id HAVING levels > 0", pair.name(), Helpers.tfToString(tf) ); LOGGER.debug(sql); Statement s = (Statement) TradeManager.getInstance().getCon().createStatement(); // Get list of ids of levels with at least one peak (MW) ResultSet rs = s.executeQuery(sql); List<Integer> srIds = new ArrayList<Integer>(); while (rs.next()) { srIds.add(rs.getInt(1)); } // Get MW's second leg for (Integer sr_id : srIds) { sql = String.format("SELECT zz.time, sr_touch.id FROM sr_touch LEFT JOIN zz ON zz.id = sr_touch.zz_id WHERE sr_touch.sr_id = '%s' ORDER BY sr_touch.time LIMIT 1", sr_id); LOGGER.debug(sql); rs = s.executeQuery(sql); Date zz2_time = null; int touch_id = 0; while (rs.next()) { zz2_time = rs.getTimestamp(1); touch_id = rs.getInt(2); } Level sr1 = Level.loadById(sr_id); Level sr2 = loadNextZZ(pair, tf, zz2_time); if (sr2 == null) { continue; } sql = String.format("INSERT INTO sr_mw VALUES (NULL, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %s, '%s', '%s', '%s')", sr1.getPair().name(), Helpers.tfToString(sr1.getTF()), sr1.getDir(), sr1.getHigh(), sr1.getLow(), Helpers.formatDateTime(sr1.getStartDate()), Helpers.formatDateTime(sr2.getStartDate()), (sr1.getEndDate() == null ? null : "'" + Helpers.formatDateTime(sr1.getEndDate()) + "'"), sr_id, touch_id, Helpers.formatDateTime(new Date()) ); LOGGER.debug(sql); s.executeUpdate(sql); } } catch (SQLException ex) { LOGGER.error("SQL Error: " + ex.getMessage()); ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); LOGGER.error(ex.getMessage()); } } }
package org.robolectric.shadows; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RuntimeEnvironment; import org.robolectric.TestRunners; import static org.assertj.core.api.Assertions.assertThat; @RunWith(TestRunners.WithDefaults.class) public class SQLiteOpenHelperTest { private TestOpenHelper helper; @Before public void setUp() throws Exception { helper = new TestOpenHelper(RuntimeEnvironment.application, "path", null, 1); } @Test public void testConstructorWithNullPathShouldCreateInMemoryDatabase() throws Exception { TestOpenHelper helper = new TestOpenHelper(null, null, null, 1); SQLiteDatabase database = helper.getReadableDatabase(); assertDatabaseOpened(database, helper); assertInitialDB(database, helper); } @Test public void testInitialGetReadableDatabase() throws Exception { SQLiteDatabase database = helper.getReadableDatabase(); assertInitialDB(database, helper); } @Test public void testSubsequentGetReadableDatabase() throws Exception { helper.getReadableDatabase(); helper.close(); SQLiteDatabase database = helper.getReadableDatabase(); assertSubsequentDB(database, helper); } @Test public void testSameDBInstanceSubsequentGetReadableDatabase() throws Exception { SQLiteDatabase db1 = helper.getReadableDatabase(); SQLiteDatabase db2 = helper.getReadableDatabase(); assertThat(db1).isSameAs(db2); } @Test public void testInitialGetWritableDatabase() throws Exception { SQLiteDatabase database = helper.getWritableDatabase(); assertInitialDB(database, helper); } @Test public void testSubsequentGetWritableDatabase() throws Exception { helper.getWritableDatabase(); helper.close(); assertSubsequentDB(helper.getWritableDatabase(), helper); } @Test public void testSameDBInstanceSubsequentGetWritableDatabase() throws Exception { SQLiteDatabase db1 = helper.getWritableDatabase(); SQLiteDatabase db2 = helper.getWritableDatabase(); assertThat(db1).isSameAs(db2); } @Test public void testClose() throws Exception { SQLiteDatabase database = helper.getWritableDatabase(); assertThat(database.isOpen()).isTrue(); helper.close(); assertThat(database.isOpen()).isFalse(); } @Test public void testGetPath() throws Exception { final String path1 = "path1", path2 = "path2"; TestOpenHelper helper1 = new TestOpenHelper(RuntimeEnvironment.application, path1, null, 1); String expectedPath1 = RuntimeEnvironment.application.getDatabasePath(path1).getAbsolutePath(); assertThat(helper1.getReadableDatabase().getPath()).isEqualTo(expectedPath1); TestOpenHelper helper2 = new TestOpenHelper(RuntimeEnvironment.application, path2, null, 1); String expectedPath2 = RuntimeEnvironment.application.getDatabasePath(path2).getAbsolutePath(); assertThat(helper2.getReadableDatabase().getPath()).isEqualTo(expectedPath2); } @Test public void testCloseMultipleDbs() throws Exception { TestOpenHelper helper2 = new TestOpenHelper(RuntimeEnvironment.application, "path2", null, 1); SQLiteDatabase database1 = helper.getWritableDatabase(); SQLiteDatabase database2 = helper2.getWritableDatabase(); assertThat(database1.isOpen()).isTrue(); assertThat(database2.isOpen()).isTrue(); helper.close(); assertThat(database1.isOpen()).isFalse(); assertThat(database2.isOpen()).isTrue(); helper2.close(); assertThat(database2.isOpen()).isFalse(); } @Test public void testOpenMultipleDbsOnCreate() throws Exception { TestOpenHelper helper2 = new TestOpenHelper(RuntimeEnvironment.application, "path2", null, 1); assertThat(helper.onCreateCalled).isFalse(); assertThat(helper2.onCreateCalled).isFalse(); helper.getWritableDatabase(); assertThat(helper.onCreateCalled).isTrue(); assertThat(helper2.onCreateCalled).isFalse(); helper2.getWritableDatabase(); assertThat(helper.onCreateCalled).isTrue(); assertThat(helper2.onCreateCalled).isTrue(); helper.close(); helper2.close(); } private void setupTable(SQLiteDatabase db, String table) { db.execSQL("CREATE TABLE " + table + " (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "testVal INTEGER DEFAULT 0" + ");"); } private void insertData(SQLiteDatabase db, String table, int[] values) { for (int i : values) { ContentValues cv = new ContentValues(); cv.put("testVal", i); db.insert(table, null, cv); } } private void verifyData(SQLiteDatabase db, String table, int expectedVals) { assertThat(db.query(table, null, null, null, null, null, null).getCount()).isEqualTo(expectedVals); } @Test public void testMultipleDbsPreserveData() throws Exception { final String TABLE_NAME1 = "fart", TABLE_NAME2 = "fart2"; SQLiteDatabase db1 = helper.getWritableDatabase(); setupTable(db1, TABLE_NAME1); insertData(db1, TABLE_NAME1, new int[]{1, 2}); TestOpenHelper helper2 = new TestOpenHelper(RuntimeEnvironment.application, "path2", null, 1); SQLiteDatabase db2 = helper2.getWritableDatabase(); setupTable(db2, TABLE_NAME2); insertData(db2, TABLE_NAME2, new int[]{4, 5, 6}); verifyData(db1, TABLE_NAME1, 2); verifyData(db2, TABLE_NAME2, 3); } @Test public void testCloseOneDbKeepsDataForOther() throws Exception { final String TABLE_NAME1 = "fart", TABLE_NAME2 = "fart2"; TestOpenHelper helper2 = new TestOpenHelper(RuntimeEnvironment.application, "path2", null, 1); SQLiteDatabase db1 = helper.getWritableDatabase(); SQLiteDatabase db2 = helper2.getWritableDatabase(); setupTable(db1, TABLE_NAME1); setupTable(db2, TABLE_NAME2); insertData(db1, TABLE_NAME1, new int[]{1, 2}); insertData(db2, TABLE_NAME2, new int[]{4, 5, 6}); verifyData(db1, TABLE_NAME1, 2); verifyData(db2, TABLE_NAME2, 3); db1.close(); verifyData(db2, TABLE_NAME2, 3); db1 = helper.getWritableDatabase(); verifyData(db1, TABLE_NAME1, 2); verifyData(db2, TABLE_NAME2, 3); } @Test public void testCreateAndDropTable() throws Exception { SQLiteDatabase database = helper.getWritableDatabase(); database.execSQL("CREATE TABLE foo(id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT);"); database.execSQL("DROP TABLE IF EXISTS foo;"); } @Test public void testCloseThenOpen() throws Exception { final String TABLE_NAME1 = "fart"; SQLiteDatabase db1 = helper.getWritableDatabase(); setupTable(db1, TABLE_NAME1); insertData(db1, TABLE_NAME1, new int[]{1, 2}); verifyData(db1, TABLE_NAME1, 2); db1.close(); db1 = helper.getWritableDatabase(); assertThat(db1.isOpen()).isTrue(); } private static void assertInitialDB(SQLiteDatabase database, TestOpenHelper helper) { assertDatabaseOpened(database, helper); assertThat(helper.onCreateCalled).isTrue(); } private static void assertSubsequentDB(SQLiteDatabase database, TestOpenHelper helper) { assertDatabaseOpened(database, helper); assertThat(helper.onCreateCalled).isFalse(); } private static void assertDatabaseOpened(SQLiteDatabase database, TestOpenHelper helper) { assertThat(database).isNotNull(); assertThat(database.isOpen()).isTrue(); assertThat(helper.onOpenCalled).isTrue(); assertThat(helper.onUpgradeCalled).isFalse(); } private class TestOpenHelper extends SQLiteOpenHelper { public boolean onCreateCalled; public boolean onUpgradeCalled; public boolean onOpenCalled; public TestOpenHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase database) { onCreateCalled = true; } @Override public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) { onUpgradeCalled = true; } @Override public void onOpen(SQLiteDatabase database) { onOpenCalled = true; } @Override public synchronized void close() { onCreateCalled = false; onUpgradeCalled = false; onOpenCalled = false; super.close(); } } }
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.maven.importing; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.DependencyScope; import com.intellij.openapi.roots.ExternalLibraryDescriptor; import com.intellij.openapi.roots.JavaProjectModelModifier; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.util.Trinity; import com.intellij.openapi.util.text.StringUtil; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.util.PsiUtilCore; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import com.intellij.util.text.VersionComparatorUtil; import com.intellij.util.xml.DomUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.concurrency.Promise; import org.jetbrains.idea.maven.dom.MavenDomBundle; import org.jetbrains.idea.maven.dom.MavenDomUtil; import org.jetbrains.idea.maven.dom.converters.MavenDependencyCompletionUtil; import org.jetbrains.idea.maven.dom.model.MavenDomDependency; import org.jetbrains.idea.maven.dom.model.MavenDomPlugin; import org.jetbrains.idea.maven.dom.model.MavenDomPlugins; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; import org.jetbrains.idea.maven.indices.MavenProjectIndicesManager; import org.jetbrains.idea.maven.model.MavenArtifact; import org.jetbrains.idea.maven.model.MavenConstants; import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.jps.model.java.JpsJavaSdkType; import java.util.*; public final class MavenProjectModelModifier extends JavaProjectModelModifier { private final Project myProject; private final MavenProjectsManager myProjectsManager; private final MavenProjectIndicesManager myIndicesManager; public MavenProjectModelModifier(Project project) { myProject = project; myProjectsManager = MavenProjectsManager.getInstance(project); myIndicesManager = MavenProjectIndicesManager.getInstance(project); } @Nullable @Override public Promise<Void> addModuleDependency(@NotNull Module from, @NotNull Module to, @NotNull DependencyScope scope, boolean exported) { final MavenProject toProject = myProjectsManager.findProject(to); if (toProject == null) return null; MavenId mavenId = toProject.getMavenId(); return addDependency(Collections.singletonList(from), mavenId, scope); } private Promise<Void> addDependency(@NotNull Collection<? extends Module> fromModules, @NotNull final MavenId mavenId, @NotNull final DependencyScope scope) { return addDependency(fromModules, mavenId, null, null, null, scope); } private Promise<Void> addDependency(@NotNull Collection<? extends Module> fromModules, @NotNull final MavenId mavenId, @Nullable String minVersion, @Nullable String maxVersion, @Nullable String preferredVersion, @NotNull final DependencyScope scope) { final List<Trinity<MavenDomProjectModel, MavenId, String>> models = new ArrayList<>(fromModules.size()); List<XmlFile> files = new ArrayList<>(fromModules.size()); List<MavenProject> projectToUpdate = new ArrayList<>(fromModules.size()); final String mavenScope = getMavenScope(scope); for (Module from : fromModules) { if (!myProjectsManager.isMavenizedModule(from)) return null; MavenProject fromProject = myProjectsManager.findProject(from); if (fromProject == null) return null; final MavenDomProjectModel model = MavenDomUtil.getMavenDomProjectModel(myProject, fromProject.getFile()); if (model == null) return null; String scopeToSet = null; String version = null; if (mavenId.getGroupId() != null && mavenId.getArtifactId() != null) { MavenDomDependency managedDependency = MavenDependencyCompletionUtil.findManagedDependency(model, myProject, mavenId.getGroupId(), mavenId.getArtifactId()); if (managedDependency != null) { String managedScope = StringUtil.nullize(managedDependency.getScope().getStringValue(), true); scopeToSet = (managedScope == null && MavenConstants.SCOPE_COMPILE.equals(mavenScope)) || StringUtil.equals(managedScope, mavenScope) ? null : mavenScope; } if (managedDependency == null || StringUtil.isEmpty(managedDependency.getVersion().getStringValue())) { version = selectVersion(mavenId, minVersion, maxVersion, preferredVersion); scopeToSet = mavenScope; } } models.add(Trinity.create(model, new MavenId(mavenId.getGroupId(), mavenId.getArtifactId(), version), scopeToSet)); files.add(DomUtil.getFile(model)); projectToUpdate.add(fromProject); } WriteCommandAction.writeCommandAction(myProject, PsiUtilCore.toPsiFileArray(files)).withName(MavenDomBundle.message("fix.add.dependency")).run(() -> { PsiDocumentManager pdm = PsiDocumentManager.getInstance(myProject); for (Trinity<MavenDomProjectModel, MavenId, String> trinity : models) { final MavenDomProjectModel model = trinity.first; MavenDomDependency dependency = MavenDomUtil.createDomDependency(model, null, trinity.second); String ms = trinity.third; if (ms != null) { dependency.getScope().setStringValue(ms); } Document document = pdm.getDocument(DomUtil.getFile(model)); if (document != null) { pdm.doPostponedOperationsAndUnblockDocument(document); FileDocumentManager.getInstance().saveDocument(document); } } }); return myProjectsManager.forceUpdateProjects(projectToUpdate); } @Nullable @Override public Promise<Void> addExternalLibraryDependency(@NotNull Collection<? extends Module> modules, @NotNull ExternalLibraryDescriptor descriptor, @NotNull DependencyScope scope) { for (Module module : modules) { if (!myProjectsManager.isMavenizedModule(module)) { return null; } } MavenId mavenId = new MavenId(descriptor.getLibraryGroupId(), descriptor.getLibraryArtifactId(), null); return addDependency(modules, mavenId, descriptor.getMinVersion(), descriptor.getMaxVersion(), descriptor.getPreferredVersion(), scope); } @NotNull private String selectVersion(@NotNull MavenId mavenId, @Nullable String minVersion, @Nullable String maxVersion, @Nullable String preferredVersion) { Set<String> versions = myIndicesManager.getVersions(mavenId.getGroupId(), mavenId.getArtifactId()); if (preferredVersion != null && versions.contains(preferredVersion)) { return preferredVersion; } List<String> suitableVersions = new ArrayList<>(); for (String version : versions) { if ((minVersion == null || VersionComparatorUtil.compare(minVersion, version) <= 0) && (maxVersion == null || VersionComparatorUtil.compare(version, maxVersion) <= 0)) { suitableVersions.add(version); } } if (suitableVersions.isEmpty()) { return mavenId.getVersion() == null ? "RELEASE" : mavenId.getVersion(); } return Collections.max(suitableVersions, VersionComparatorUtil.COMPARATOR); } @Nullable @Override public Promise<Void> addLibraryDependency(@NotNull Module from, @NotNull Library library, @NotNull DependencyScope scope, boolean exported) { String name = library.getName(); if (name != null && name.startsWith(MavenArtifact.MAVEN_LIB_PREFIX)) { //it would be better to use RepositoryLibraryType for libraries imported from Maven and fetch mavenId from the library properties instead String mavenCoordinates = StringUtil.trimStart(name, MavenArtifact.MAVEN_LIB_PREFIX); return addDependency(Collections.singletonList(from), new MavenId(mavenCoordinates), scope); } return null; } @Override public Promise<Void> changeLanguageLevel(@NotNull Module module, @NotNull final LanguageLevel level) { if (!myProjectsManager.isMavenizedModule(module)) return null; MavenProject mavenProject = myProjectsManager.findProject(module); if (mavenProject == null) return null; final MavenDomProjectModel model = MavenDomUtil.getMavenDomProjectModel(myProject, mavenProject.getFile()); if (model == null) return null; WriteCommandAction.writeCommandAction(myProject, DomUtil.getFile(model)).withName(MavenDomBundle.message("fix.add.dependency")).run(() -> { PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject); Document document = documentManager.getDocument(DomUtil.getFile(model)); if (document != null) { documentManager.commitDocument(document); } XmlTag tag = getCompilerPlugin(model).getConfiguration().ensureTagExists(); String option = JpsJavaSdkType.complianceOption(level.toJavaVersion()); setChildTagValue(tag, "source", option); setChildTagValue(tag, "target", option); if (level.isPreview()) { setChildTagValue(tag, "compilerArgs","--enable-preview"); } if (document != null) { FileDocumentManager.getInstance().saveDocument(document); } }); return myProjectsManager.forceUpdateProjects(Collections.singleton(mavenProject)); } private static void setChildTagValue(@NotNull XmlTag tag, @NotNull String subTagName, @NotNull String value) { XmlTag subTag = tag.findFirstSubTag(subTagName); if (subTag != null) { subTag.getValue().setText(value); } else { tag.addSubTag(tag.createChildTag(subTagName, tag.getNamespace(), value, false), false); } } @NotNull private static MavenDomPlugin getCompilerPlugin(MavenDomProjectModel model) { MavenDomPlugins plugins = model.getBuild().getPlugins(); for (MavenDomPlugin plugin : plugins.getPlugins()) { if ("org.apache.maven.plugins".equals(plugin.getGroupId().getValue()) && "maven-compiler-plugin".equals(plugin.getArtifactId().getValue())) { return plugin; } } MavenDomPlugin plugin = plugins.addPlugin(); plugin.getGroupId().setValue("org.apache.maven.plugins"); plugin.getArtifactId().setValue("maven-compiler-plugin"); return plugin; } private static String getMavenScope(@NotNull DependencyScope scope) { switch (scope) { case RUNTIME: return MavenConstants.SCOPE_RUNTIME; case COMPILE: return MavenConstants.SCOPE_COMPILE; case TEST: return MavenConstants.SCOPE_TEST; case PROVIDED: return MavenConstants.SCOPE_PROVIDED; default: throw new IllegalArgumentException(String.valueOf(scope)); } } }
/* * This file is part of the Cliche project, licensed under MIT License. * See LICENSE.txt file in root folder of Cliche sources. */ package asg.cliche; import java.util.ArrayList; import java.util.List; /** * Token associates index of a token in the input line with the token itself, * in order to be able to provide helpful error indecation (see below :) * ------------------------------------------------^ Misspelled word! (Exactly how it should work). * * This class is immutable. * * Parsing procedural module is also within. */ public class Token { private int index; private String string; public Token(int index, String string) { super(); this.index = index; this.string = string; } public final int getIndex() { return index; } public final String getString() { return string; } @Override public String toString() { return (string != null ? string : "(null)") + ":" + Integer.toString(index); } @Override public boolean equals(Object obj) { // The contents generated by NetBeans. if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Token other = (Token)obj; if ((this.string == null) ? (other.string != null) : !this.string.equals(other.string)) { return false; } return true; } @Override public int hashCode() { int hash = 5; hash = 43 * hash + (this.string != null ? this.string.hashCode() : 0); return hash; } // *** Parser procmodule begins here *** /** * State machine input string tokenizer. * * @param input String to be tokenized * @return List of tokens * * @see asg.cliche.Shell.Token * @see asg.cliche.Shell.escapeString */ /*package-private for tests*/ static List<Token> tokenize(final String input) { List<Token> result = new ArrayList<Token>(); if (input == null) { return result; } final int WHITESPACE = 0; final int WORD = 1; final int STRINGDQ = 2; final int STRINGSQ = 3; final int COMMENT = 4; int state = WHITESPACE; char ch; // character in hand int tokenIndex = -1; StringBuilder token = new StringBuilder(""); for (int i = 0; i < input.length(); i++) { ch = input.charAt(i); switch (state) { case WHITESPACE: if (Character.isWhitespace(ch)) { // keep state } else if (Character.isLetterOrDigit(ch) || ch == '_') { state = WORD; tokenIndex = i; token.append(ch); } else if (ch == '"') { state = STRINGDQ; tokenIndex = i; } else if (ch == '\'') { state = STRINGSQ; tokenIndex = i; } else if (ch == '#') { state = COMMENT; } else { state = WORD; tokenIndex = i; token.append(ch); } break; case WORD: if (Character.isWhitespace(ch)) { // submit token result.add(new Token(tokenIndex, token.toString())); token.setLength(0); state = WHITESPACE; } else if (Character.isLetterOrDigit(ch) || ch == '_') { token.append(ch); // and keep state } else if (ch == '"') { if (i < input.length()-1 && input.charAt(i+1) == '"' ) { // Yes, it's somewhat wrong in terms of statemachine, but it's the // simplest and crearest way. token.append('"'); i++; // and keep state. } else { state = STRINGDQ; // but don't append; a"b"c is the same as abc. } } else if (ch == '\'') { if (i < input.length()-1 && input.charAt(i+1) == '\'' ) { // Yes, it's somewhat wrong in terms of statemachine, but it's the // simplest and crearest way. token.append('\''); i++; // and keep state. } else { state = STRINGSQ; // but don't append; a"b"c is the same as abc. } } else if (ch == '#') { // submit token result.add(new Token(tokenIndex, token.toString())); token.setLength(0); state = COMMENT; } else { // for now we do allow special chars in words token.append(ch); } break; case STRINGDQ: if (ch == '"') { if (i < input.length() - 1 && input.charAt(i+1) == '"') { token.append('"'); i++; // and keep state } else { state = WORD; } } else { token.append(ch); } break; case STRINGSQ: if (ch == '\'') { if (i < input.length() - 1 && input.charAt(i+1) == '\'') { token.append('\''); i++; // and keep state } else { state = WORD; } } else { token.append(ch); } break; case COMMENT: // eat ch break; default: assert false : "Unknown state in Shell.tokenize() state machine"; break; } } if (state == WORD || state == STRINGDQ || state == STRINGSQ) { result.add(new Token(tokenIndex, token.toString())); } return result; } /** * Escape given string so that tokenize(escapeString(str)).get(0).getString === str. * @param input String to be escaped * @return escaped string */ public static String escapeString(String input) { StringBuilder escaped = new StringBuilder(input.length() + 10); escaped.append('"'); for (int i = 0; i < input.length(); i++) { if (input.charAt(i) == '"') { escaped.append("\"\""); } else { escaped.append(input.charAt(i)); } } escaped.append('"'); return escaped.toString(); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tat.indicator; import java.util.Calendar; import java.util.Collections; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.TreeMap; import java.util.concurrent.ConcurrentSkipListSet; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import tat.data.ChartType; import tat.data.OHLC; /** * * @author tangz */ public class OpenPriceTest { private ConcurrentSkipListSet<OHLC> rawData = new ConcurrentSkipListSet(); private ConcurrentSkipListSet<OHLC> aList; private ObservableList<OHLC> bList = FXCollections.observableArrayList(); private Calendar day1 = new GregorianCalendar(2009, 11, 14, 0, 0, 0); private Calendar day2 = new GregorianCalendar(2009, 11, 15, 0, 0, 0); private Calendar day3 = new GregorianCalendar(2009, 11, 16, 0, 0, 0); private Calendar day4 = new GregorianCalendar(2009, 11, 17, 0, 0, 0); private Calendar day5 = new GregorianCalendar(2009, 11, 18, 0, 0, 0); private Calendar day6 = new GregorianCalendar(2009, 11, 21, 0, 0, 0); private Calendar day7 = new GregorianCalendar(2009, 11, 22, 0, 0, 0); private Calendar day8 = new GregorianCalendar(2009, 11, 23, 0, 0, 0); private Calendar day9 = new GregorianCalendar(2009, 11, 24, 0, 0, 0); private Calendar day10 = new GregorianCalendar(2009, 11, 28, 0, 0, 0); //Setup testing data OHLC aqcOhlc1 = new OHLC("AQC", day1, 1.33f, 1f, 1f, 1.075f, 100000); OHLC aqcOhlc2 = new OHLC("AQC", day2, 2.33f, 1f, 1f, 1.08f, 200000); OHLC aqcOhlc3 = new OHLC("AQC", day3, 3.33f, 1f, 1f, 1.07f, 300000); OHLC aqcOhlc4 = new OHLC("AQC", day4, 4.33f, 1f, 1f, 1.05f, 400000); OHLC aqcOhlc5 = new OHLC("AQC", day5, 5.33f, 1f, 1f, 1.045f, 500000); OHLC aqcOhlc6 = new OHLC("AQC", day6, 6.33f, 1f, 1f, 1.035f, 600000); OHLC aqcOhlc7 = new OHLC("AQC", day7, 7.33f, 1f, 1f, 1.025f, 700000); OHLC aqcOhlc8 = new OHLC("AQC", day8, 8.33f, 1f, 1f, 1.02f, 800000); OHLC aqcOhlc9 = new OHLC("AQC", day9, 9.33f, 1f, 1f, 1.025f, 900000); OHLC aqcOhlc10 = new OHLC("AQC", day10, 10.33f, 1f, 1f, 1.015f, 1000000); public OpenPriceTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { bList.add(aqcOhlc1); bList.add(aqcOhlc2); bList.add(aqcOhlc3); bList.add(aqcOhlc4); bList.add(aqcOhlc5); bList.add(aqcOhlc6); bList.add(aqcOhlc7); bList.add(aqcOhlc8); bList.add(aqcOhlc9); bList.add(aqcOhlc10); Collections.sort(bList, OHLC.dateComparator); aList = new ConcurrentSkipListSet<>(bList); } @After public void tearDown() { } /** * Test of toString method, of class OpenPrice. */ @Test public void testToString() { System.out.println("toString"); OpenPrice instance = new OpenPrice("UUID"); String expResult = "Daily Open Price"; String result = instance.toString().trim(); assertEquals(expResult, result); instance.setChartType(ChartType.WEEK); expResult = "Weekly Open Price"; result = instance.toString().trim(); assertEquals(expResult, result); } /** * Test of setChartType method, of class OpenPrice. */ @Test public void testSetChartType() { System.out.println("setChartType"); OpenPrice instance = new OpenPrice("UUID"); String expResult = "Daily Open Price"; String result = instance.toString().trim(); assertEquals(expResult, result); instance.setChartType(ChartType.WEEK); expResult = "Weekly Open Price"; result = instance.toString().trim(); assertEquals(expResult, result); } /** * Test of getChartType method, of class OpenPrice. */ @Test public void testGetChartType() { System.out.println("getChartType"); OpenPrice instance = new OpenPrice("UUID"); instance.setChartType(ChartType.HOUR); assertEquals(ChartType.HOUR, instance.getChartType()); } /** * Test of getPrimaryKey method, of class OpenPrice. */ @Test public void testGetPrimaryKey() { System.out.println("getPrimaryKey"); OpenPrice instance = new OpenPrice("UUID_NEW"); String expResult = "UUID_NEW"; String actul = instance.getPrimaryKey().trim(); assertEquals(expResult, actul); } /** * Test of setPrimaryKey method, of class OpenPrice. */ @Test public void testSetPrimaryKey() { System.out.println("setPrimaryKey"); String primaryKey = "UUID_SUPA"; OpenPrice instance = new OpenPrice("UUID"); instance.setPrimaryKey(primaryKey); assertEquals(primaryKey, instance.getPrimaryKey()); } /** * Test of doCalculation method, of class OpenPrice. */ @Test public void testDoCalculation_ObservableList() { System.out.println("doCalculation"); ObservableList<OHLC> data = bList; OpenPrice instance = new OpenPrice("UUID"); assertEquals(0, instance.getData().size()); instance.doCalculation(data); assertEquals(10, instance.getData().size()); Float result = 6.33f; assertEquals(result,(Float)instance.getData(day6), 0.01); } /** * Test of doCalculation method, of class OpenPrice. */ @Test public void testDoCalculation_ConcurrentSkipListSet() { System.out.println("doCalculation"); ConcurrentSkipListSet<OHLC> orgData = aList; OpenPrice instance = new OpenPrice("UUID"); instance.doCalculation(orgData); Float result = 1.33f; assertEquals(result, (Float)instance.getData().get(day1), 0.01); result = 2.33f; assertEquals(result, (Float)instance.getData().get(day2), 0.01); result = 3.33f; assertEquals(result, (Float)instance.getData().get(day3), 0.01); } /** * Test of doCalculation method, of class OpenPrice. */ @Test (expected = UnsupportedOperationException.class) public void testDoCalculation_ObservableList_ObservableList() { System.out.println("doCalculation"); ObservableList<OHLC> numeratorData = null; ObservableList<OHLC> denominatorData = null; OpenPrice instance = new OpenPrice("UUID"); instance.doCalculation(numeratorData, denominatorData); } /** * Test of doCalculation method, of class OpenPrice. */ @Test (expected = UnsupportedOperationException.class) public void testDoCalculation_ConcurrentSkipListSet_ConcurrentSkipListSet() { System.out.println("doCalculation"); ConcurrentSkipListSet<OHLC> numeratorData = null; ConcurrentSkipListSet<OHLC> denomiatorData = null; OpenPrice instance = new OpenPrice("UUID"); instance.doCalculation(numeratorData, denomiatorData); } /** * Test of getAllTimeHigh method, of class OpenPrice. */ @Test public void testGetMaxData() { System.out.println("getMaxData"); ObservableList<OHLC> data = bList; OpenPrice instance = new OpenPrice("UUID"); assertEquals(0, instance.getData().size()); instance.doCalculation(data); assertEquals(10, instance.getData().size()); Float result = 6.33f; assertEquals(result,(Float)instance.getData(day6), 0.01); Float max = 10.33f; assertEquals(max, (Float)instance.getAllTimeHigh(), 0.01); } /** * Test of getAllTimeLow method, of class OpenPrice. */ @Test public void testGetMinData() { System.out.println("getMinData"); ObservableList<OHLC> data = bList; OpenPrice instance = new OpenPrice("UUID"); assertEquals(0, instance.getData().size()); instance.doCalculation(data); assertEquals(10, instance.getData().size()); Float result = 6.33f; assertEquals(result,(Float)instance.getData(day6), 0.01); Float min = 1.33f; assertEquals(min, (Float)instance.getAllTimeLow(), 0.01); } /** * Test of getData method, of class OpenPrice. */ @Test public void testGetData_Calendar() { System.out.println("getData"); ObservableList<OHLC> data = bList; OpenPrice instance = new OpenPrice("UUID"); assertEquals(0, instance.getData().size()); instance.doCalculation(data); assertEquals(10, instance.getData().size()); Float result = 6.33f; assertEquals(result,(Float)instance.getData(day6), 0.01); Float max = 10.33f; assertEquals(max, (Float)instance.getAllTimeHigh(), 0.01); result = 4.33f; assertEquals(result, (Float)instance.getData(day4), 0.01); } /** * Test of getData method, of class OpenPrice. */ @Test public void testGetData_0args() { System.out.println("getData"); ObservableList<OHLC> data = bList; OpenPrice instance = new OpenPrice("UUID"); assertEquals(0, instance.getData().size()); instance.doCalculation(data); assertEquals(10, instance.getData().size()); Float result = 6.33f; assertEquals(result,(Float)instance.getData(day6), 0.01); Float max = 10.33f; assertEquals(max, (Float)instance.getAllTimeHigh(), 0.01); result = 4.33f; assertEquals(result, (Float)instance.getData().get(day4), 0.01); } /** * Test of getAverageOfLast method, of class OpenPrice. */ @Test public void testGetAverageOfLast() { System.out.println("getAverageOfLast"); ObservableList<OHLC> data = bList; OpenPrice instance = new OpenPrice("UUID"); assertEquals(0, instance.getData().size()); instance.doCalculation(data); Float result = 7.83f; assertEquals(result, (Float)instance.getAverageOfLast(6), 0.01); } /** * Test of get52weekHigh method, of class OpenPrice. */ @Test public void testGet52weekHigh() { System.out.println("get52weekHigh"); ObservableList<OHLC> data = bList; OpenPrice instance = new OpenPrice("UUID"); assertEquals(0, instance.getData().size()); instance.doCalculation(data); Float result = 10.33f; assertEquals(result, (Float)instance.get52weekHigh(), 0.01); } /** * Test of get52weekLow method, of class OpenPrice. */ @Test public void testGet52weekLow() { System.out.println("get52weekLow"); ObservableList<OHLC> data = bList; OpenPrice instance = new OpenPrice("UUID"); assertEquals(0, instance.getData().size()); instance.doCalculation(data); Float result = 1.33f; assertEquals(result, (Float)instance.get52weekLow(), 0.01); } /** * Test of getDataType method, of class OpenPrice. */ @Test public void testGetDataType() { System.out.println("getDataType"); OpenPrice instance = new OpenPrice("UUID"); assertEquals(DataType.FLOAT, instance.getDataType()); } /** * Test of GetDurationHigh with exception */ @Test (expected = IllegalArgumentException.class) public void testGetDurationHigh_WithException() { System.out.println("testGetDurationHigh_WithException"); ObservableList<OHLC> data = bList; OpenPrice instance = new OpenPrice("UUID"); assertEquals(0, instance.getData().size()); instance.doCalculation(data); Float result = 1.33f; assertEquals(result, (Float)instance.getDurationHigh(new Duration(ChartType.WEEK, 4)), 0.01); } /** * Test of GetDurationHigh without exception */ @Test public void testGetDurationHigh() { System.out.println("testGetDurationHigh"); ObservableList<OHLC> data = bList; OpenPrice instance = new OpenPrice("UUID"); assertEquals(0, instance.getData().size()); instance.doCalculation(data); Float result = 10.33f; assertEquals(result, (Float)instance.getDurationHigh(new Duration(ChartType.DAY, 4)), 0.01); } /** * Test of GetDurationHigh with exception */ @Test (expected = IllegalArgumentException.class) public void testGetDurationLow_WithException() { System.out.println("testGetDurationLow_WithException"); ObservableList<OHLC> data = bList; OpenPrice instance = new OpenPrice("UUID"); assertEquals(0, instance.getData().size()); instance.doCalculation(data); Float result = 1.33f; assertEquals(result, (Float)instance.getDurationLow(new Duration(ChartType.WEEK, 4)), 0.01); } /** * Test of GetDurationLow without exception */ @Test public void testGetDurationLow() { System.out.println("testGetDurationLow"); ObservableList<OHLC> data = bList; OpenPrice instance = new OpenPrice("UUID"); assertEquals(0, instance.getData().size()); instance.doCalculation(data); Float result = 7.33f; assertEquals(result, (Float)instance.getDurationLow(new Duration(ChartType.DAY, 4)), 0.01); } /** * Test of getReversedData for OpenPrice indicator */ @Test public void testGetReversedData() { System.out.println("testGetReversedData"); ObservableList<OHLC> data = bList; OpenPrice instance = new OpenPrice("UUID"); assertEquals(0, instance.getData().size()); instance.doCalculation(data); Iterator<Calendar> it = instance.getData().keySet().iterator(); while(it.hasNext()) { Calendar date = it.next(); Number value = (Number)instance.getData().get(date); System.out.println(date.getTime().toString() + " : " + value); } System.out.println(" -------------------- "); Iterator<Calendar> itr = instance.getReversedData().keySet().iterator(); while(itr.hasNext()){ Calendar date = itr.next(); Number value = (Number)instance.getReversedData().get(date); System.out.println(date.getTime().toString() + " : " + value); } } }
package com.comcast.cdn.traffic_control.traffic_monitor.data; import org.apache.log4j.Logger; import java.util.Arrays; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; public class StatisticsLog { private static final Logger LOGGER = Logger.getLogger(StatisticsLog.class); private final Map<String,Deque<DataPoint>> data = new HashMap<String,Deque<DataPoint>>(); protected final Set<String> hiddenKeys = new HashSet<String>(); private final List<Long> times = new LinkedList<Long>(); private final List<Long> indexes = new LinkedList<Long>(); private int index; public Deque<DataPoint> get(final String key) { return data.get(key); } public void putDataPoint(final String key, final String value) { Deque<DataPoint> statistics = data.get(key); if (statistics == null) { statistics = new LinkedList<DataPoint>(); synchronized(data) { data.put(key, statistics); } } DataPoint dataPoint = getLastDataPoint(key); if (dataPoint != null && dataPoint.matches(value)) { dataPoint.update(index); return; } dataPoint = new DataPoint(value, index); statistics.addLast(dataPoint); } private DataPoint getLastDataPoint(final String key) { if (!hasValue(key)) { return null; } return data.get(key).getLast(); } public Set<String> getKeys() { return data.keySet(); } public boolean hasValue(final String key) { return data.containsKey(key) && (!data.get(key).isEmpty()); } public String getLastValue(final String key) { final DataPoint dataPoint = getLastDataPoint(key); return (dataPoint != null) ? dataPoint.getValue() : null; } public String getValue(final String key, final long targetIndex) { if (!hasValue(key)) { return null; } Iterator<DataPoint> dataPoints = get(key).descendingIterator(); while (dataPoints.hasNext()) { final DataPoint dataPoint = dataPoints.next(); if (targetIndex > dataPoint.getIndex()) { return null; } if (targetIndex <= (dataPoint.getIndex() - dataPoint.getSpan())) { continue; } return dataPoint.getValue(); } return null; } public boolean getBool(final String key) { try { return Boolean.parseBoolean(getLastValue(key)); } catch (Exception e) { return true; } } public long getLong(final String key) { try { return Long.parseLong(getLastValue(key)); } catch (Exception e) { return 0; } } public double getDouble(final String key) { try { return Double.parseDouble(getLastValue(key)); } catch (Exception e) { return 0; } } private Set<String> filterKeys(final String[] statList, final boolean wildcard) { Set<String> statisticsKeys; if (statList == null) { return getKeys(); } if (!wildcard) { return new HashSet<String>(Arrays.asList(statList)); } statisticsKeys = new HashSet<String>(); for (String key : getKeys()) { for (String stat : statList) { if (key.toLowerCase().contains(stat.toLowerCase())) { statisticsKeys.add(key); break; } } } return statisticsKeys; } public Map<String, Deque<DataPoint>> filter(final int maxItems, final String[] statList, final boolean wildcard, final boolean allowHidden) { final Map<String, Deque<DataPoint>> filteredStatistics = new HashMap<String,Deque<DataPoint>>(); synchronized(data) { Set<String> statisticsKeys = filterKeys(statList, wildcard); for (String key : statisticsKeys) { if (!data.containsKey(key) || (!allowHidden && hiddenKeys.contains(key))) { continue; } final LinkedList<DataPoint> statistics = (LinkedList<DataPoint>) data.get(key); if (maxItems == 0 || statistics.size() <= 1) { filteredStatistics.put(key, statistics); } else { /* * If fromIndex == toIndex, List.subList() will return an empty list. * The only way they will be equal is if the list is empty or * has a single item, which is handled above. */ final int toIndex = statistics.size(); final int fromIndex = Math.max(0, toIndex - maxItems); filteredStatistics.put(key, new LinkedList<DataPoint>(statistics.subList(fromIndex, toIndex))); } } } return filteredStatistics; } public void addHiddenStats(Set<String> keys) { hiddenKeys.addAll(keys); } public long getTime(final DataPoint dataPoint) { return getTime(dataPoint.getIndex()); } public long getTime(final long targetIndex) { synchronized(times) { for (long index : indexes) { if (index == targetIndex) { return times.get(indexes.indexOf(index)); } } } return 0; } public void prepareForUpdate(final String stateId, final long historyTime) { synchronized(times) { addNullDataForIndex(index); index++; final long time = System.currentTimeMillis(); final long removeTime = time - historyTime; int removeCount = 0; times.add(time); indexes.add(new Long(index)); while (times.get(0) < removeTime) { removeCount++; times.remove(0); } if (removeCount == 0) { return; } for (int i = 0; i < removeCount; i++) { indexes.remove(0); } removeOldest(stateId); } } private void addNullDataForIndex(final long index) { synchronized (data) { for(String key : data.keySet()) { DataPoint lastDataPoint = getLastDataPoint(key); if (lastDataPoint == null || lastDataPoint.getIndex() != index) { putDataPoint(key, null); } } } } private void removeOldest(final String stateId) { final long oldestIndex = indexes.get(0); for(String key : data.keySet()) { final Deque<DataPoint> dataPoints = get(key); if (dataPoints.isEmpty()) { LOGGER.warn("list empty for " + key + " - " + stateId); continue; } while (dataPoints.getFirst().getIndex() < oldestIndex) { if (dataPoints.size() == 1) { LOGGER.warn(String.format("%s - %s: index %d < baseIndex %d", key, stateId, dataPoints.getFirst().getIndex(), oldestIndex)); break; } dataPoints.remove(); if (dataPoints.isEmpty()) { LOGGER.warn(String.format("list empty for %s - %s", key, stateId)); } } } } }
/* * Copyright 2017 Nikolas Falco * 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.github.nfalco79.junit4osgi.registry.internal; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.*; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.example.JUnit3Test; import org.example.MyServiceIT; import org.example.SimpleITTest; import org.example.SimpleTestCase; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.ArgumentCaptor; import org.mockito.internal.util.io.IOUtil; import org.osgi.framework.Bundle; import org.osgi.service.log.LogService; import com.github.nfalco79.junit4osgi.registry.internal.util.BundleBuilder; import com.github.nfalco79.junit4osgi.registry.spi.TestBean; import com.github.nfalco79.junit4osgi.registry.spi.TestRegistryChangeListener; import com.github.nfalco79.junit4osgi.registry.spi.TestRegistryEvent; import com.github.nfalco79.junit4osgi.registry.spi.TestRegistryEvent.TestRegistryEventType; public class ManifestRegistryTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void jar_with_missing_manifest() throws Exception { LogService logService = spy(LogService.class); ManifestRegistry registry = new ManifestRegistry(); registry.setLog(logService); registry.registerTests(getMockBundle()); assertThat(registry.getTests(), Matchers.empty()); verify(logService).log(eq(LogService.LOG_WARNING), contains("No MANIFEST for bundle")); registry.dispose(); } @Test public void test_jmx_method_get_test_ids() throws Exception { Bundle bundle = getMockBundle(SimpleTestCase.class, JUnit3Test.class); ManifestRegistry registry = new ManifestRegistry(); registry.setLog(mock(LogService.class)); registry.registerTests(bundle); assertThat(registry.getTestIds(), Matchers.arrayContainingInAnyOrder("acme@" + SimpleTestCase.class.getName(), "acme@" + JUnit3Test.class.getName())); } @Test public void bundle_are_not_registered_twice() throws Exception { Bundle bundle = getMockBundle(SimpleTestCase.class, JUnit3Test.class); ManifestRegistry registry = new ManifestRegistry(); registry.setLog(mock(LogService.class)); registry.registerTests(bundle); registry.registerTests(bundle); assertThat(registry.getTests(), Matchers.hasSize(2)); assertThat(registry.getTests(), Matchers.hasItems(new TestBean(bundle, SimpleTestCase.class.getName()), new TestBean(bundle, JUnit3Test.class.getName()))); verify(bundle).getEntry("META-INF/MANIFEST.MF"); } @Test public void testclass_not_found() throws Exception { LogService logService = spy(LogService.class); String className = "com.acme.Foo"; Bundle bundle = BundleBuilder.newBuilder() // .symbolicName("acme") // .addResource("META-INF/MANIFEST.MF", getManifest(className)) // .state(Bundle.ACTIVE) // .build(); ManifestRegistry registry = new ManifestRegistry(); registry.setLog(logService); registry.registerTests(bundle); assertThat(registry.getTests(), Matchers.empty()); String expectedLog = "Test class '" + className + "' could not be found in the bundle " + bundle.getSymbolicName(); verify(logService).log(eq(LogService.LOG_ERROR), contains(expectedLog), any(Exception.class)); registry.dispose(); } @Test public void registry_must_returns_the_expected_tests() throws Exception { TestRegistryChangeListener listener = spy(TestRegistryChangeListener.class); Class<?> testsClass[] = new Class<?>[] { SimpleTestCase.class, JUnit3Test.class }; Bundle bundle = getMockBundle(testsClass); ManifestRegistry registry = new ManifestRegistry(); registry.setLog(mock(LogService.class)); registry.addTestRegistryListener(listener); registry.registerTests(bundle); Set<TestBean> tests = registry.getTests(); assertThat(tests, Matchers.hasSize(2)); assertThat(tests, Matchers.hasItems(new TestBean(bundle, testsClass[0].getName()), new TestBean(bundle, testsClass[1].getName()))); ArgumentCaptor<TestRegistryEvent> argument = ArgumentCaptor.forClass(TestRegistryEvent.class); verify(listener, times(2)).registryChanged(argument.capture()); for (TestRegistryEvent event : argument.getAllValues()) { assertThat(event.getType(), Matchers.is(TestRegistryEventType.ADD)); } registry.dispose(); } @Test public void remove_a_contributor_fires_a_remove_event() throws Exception { Bundle bundle = getMockBundle(SimpleTestCase.class, JUnit3Test.class); ManifestRegistry registry = new ManifestRegistry(); registry.setLog(mock(LogService.class)); registry.registerTests(bundle); TestRegistryChangeListener listener = spy(TestRegistryChangeListener.class); registry.addTestRegistryListener(listener); registry.removeTests(bundle); ArgumentCaptor<TestRegistryEvent> argument = ArgumentCaptor.forClass(TestRegistryEvent.class); verify(listener, times(2)).registryChanged(argument.capture()); for (TestRegistryEvent event : argument.getAllValues()) { assertThat(event.getType(), Matchers.is(TestRegistryEventType.REMOVE)); } registry.dispose(); } @Test public void remove_a_contributor_removes_only_tests_contributed_by_that_bundle() throws Exception { Bundle bundle1 = getMockBundle(SimpleTestCase.class, JUnit3Test.class); Bundle bundle2 = getMockBundle(MyServiceIT.class, SimpleITTest.class); ManifestRegistry registry = new ManifestRegistry(); registry.setLog(mock(LogService.class)); registry.registerTests(bundle1); registry.registerTests(bundle2); assertThat(registry.getTests(), Matchers.hasSize(4)); registry.removeTests(bundle1); assertThat(registry.getTests(), Matchers.hasSize(2)); assertThat(registry.getTests(), Matchers.hasItems(new TestBean(bundle2, MyServiceIT.class.getName()), new TestBean(bundle2, SimpleITTest.class.getName()))); registry.dispose(); } private File getManifest(String... className) throws Exception { StringBuilder sb = new StringBuilder(); for (String clazz : className) { sb.append(clazz).append(","); } Manifest mf = new Manifest(); Attributes mainAttributes = mf.getMainAttributes(); mainAttributes.putValue("Manifest-Version", "1.0"); mainAttributes.putValue(ManifestRegistry.TEST_ENTRY, sb.toString()); File manifestFile = folder.newFile(); OutputStream fos = new FileOutputStream(manifestFile); try { mf.write(fos); } finally { IOUtil.closeQuietly(fos); } return manifestFile; } private Bundle getMockBundle(final Class<?>... testsClass) throws Exception { BundleBuilder builder = BundleBuilder.newBuilder() // .symbolicName("acme") // .addClasses(testsClass); if (testsClass != null && testsClass.length > 0) { String[] classesName = new String[testsClass.length]; for (int i = 0; i < testsClass.length; i++) { classesName[i] = testsClass[i].getName(); } builder.addResource("META-INF/MANIFEST.MF", getManifest(classesName)); } return builder.build(); } }
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.kinesis.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kinesis-2013-12-02/UpdateShardCount" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class UpdateShardCountResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The name of the stream. * </p> */ private String streamName; /** * <p> * The current number of shards. * </p> */ private Integer currentShardCount; /** * <p> * The updated number of shards. * </p> */ private Integer targetShardCount; /** * <p> * The name of the stream. * </p> * * @param streamName * The name of the stream. */ public void setStreamName(String streamName) { this.streamName = streamName; } /** * <p> * The name of the stream. * </p> * * @return The name of the stream. */ public String getStreamName() { return this.streamName; } /** * <p> * The name of the stream. * </p> * * @param streamName * The name of the stream. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateShardCountResult withStreamName(String streamName) { setStreamName(streamName); return this; } /** * <p> * The current number of shards. * </p> * * @param currentShardCount * The current number of shards. */ public void setCurrentShardCount(Integer currentShardCount) { this.currentShardCount = currentShardCount; } /** * <p> * The current number of shards. * </p> * * @return The current number of shards. */ public Integer getCurrentShardCount() { return this.currentShardCount; } /** * <p> * The current number of shards. * </p> * * @param currentShardCount * The current number of shards. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateShardCountResult withCurrentShardCount(Integer currentShardCount) { setCurrentShardCount(currentShardCount); return this; } /** * <p> * The updated number of shards. * </p> * * @param targetShardCount * The updated number of shards. */ public void setTargetShardCount(Integer targetShardCount) { this.targetShardCount = targetShardCount; } /** * <p> * The updated number of shards. * </p> * * @return The updated number of shards. */ public Integer getTargetShardCount() { return this.targetShardCount; } /** * <p> * The updated number of shards. * </p> * * @param targetShardCount * The updated number of shards. * @return Returns a reference to this object so that method calls can be chained together. */ public UpdateShardCountResult withTargetShardCount(Integer targetShardCount) { setTargetShardCount(targetShardCount); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getStreamName() != null) sb.append("StreamName: ").append(getStreamName()).append(","); if (getCurrentShardCount() != null) sb.append("CurrentShardCount: ").append(getCurrentShardCount()).append(","); if (getTargetShardCount() != null) sb.append("TargetShardCount: ").append(getTargetShardCount()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof UpdateShardCountResult == false) return false; UpdateShardCountResult other = (UpdateShardCountResult) obj; if (other.getStreamName() == null ^ this.getStreamName() == null) return false; if (other.getStreamName() != null && other.getStreamName().equals(this.getStreamName()) == false) return false; if (other.getCurrentShardCount() == null ^ this.getCurrentShardCount() == null) return false; if (other.getCurrentShardCount() != null && other.getCurrentShardCount().equals(this.getCurrentShardCount()) == false) return false; if (other.getTargetShardCount() == null ^ this.getTargetShardCount() == null) return false; if (other.getTargetShardCount() != null && other.getTargetShardCount().equals(this.getTargetShardCount()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getStreamName() == null) ? 0 : getStreamName().hashCode()); hashCode = prime * hashCode + ((getCurrentShardCount() == null) ? 0 : getCurrentShardCount().hashCode()); hashCode = prime * hashCode + ((getTargetShardCount() == null) ? 0 : getTargetShardCount().hashCode()); return hashCode; } @Override public UpdateShardCountResult clone() { try { return (UpdateShardCountResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
package org.sagebionetworks.bridge.exporter.handler; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyListOf; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.notNull; import static org.mockito.Matchers.same; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Multiset; import org.mockito.ArgumentCaptor; import org.sagebionetworks.bridge.exporter.synapse.ColumnDefinition; import org.sagebionetworks.repo.model.table.ColumnChange; import org.sagebionetworks.repo.model.table.ColumnModel; import org.sagebionetworks.repo.model.table.ColumnType; import org.sagebionetworks.repo.model.table.TableSchemaChangeRequest; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.sagebionetworks.bridge.config.Config; import org.sagebionetworks.bridge.exporter.exceptions.BridgeExporterException; import org.sagebionetworks.bridge.exporter.exceptions.BridgeExporterNonRetryableException; import org.sagebionetworks.bridge.exporter.exceptions.BridgeExporterTsvException; import org.sagebionetworks.bridge.exporter.metrics.Metrics; import org.sagebionetworks.bridge.exporter.synapse.SynapseHelper; import org.sagebionetworks.bridge.exporter.util.TestUtil; import org.sagebionetworks.bridge.exporter.worker.ExportSubtask; import org.sagebionetworks.bridge.exporter.worker.ExportTask; import org.sagebionetworks.bridge.exporter.worker.ExportWorkerManager; import org.sagebionetworks.bridge.exporter.worker.TsvInfo; import org.sagebionetworks.bridge.file.InMemoryFileHelper; @SuppressWarnings({ "rawtypes", "unchecked" }) public class SynapseExportHandlerUpdateTableTest { private static final List<ColumnDefinition> MOCK_COLUMN_DEFINITION; private static final List<ColumnModel> MOCK_COLUMN_LIST; private static final List<ColumnModel> MOCK_EXISTING_COLUMN_LIST; static { MOCK_COLUMN_DEFINITION = SynapseExportHandlerTest.createTestSynapseColumnDefinitions(); MOCK_COLUMN_LIST = SynapseExportHandlerTest.createTestSynapseColumnList(MOCK_COLUMN_DEFINITION); // Existing columns are the same, except they also have column IDs. MOCK_EXISTING_COLUMN_LIST = new ArrayList<>(); for (ColumnModel oneColumn : MOCK_COLUMN_LIST) { // Copy the columns, so we don't change the columns in MOCK_COLUMN_LIST. The only attributes // MOCK_COLUMN_LIST uses are name, type, and max size. ColumnModel copy = new ColumnModel(); copy.setName(oneColumn.getName()); copy.setColumnType(oneColumn.getColumnType()); copy.setMaximumSize(oneColumn.getMaximumSize()); // ID is [name]-id. copy.setId(oneColumn.getName() + "-id"); // Add to list. MOCK_EXISTING_COLUMN_LIST.add(copy); } } private List<ColumnModel> expectedColDefList; private List<String> expectedColIdList; private SynapseHelper mockSynapseHelper; private ExportTask task; private byte[] tsvBytes; @BeforeMethod public void before() { // clear vars, because TestNG doesn't always do that expectedColIdList = null; tsvBytes = null; } private SynapseExportHandler setup(List<ColumnModel> existingColumnList) throws Exception { // This needs to be done first, because lots of stuff reference this, even while we're setting up mocks. SynapseExportHandler handler = new UpdateTestSynapseHandler(); handler.setStudyId(SynapseExportHandlerTest.TEST_STUDY_ID); // mock config Config mockConfig = mock(Config.class); when(mockConfig.get(ExportWorkerManager.CONFIG_KEY_EXPORTER_DDB_PREFIX)).thenReturn( SynapseExportHandlerTest.DUMMY_DDB_PREFIX); when(mockConfig.getInt(ExportWorkerManager.CONFIG_KEY_SYNAPSE_PRINCIPAL_ID)) .thenReturn(SynapseExportHandlerTest.TEST_SYNAPSE_PRINCIPAL_ID); when(mockConfig.getInt(ExportWorkerManager.CONFIG_KEY_WORKER_MANAGER_PROGRESS_REPORT_PERIOD)).thenReturn(250); // mock file helper InMemoryFileHelper mockFileHelper = new InMemoryFileHelper(); File tmpDir = mockFileHelper.createTempDir(); // set up task task = new ExportTask.Builder().withExporterDate(SynapseExportHandlerTest.DUMMY_REQUEST_DATE) .withMetrics(new Metrics()).withRequest(SynapseExportHandlerTest.DUMMY_REQUEST).withTmpDir(tmpDir) .build(); // mock Synapse helper mockSynapseHelper = mock(SynapseHelper.class); // mock get column model list when(mockSynapseHelper.getColumnModelsForTableWithRetry(SynapseExportHandlerTest.TEST_SYNAPSE_TABLE_ID)) .thenReturn(existingColumnList); // mock create column model list - We only care about the names and IDs for the created columns. expectedColDefList = new ArrayList<>(); expectedColDefList.addAll(MOCK_COLUMN_LIST); expectedColDefList.addAll(handler.getSynapseTableColumnList(task)); List<ColumnModel> createdColumnList = new ArrayList<>(); expectedColIdList = new ArrayList<>(); for (ColumnModel oneColumnDef : expectedColDefList) { String colName = oneColumnDef.getName(); String colId = colName + "-id"; expectedColIdList.add(colId); ColumnModel createdColumn = new ColumnModel(); createdColumn.setName(colName); createdColumn.setId(colId); createdColumnList.add(createdColumn); } when(mockSynapseHelper.createColumnModelsWithRetry(anyListOf(ColumnModel.class))).thenReturn( createdColumnList); // mock upload the TSV and capture the upload when(mockSynapseHelper.uploadTsvFileToTable(eq(SynapseExportHandlerTest.TEST_SYNAPSE_PROJECT_ID), eq(SynapseExportHandlerTest.TEST_SYNAPSE_TABLE_ID), notNull(File.class))).thenAnswer(invocation -> { // on cleanup, the file is destroyed, so we need to intercept that file now File tsvFile = invocation.getArgumentAt(2, File.class); tsvBytes = mockFileHelper.getBytes(tsvFile); // we processed 1 rows return 1; }); // setup manager - This is mostly used to get helper objects. ExportWorkerManager manager = spy(new ExportWorkerManager()); manager.setConfig(mockConfig); manager.setFileHelper(mockFileHelper); manager.setSynapseHelper(mockSynapseHelper); manager.setSynapseColumnDefinitions(MOCK_COLUMN_DEFINITION); handler.setManager(manager); // spy getSynapseProjectId and getDataAccessTeam // These calls through to a bunch of stuff (which we test in ExportWorkerManagerTest), so to simplify our test, // we just use a spy here. doReturn(SynapseExportHandlerTest.TEST_SYNAPSE_PROJECT_ID).when(manager).getSynapseProjectIdForStudyAndTask( eq(SynapseExportHandlerTest.TEST_STUDY_ID), same(task)); doReturn(SynapseExportHandlerTest.TEST_SYNAPSE_DATA_ACCESS_TEAM_ID).when(manager).getDataAccessTeamIdForStudy( SynapseExportHandlerTest.TEST_STUDY_ID); // Similarly, spy get/setSynapseTableIdFromDDB. doReturn(SynapseExportHandlerTest.TEST_SYNAPSE_TABLE_ID).when(manager).getSynapseTableIdFromDdb(task, handler.getDdbTableName(), handler.getDdbTableKeyName(), handler.getDdbTableKeyValue()); return handler; } // Subclass TestSynapseHandler and add a few more fields. private static class UpdateTestSynapseHandler extends TestSynapseHandler { @Override protected List<ColumnModel> getSynapseTableColumnList(ExportTask task) { // Columns generated on the fly don't have column IDs yet, because they haven't been created yet. return ImmutableList.of(makeColumn("modify-this", null), makeColumn("add-this", null), makeColumn("swap-this-A", null), makeColumn("swap-this-B", null)); } // For test purposes, this will always match the schema returned by getSynapseTableColumnList. The tests will // validate how this interacts with the "existing" table and updates (or lack thereof). @Override protected Map<String, String> getTsvRowValueMap(ExportSubtask subtask) throws IOException { return new ImmutableMap.Builder<String, String>().put("modify-this", "modify-this value") .put("add-this", "add-this value") .put("swap-this-A", "swap-this-A value") .put("swap-this-B", "swap-this-B value").build(); } } @Test public void rejectDelete() throws Exception { // Existing columns has "delete-this" (rejected). List<ColumnModel> existingColumnList = new ArrayList<>(); existingColumnList.addAll(MOCK_EXISTING_COLUMN_LIST); existingColumnList.add(makeColumn("delete-this", "delete-this-id")); existingColumnList.add(makeColumn("modify-this", "modify-this-id")); testInitError(existingColumnList); } @Test public void incompatibleTypeChange() throws Exception { // Modify column type. List<ColumnModel> existingColumnList = new ArrayList<>(); existingColumnList.addAll(MOCK_EXISTING_COLUMN_LIST); ColumnModel oldModifiedColumn = new ColumnModel(); oldModifiedColumn.setName("modify-this"); oldModifiedColumn.setId("modify-this-old"); oldModifiedColumn.setColumnType(ColumnType.FILEHANDLEID); existingColumnList.add(oldModifiedColumn); testInitError(existingColumnList); } @Test public void incompatibleLengthChange() throws Exception { // Modify column type. List<ColumnModel> existingColumnList = new ArrayList<>(); existingColumnList.addAll(MOCK_EXISTING_COLUMN_LIST); ColumnModel oldModifiedColumn = new ColumnModel(); oldModifiedColumn.setName("modify-this"); oldModifiedColumn.setId("modify-this-old"); oldModifiedColumn.setColumnType(ColumnType.STRING); oldModifiedColumn.setMaximumSize(1000L); existingColumnList.add(oldModifiedColumn); testInitError(existingColumnList); } private void testInitError(List<ColumnModel> existingColumnList) throws Exception { existingColumnList.add(makeColumn("add-this", "add-this-id")); existingColumnList.add(makeColumn("swap-this-A", "swap-this-A-id")); existingColumnList.add(makeColumn("swap-this-B", "swap-this-B-id")); // setup SynapseExportHandler handler = setup(existingColumnList); // execute - First row triggers the error initializing TSV. Second row short-circuit fails. ExportSubtask subtask = SynapseExportHandlerTest.makeSubtask(task); handleSubtaskWithInitError(handler, subtask); handleSubtaskWithInitError(handler, subtask); // upload to Synapse should fail try { handler.uploadToSynapseForTask(task); fail("expected exception"); } catch (BridgeExporterException ex) { assertTrue(ex instanceof BridgeExporterTsvException); assertTrue(ex.getMessage().startsWith("TSV was not successfully initialized: ")); assertTrue(ex.getCause() instanceof BridgeExporterNonRetryableException); assertEquals(ex.getCause().getMessage(), "Table has deleted and/or modified columns"); } // verify we did not update the table verify(mockSynapseHelper, never()).updateTableColumns(any(), any()); // verify we don't upload the TSV to Synapse verify(mockSynapseHelper, never()).uploadTsvFileToTable(any(), any(), any()); // validate metrics Multiset<String> counterMap = task.getMetrics().getCounterMap(); assertEquals(counterMap.count(handler.getDdbTableKeyValue() + ".lineCount"), 0); assertEquals(counterMap.count(handler.getDdbTableKeyValue() + ".errorCount"), 2); // validate tsvInfo TsvInfo tsvInfo = handler.getTsvInfoForTask(task); assertEquals(tsvInfo.getLineCount(), 0); } private static void handleSubtaskWithInitError(SynapseExportHandler handler, ExportSubtask subtask) throws Exception { try { handler.handle(subtask); fail("expected exception"); } catch (BridgeExporterException ex) { assertTrue(ex instanceof BridgeExporterTsvException); assertTrue(ex.getMessage().startsWith("TSV was not successfully initialized: ")); assertTrue(ex.getCause() instanceof BridgeExporterNonRetryableException); assertEquals(ex.getCause().getMessage(), "Table has deleted and/or modified columns"); } } @Test public void dontUpdateIfNoAddedColumns() throws Exception { // Swap the columns. "Add this" has already been added. List<ColumnModel> existingColumnList = new ArrayList<>(); existingColumnList.addAll(MOCK_EXISTING_COLUMN_LIST); existingColumnList.add(makeColumn("modify-this", "modify-this-id")); existingColumnList.add(makeColumn("add-this", "add-this-id")); existingColumnList.add(makeColumn("swap-this-B", "swap-this-B-id")); existingColumnList.add(makeColumn("swap-this-A", "swap-this-A-id")); // setup and execute - The columns will be in the order specified by the column defs, not in the order // specified in Synapse. This is fine. As long as the headers are properly labeled, Synapse can handle this. setupAndExecuteSuccessCase(existingColumnList); // verify we did not update the table verify(mockSynapseHelper, never()).updateTableColumns(any(), any()); } @Test public void addAndSwapColumns() throws Exception { // Existing columns does not have "add-this" and has swapped columns. List<ColumnModel> existingColumnList = new ArrayList<>(); existingColumnList.addAll(MOCK_EXISTING_COLUMN_LIST); existingColumnList.add(makeColumn("modify-this", "modify-this-id")); existingColumnList.add(makeColumn("swap-this-B", "swap-this-B-id")); existingColumnList.add(makeColumn("swap-this-A", "swap-this-A-id")); // setup and execute setupAndExecuteSuccessCase(existingColumnList); // verify create columns call verify(mockSynapseHelper).createColumnModelsWithRetry(expectedColDefList); // verify table update ArgumentCaptor<TableSchemaChangeRequest> requestCaptor = ArgumentCaptor.forClass( TableSchemaChangeRequest.class); verify(mockSynapseHelper).updateTableColumns(requestCaptor.capture(), eq(SynapseExportHandlerTest.TEST_SYNAPSE_TABLE_ID)); TableSchemaChangeRequest request = requestCaptor.getValue(); assertEquals(request.getEntityId(), SynapseExportHandlerTest.TEST_SYNAPSE_TABLE_ID); assertEquals(request.getOrderedColumnIds(), expectedColIdList); List<ColumnChange> changeList = request.getChanges(); assertEquals(changeList.size(), 1); assertNull(changeList.get(0).getOldColumnId()); assertEquals(changeList.get(0).getNewColumnId(), "add-this-id"); } @Test public void willAddCommonColumnList() throws Exception { // provide an empty existing list and verify if handler will add common column list into it List<ColumnModel> existingColumnList = new ArrayList<>(); setupAndExecuteSuccessCase(existingColumnList); // verify create columns call verify(mockSynapseHelper).createColumnModelsWithRetry(expectedColDefList); // verify table update ArgumentCaptor<TableSchemaChangeRequest> requestCaptor = ArgumentCaptor.forClass( TableSchemaChangeRequest.class); verify(mockSynapseHelper).updateTableColumns(requestCaptor.capture(), eq(SynapseExportHandlerTest.TEST_SYNAPSE_TABLE_ID)); TableSchemaChangeRequest request = requestCaptor.getValue(); assertEquals(request.getEntityId(), SynapseExportHandlerTest.TEST_SYNAPSE_TABLE_ID); assertEquals(request.getOrderedColumnIds(), expectedColIdList); int numExpectedColumns = expectedColIdList.size(); List<ColumnChange> changeList = request.getChanges(); assertEquals(changeList.size(), numExpectedColumns); for (int i = 0; i < numExpectedColumns; i++) { assertNull(changeList.get(i).getOldColumnId()); assertEquals(changeList.get(i).getNewColumnId(), expectedColIdList.get(i)); } } @Test public void compatibleTypeChange() throws Exception { // Swap the columns. "Add this" has already been added. List<ColumnModel> existingColumnList = new ArrayList<>(); existingColumnList.addAll(MOCK_EXISTING_COLUMN_LIST); existingColumnList.add(makeColumn("add-this", "add-this-id")); existingColumnList.add(makeColumn("swap-this-B", "swap-this-B-id")); existingColumnList.add(makeColumn("swap-this-A", "swap-this-A-id")); // Old modified is an Int, which can be converted to String just fine. ColumnModel oldModifiedColumn = new ColumnModel(); oldModifiedColumn.setName("modify-this"); oldModifiedColumn.setId("modify-this-old"); oldModifiedColumn.setColumnType(ColumnType.INTEGER); existingColumnList.add(oldModifiedColumn); // setup and execute - The columns will be in the order specified by the column defs, not in the order // specified in Synapse. This is fine. As long as the headers are properly labeled, Synapse can handle this. setupAndExecuteSuccessCase(existingColumnList); // verify table update ArgumentCaptor<TableSchemaChangeRequest> requestCaptor = ArgumentCaptor.forClass( TableSchemaChangeRequest.class); verify(mockSynapseHelper).updateTableColumns(requestCaptor.capture(), eq(SynapseExportHandlerTest.TEST_SYNAPSE_TABLE_ID)); TableSchemaChangeRequest request = requestCaptor.getValue(); assertEquals(request.getEntityId(), SynapseExportHandlerTest.TEST_SYNAPSE_TABLE_ID); assertEquals(request.getOrderedColumnIds(), expectedColIdList); List<ColumnChange> changeList = request.getChanges(); assertEquals(changeList.size(), 1); assertEquals(changeList.get(0).getOldColumnId(), "modify-this-old"); assertEquals(changeList.get(0).getNewColumnId(), "modify-this-id"); } @Test public void compatibleLengthChange() throws Exception { // Swap the columns. "Add this" has already been added. List<ColumnModel> existingColumnList = new ArrayList<>(); existingColumnList.addAll(MOCK_EXISTING_COLUMN_LIST); existingColumnList.add(makeColumn("add-this", "add-this-id")); existingColumnList.add(makeColumn("swap-this-B", "swap-this-B-id")); existingColumnList.add(makeColumn("swap-this-A", "swap-this-A-id")); // Old modified is a smaller string (24 chars), which can be converted to a larger string just fine. ColumnModel oldModifiedColumn = new ColumnModel(); oldModifiedColumn.setName("modify-this"); oldModifiedColumn.setId("modify-this-old"); oldModifiedColumn.setColumnType(ColumnType.STRING); oldModifiedColumn.setMaximumSize(24L); existingColumnList.add(oldModifiedColumn); // setup and execute - The columns will be in the order specified by the column defs, not in the order // specified in Synapse. This is fine. As long as the headers are properly labeled, Synapse can handle this. setupAndExecuteSuccessCase(existingColumnList); // verify table update ArgumentCaptor<TableSchemaChangeRequest> requestCaptor = ArgumentCaptor.forClass( TableSchemaChangeRequest.class); verify(mockSynapseHelper).updateTableColumns(requestCaptor.capture(), eq(SynapseExportHandlerTest.TEST_SYNAPSE_TABLE_ID)); TableSchemaChangeRequest request = requestCaptor.getValue(); assertEquals(request.getEntityId(), SynapseExportHandlerTest.TEST_SYNAPSE_TABLE_ID); assertEquals(request.getOrderedColumnIds(), expectedColIdList); List<ColumnChange> changeList = request.getChanges(); assertEquals(changeList.size(), 1); assertEquals(changeList.get(0).getOldColumnId(), "modify-this-old"); assertEquals(changeList.get(0).getNewColumnId(), "modify-this-id"); } private void setupAndExecuteSuccessCase(List<ColumnModel> existingColumnList) throws Exception { // setup and execute SynapseExportHandler handler = setup(existingColumnList); handler.handle(SynapseExportHandlerTest.makeSubtask(task)); handler.uploadToSynapseForTask(task); // validate tsv file List<String> tsvLineList = TestUtil.bytesToLines(tsvBytes); assertEquals(tsvLineList.size(), 2); SynapseExportHandlerTest.validateTsvHeaders(tsvLineList.get(0), "modify-this", "add-this", "swap-this-A", "swap-this-B"); SynapseExportHandlerTest.validateTsvRow(tsvLineList.get(1), "modify-this value", "add-this value", "swap-this-A value", "swap-this-B value"); } private static ColumnModel makeColumn(String name, String id) { ColumnModel col = new ColumnModel(); col.setName(name); col.setId(id); col.setColumnType(ColumnType.STRING); col.setMaximumSize(100L); return col; } }
// ============================================================================ // Copyright (C) 2006-2018 Talend Inc. - www.talend.com // // This source code is available under agreement available at // https://github.com/Talend/data-prep/blob/master/LICENSE // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.dataprep.preparation.service; import static com.jayway.restassured.RestAssured.given; import static java.util.stream.Collectors.toList; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import java.io.IOException; import java.util.List; import java.util.stream.StreamSupport; import org.junit.Test; import org.talend.dataprep.api.dataset.RowMetadata; import org.talend.dataprep.api.folder.Folder; import org.talend.dataprep.api.folder.FolderInfo; import org.talend.dataprep.api.folder.FolderTreeNode; import org.talend.dataprep.api.preparation.Preparation; import org.talend.dataprep.preparation.BasePreparationTest; import com.fasterxml.jackson.core.type.TypeReference; import com.jayway.restassured.response.Response; /** * Unit/integration tests for the FolderService */ public class FolderServiceTest extends BasePreparationTest { @Test public void shouldListChildren() throws Exception { // given createFolder(home.getId(), "/bar"); createFolder(home.getId(), "/toto"); // when final List<Folder> folders = getFolderChildren(home.getId()); // then final List<String> foldersNames = folders.stream().map(Folder::getName).collect(toList()); assertThat(foldersNames.size(), is(2)); assertThat(foldersNames, containsInAnyOrder("bar", "toto")); } @Test public void childrenShouldContainsPreparationsCount() throws Exception { // given createFolder(home.getId(), "foo"); final Folder fooFolder = getFolder(home.getId(), "foo"); long expectedNbPreparations = 12; for (int i = 0; i < expectedNbPreparations; i++) { Preparation preparation = new Preparation(); preparation.setName("prep_" + i); preparation.setDataSetId("1234"); preparation.setRowMetadata(new RowMetadata()); clientTest.createPreparation(preparation, fooFolder.getId()); } // when final List<Folder> folders = getFolderChildren(home.getId()); // then assertThat(folders.size(), is(1)); assertThat(folders.get(0).getNbPreparations(), is(expectedNbPreparations)); } @Test public void shouldNotFindFolder() throws Exception { // when final Response response = given() // .expect() .statusCode(404) .log() .ifError()// .when() // .get("/folders?parentId={parentId}", "unknownId"); // then assertThat(response.getStatusCode(), is(404)); } @Test public void shouldSearchFolderByName() throws Exception { // given createFolder(home.getId(), "foo"); createFolder(home.getId(), "bar"); // when final Response response = given() // .queryParam("name", "foo") // .expect() .statusCode(200) .log() .ifError()// .when() // .get("/folders/search"); // then final List<Folder> folders = mapper.readValue(response.asString(), new TypeReference<List<Folder>>() { }); assertThat(folders, hasSize(1)); assertThat(folders.get(0).getName(), is("foo")); } @Test public void searchFolderShouldUpdateNbPreparationsFound() throws Exception { // given createFolder(home.getId(), "foo"); final Folder foo = getFolder(home.getId(), "foo"); Preparation preparation = new Preparation(); preparation.setName("test_name"); preparation.setDataSetId("1234"); preparation.setRowMetadata(new RowMetadata()); clientTest.createPreparation(preparation, foo.getId()); // when final Response response = given() // .queryParam("name", "foo") // .expect() .statusCode(200) .log() .ifError()// .when() // .get("/folders/search"); // then final List<Folder> folders = mapper.readValue(response.asString(), new TypeReference<List<Folder>>() { }); assertThat(folders, hasSize(1)); final Folder folder = folders.get(0); assertThat(folder.getName(), is("foo")); assertEquals(1, folder.getNbPreparations()); } @Test public void shouldRemoveFolder() throws Exception { // given createFolder(home.getId(), "foo"); createFolder(home.getId(), "bar"); final Folder fooFolder = getFolder(home.getId(), "foo"); // when given() // .expect() .statusCode(200) .log() .ifError()// .when() // .delete("/folders/" + fooFolder.getId()); // then final List<Folder> folders = getFolderChildren(home.getId()); assertThat(folders, hasSize(1)); assertThat(folders.get(0).getName(), is("bar")); } @Test public void shouldRemoveMissingFolder() throws Exception { // then given() // .expect() .statusCode(404) .log() .ifError()// .when() // .delete("/folders/folder1234"); } @Test public void folderNotFoundShouldThrow404() { // when given() // .expect() .statusCode(404) .log() .ifError()// .when() // .get("/folders/mlkjmlkjmlkj"); } @Test public void shouldRenameFolderAndItsChildren() throws Exception { // given createFolder(home.getId(), "foo"); final Folder fooFolder = getFolder(home.getId(), "foo"); createFolder(fooFolder.getId(), "fooChildOne"); createFolder(fooFolder.getId(), "fooChildTwo"); // when given() // .body("faa") .expect() .statusCode(200) .log() .ifError()// .when() // .put("/folders/" + fooFolder.getId() + "/name"); // then final List<Folder> folders = getFolderChildren(home.getId()); assertThat(folders, hasSize(1)); assertThat(folders.get(0).getName(), is("faa")); final List<Folder> children = getFolderChildren(folders.get(0).getId()); assertThat(children, hasSize(2)); final List<String> childrenPath = children.stream().map(Folder::getPath).collect(toList()); assertThat(childrenPath, containsInAnyOrder("/faa/fooChildOne", "/faa/fooChildTwo")); } @Test public void shouldReturnEntireFolderTree() throws Exception { // @formatter:off // given // HOME // ___________|____________ // | | // first second // ____|____ | // | | | //first child 1 first child 2 second child // | // | // second child child // @formatter:on createFolder(home.getId(), "first"); createFolder(home.getId(), "second"); final Folder firstFolder = getFolder(home.getId(), "first"); final Folder secondFolder = getFolder(home.getId(), "second"); createFolder(firstFolder.getId(), "first child one"); createFolder(firstFolder.getId(), "first child two"); createFolder(secondFolder.getId(), "second child"); final Folder secondChildFolder = getFolder(secondFolder.getId(), "second child"); createFolder(secondChildFolder.getId(), "second child child"); // when final Response response = given() // .expect() .statusCode(200) .log() .ifError()// .when() // .get("/folders/tree"); // then final FolderTreeNode tree = mapper.readValue(response.asString(), new TypeReference<FolderTreeNode>() { }); assertTree(tree, "/", new String[] { "/first", "/second" }); final FolderTreeNode firstFolderNode = getChild(tree, "first"); final FolderTreeNode secondFolderNode = getChild(tree, "second"); assertTree(firstFolderNode, "/first", new String[] { "/first/first child one", "/first/first child two" }); assertTree(secondFolderNode, "/second", new String[] { "/second/second child" }); final FolderTreeNode secondChildFolderNode = getChild(secondFolderNode, "second child"); assertTree(secondChildFolderNode, "/second/second child", new String[] { "/second/second child/second child child" }); } @Test public void shouldFolderMetadataWithHierarchy() throws Exception { // @formatter:off // given // HOME // ___________|____________ // | | // first second // ____|____ | // | | | //first child 1 first child 2 second child // | // | // second child child // @formatter:on createFolder(home.getId(), "first"); createFolder(home.getId(), "second"); final Folder firstFolder = getFolder(home.getId(), "first"); final Folder secondFolder = getFolder(home.getId(), "second"); createFolder(firstFolder.getId(), "first child one"); createFolder(firstFolder.getId(), "first child two"); createFolder(secondFolder.getId(), "second child"); final Folder secondChildFolder = getFolder(secondFolder.getId(), "second child"); createFolder(secondChildFolder.getId(), "second child child"); final Folder firstChildTwo = getFolder(firstFolder.getId(), "first child two"); // when final Response response = given() // .expect() .statusCode(200) .log() .ifError()// .when() // .get("/folders/{id}", firstChildTwo.getId()); // then final FolderInfo infos = mapper.readValue(response.asString(), new TypeReference<FolderInfo>() { }); final List<Folder> hierarchy = StreamSupport.stream(infos.getHierarchy().spliterator(), false).collect(toList()); assertThat(infos.getFolder(), equalTo(firstChildTwo)); assertThat(hierarchy, hasSize(2)); assertThat(hierarchy.get(0).getId(), equalTo(home.getId())); assertThat(hierarchy.get(1).getId(), equalTo(firstFolder.getId())); } @Test public void shouldSearchFolders() throws Exception { // given final boolean strict = true; final boolean nonStrict = false; createFolder(home.getId(), "foo"); createFolder(home.getId(), "foo/bar"); createFolder(home.getId(), "foo/toto"); createFolder(home.getId(), "foo/bar/tototo"); // when / then assertSearch("toto", strict, new String[] { "/foo/toto" }); assertSearch("tot", nonStrict, new String[] { "/foo/toto", "/foo/bar/tototo" }); } private void assertSearch(final String name, final boolean strict, final String[] expectedResultPaths) throws IOException { final Response response = given() // .queryParam("name", name) // .queryParam("strict", strict) // .expect() .statusCode(200) .log() .ifError()// .when() // .get("/folders/search"); // then assertThat(response.getStatusCode(), is(200)); final List<Folder> folders = mapper.readValue(response.asString(), new TypeReference<List<Folder>>() { }); final List<String> foldersNames = folders.stream().map(Folder::getPath).collect(toList()); assertThat(foldersNames.size(), is(expectedResultPaths.length)); assertThat(foldersNames, containsInAnyOrder(expectedResultPaths)); } private void assertTree(final FolderTreeNode node, final String nodePath, final String[] expectedChildrenPaths) { assertThat(node.getFolder().getPath(), is(nodePath)); assertThat(node.getChildren(), hasSize(expectedChildrenPaths.length)); final List<String> actualChildrenPaths = node .getChildren() .stream() .map((folderTreeNode -> folderTreeNode.getFolder().getPath())) .collect(toList()); assertThat(actualChildrenPaths, containsInAnyOrder(expectedChildrenPaths)); } private FolderTreeNode getChild(final FolderTreeNode tree, final String childName) { return tree .getChildren() .stream() .filter((child) -> child.getFolder().getName().equals(childName)) .findFirst() .orElse(null); } }
/* * Copyright (C) 2015 SoftIndex LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.datakernel.codegen; import org.objectweb.asm.Type; import org.objectweb.asm.commons.GeneratorAdapter; import org.objectweb.asm.commons.Method; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.IntStream; import java.util.stream.Stream; import static io.datakernel.codegen.Utils.*; import static io.datakernel.common.Preconditions.checkArgument; import static java.lang.String.format; import static java.lang.reflect.Modifier.isStatic; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toSet; import static org.objectweb.asm.Type.*; /** * Contains information about a dynamic class */ public final class Context { private final DefiningClassLoader classLoader; private final GeneratorAdapter g; private final Type selfType; private final Class<?> superclass; private final List<Class<?>> interfaces; private final Map<String, Class<?>> fields; private final Map<Method, Expression> methods; private final Map<Method, Expression> staticMethods; private final Method method; private final Map<String, Object> staticConstants; public Context(DefiningClassLoader classLoader, GeneratorAdapter g, Type selfType, Class<?> superclass, List<Class<?>> interfaces, Map<String, Class<?>> fields, Map<Method, Expression> methods, Map<Method, Expression> staticMethods, Method method, Map<String, Object> staticConstants) { this.classLoader = classLoader; this.g = g; this.selfType = selfType; this.superclass = superclass; this.interfaces = interfaces; this.fields = fields; this.methods = methods; this.staticMethods = staticMethods; this.method = method; this.staticConstants = staticConstants; } public DefiningClassLoader getClassLoader() { return classLoader; } public GeneratorAdapter getGeneratorAdapter() { return g; } public Type getSelfType() { return selfType; } public Class<?> getSuperclass() { return superclass; } public List<Class<?>> getInterfaces() { return interfaces; } public Map<String, Class<?>> getFields() { return fields; } public Map<Method, Expression> getMethods() { return methods; } public Map<Method, Expression> getStaticMethods() { return staticMethods; } public Method getMethod() { return method; } public Map<String, Object> getStaticConstants() { return staticConstants; } public void addStaticConstant(String field, Object value) { staticConstants.put(field, value); } public VarLocal newLocal(Type type) { int local = getGeneratorAdapter().newLocal(type); return new VarLocal(local); } public Class<?> toJavaType(Type type) { if (type.equals(getSelfType())) throw new IllegalArgumentException(); int sort = type.getSort(); if (sort == BOOLEAN) return boolean.class; if (sort == CHAR) return char.class; if (sort == BYTE) return byte.class; if (sort == SHORT) return short.class; if (sort == INT) return int.class; if (sort == FLOAT) return float.class; if (sort == LONG) return long.class; if (sort == DOUBLE) return double.class; if (sort == VOID) return void.class; if (sort == OBJECT) { try { return classLoader.loadClass(type.getClassName()); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(format("No class %s in class loader", type.getClassName()), e); } } if (sort == ARRAY) { Class<?> result; if (type.equals(getType(Object[].class))) { result = Object[].class; } else { String className = type.getDescriptor().replace('/', '.'); try { result = Class.forName(className); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(format("No class %s in Class.forName", className), e); } } return result; } throw new IllegalArgumentException(format("No Java type for %s", type.getClassName())); } public void cast(Type typeFrom, Type typeTo) { GeneratorAdapter g = getGeneratorAdapter(); if (typeFrom.equals(typeTo)) { return; } if (typeTo == VOID_TYPE) { if (typeFrom.getSize() == 1) g.pop(); if (typeFrom.getSize() == 2) g.pop2(); return; } if (typeFrom == VOID_TYPE) { throw new RuntimeException(format("Can't cast VOID_TYPE typeTo %s. %s", typeTo.getClassName(), exceptionInGeneratedClass(this))); } if (typeFrom.equals(getSelfType())) { Class<?> javaType = toJavaType(typeTo); if (javaType.isAssignableFrom(getSuperclass())) { return; } for (Class<?> type : getInterfaces()) { if (javaType.isAssignableFrom(type)) { return; } } throw new RuntimeException(format("Can't cast self %s typeTo %s, %s", typeFrom.getClassName(), typeTo.getClassName(), exceptionInGeneratedClass(this))); } if (!typeFrom.equals(getSelfType()) && !typeTo.equals(getSelfType()) && toJavaType(typeTo).isAssignableFrom(toJavaType(typeFrom))) { return; } if (typeTo.equals(getType(Object.class)) && isPrimitiveType(typeFrom)) { g.box(typeFrom); // g.cast(wrap(typeFrom), getType(Object.class)); return; } if ((isPrimitiveType(typeFrom) || isWrapperType(typeFrom)) && (isPrimitiveType(typeTo) || isWrapperType(typeTo))) { Type targetTypePrimitive = isPrimitiveType(typeTo) ? typeTo : unwrap(typeTo); if (isWrapperType(typeFrom)) { g.invokeVirtual(typeFrom, toPrimitive(typeTo)); return; } assert isPrimitiveType(typeFrom); if (isValidCast(typeFrom, targetTypePrimitive)) { g.cast(typeFrom, targetTypePrimitive); } if (isWrapperType(typeTo)) { g.valueOf(targetTypePrimitive); } return; } g.checkCast(typeTo); } public Type invoke(Expression owner, String methodName, Expression... arguments) { return invoke(owner, methodName, asList(arguments)); } public Type invoke(Expression owner, String methodName, List<Expression> arguments) { Type ownerType = owner.load(this); Type[] argumentTypes = new Type[arguments.size()]; for (int i = 0; i < arguments.size(); i++) { Expression argument = arguments.get(i); argumentTypes[i] = argument.load(this); } return invoke(ownerType, methodName, argumentTypes); } public Type invoke(Type ownerType, String methodName, Type... argumentTypes) { Class<?>[] arguments = Stream.of(argumentTypes).map(this::toJavaType).toArray(Class[]::new); Method foundMethod; if (ownerType.equals(getSelfType())) { foundMethod = findMethod( getMethods().keySet().stream(), methodName, arguments); g.invokeVirtual(ownerType, foundMethod); } else { Class<?> javaOwnerType = toJavaType(ownerType); foundMethod = findMethod( Arrays.stream(javaOwnerType.getMethods()) .filter(m -> !isStatic(m.getModifiers())) .map(Method::getMethod), methodName, arguments); if (javaOwnerType.isInterface()) { g.invokeInterface(ownerType, foundMethod); } else { g.invokeVirtual(ownerType, foundMethod); } } return foundMethod.getReturnType(); } public Type invokeStatic(Type ownerType, String methodName, Expression... arguments) { return invokeStatic(ownerType, methodName, asList(arguments)); } public Type invokeStatic(Type ownerType, String methodName, List<Expression> arguments) { Type[] argumentTypes = new Type[arguments.size()]; for (int i = 0; i < arguments.size(); i++) { Expression argument = arguments.get(i); argumentTypes[i] = argument.load(this); } return invokeStatic(ownerType, methodName, argumentTypes); } public Type invokeStatic(Type ownerType, String methodName, Type... argumentTypes) { Class<?>[] arguments = Stream.of(argumentTypes).map(this::toJavaType).toArray(Class[]::new); Method foundMethod; if (ownerType.equals(getSelfType())) { foundMethod = findMethod( getStaticMethods().keySet().stream(), methodName, arguments); } else { foundMethod = findMethod( Arrays.stream(toJavaType(ownerType).getMethods()) .filter(m -> isStatic(m.getModifiers())) .map(Method::getMethod), methodName, arguments); } g.invokeStatic(ownerType, foundMethod); return foundMethod.getReturnType(); } public Type invokeConstructor(Type ownerType, Expression... arguments) { return invokeConstructor(ownerType, asList(arguments)); } public Type invokeConstructor(Type ownerType, List<Expression> arguments) { g.newInstance(ownerType); g.dup(); Type[] argumentTypes = new Type[arguments.size()]; for (int i = 0; i < arguments.size(); i++) { argumentTypes[i] = arguments.get(i).load(this); } return invokeConstructor(ownerType, argumentTypes); } public Type invokeConstructor(Type ownerType, Type... argumentTypes) { Class<?>[] arguments = Stream.of(argumentTypes).map(this::toJavaType).toArray(Class[]::new); checkArgument(!ownerType.equals(getSelfType())); Method foundMethod = findMethod( Arrays.stream(toJavaType(ownerType).getConstructors()) .map(Method::getMethod), "<init>", arguments); g.invokeConstructor(ownerType, foundMethod); return ownerType; } private Method findMethod(Stream<Method> methods, String name, Class<?>[] arguments) { Set<Method> methodSet = methods.collect(toSet()); methodSet.addAll(Arrays.stream(Object.class.getMethods()) .filter(m -> !isStatic(m.getModifiers())) .map(Method::getMethod) .collect(toSet())); Method foundMethod = null; Class<?>[] foundMethodArguments = null; for (Method method : methodSet) { if (!name.equals(method.getName())) continue; Class[] methodArguments = Stream.of(method.getArgumentTypes()).map(this::toJavaType).toArray(Class[]::new); if (!isAssignable(methodArguments, arguments)) { continue; } if (foundMethod == null) { foundMethod = method; foundMethodArguments = methodArguments; } else { if (isAssignable(foundMethodArguments, methodArguments)) { foundMethod = method; foundMethodArguments = methodArguments; } else if (isAssignable(methodArguments, foundMethodArguments)) { // do nothing } else { throw new IllegalArgumentException("Ambiguous method: " + method + " " + Arrays.toString(arguments)); } } } if (foundMethod == null) { throw new IllegalArgumentException("Method not found: " + name + " " + Arrays.toString(arguments)); } return foundMethod; } private static boolean isAssignable(Class<?>[] to, Class<?>[] from) { if (to.length != from.length) return false; return IntStream.range(0, from.length) .allMatch(i -> to[i].isAssignableFrom(from[i])); } }
/* * Copyright (c) 2013, jEVETools * 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 author nor the names of the 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 com.jevetools.data.model.api.inventory.impl.tests; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; import org.junit.Test; import com.jevetools.data.model.api.impl.internal.tests.AbstractTest; import com.jevetools.data.model.api.inventory.MetaGroup; import com.jevetools.data.model.api.inventory.impl.MetaGroupImpl; /** * Copyright (c) 2013, jEVETools. * * All rights reserved. * * @version 0.0.1 * @since 0.0.1 */ public final class MetaGroupImplTest extends AbstractTest { /** * Default values test. */ @Test public void testDefault() { final MetaGroupImpl.Builder builder = new MetaGroupImpl.Builder(); final MetaGroup testSubject = builder.build(); assertThat(testSubject.getMetaGroupID(), equalTo(0)); assertThat(testSubject.getMetaGroupName(), equalTo(EMPTY_STRING)); assertThat(testSubject.getDescription(), equalTo(EMPTY_STRING)); assertThat(testSubject.getIconID(), equalTo(0)); } /** * MetaGroupID test. */ @Test public void testMetaGroupID() { final MetaGroupImpl.Builder builder = new MetaGroupImpl.Builder(); final int expected = randomInteger(0, Integer.MAX_VALUE - 1); builder.metaGroupID(expected); final MetaGroup testSubject = builder.build(); assertThat(testSubject.getMetaGroupID(), equalTo(expected)); assertThat(testSubject.getMetaGroupName(), equalTo(EMPTY_STRING)); assertThat(testSubject.getDescription(), equalTo(EMPTY_STRING)); assertThat(testSubject.getIconID(), equalTo(0)); } /** * MetaGroupName test. */ @Test public void testMetaGroupName() { final MetaGroupImpl.Builder builder = new MetaGroupImpl.Builder(); builder.metaGroupName(TEST_STRING); final MetaGroup testSubject = builder.build(); assertThat(testSubject.getMetaGroupID(), equalTo(0)); assertThat(testSubject.getMetaGroupName(), equalTo(TEST_STRING)); assertThat(testSubject.getDescription(), equalTo(EMPTY_STRING)); assertThat(testSubject.getIconID(), equalTo(0)); } /** * Description test. */ @Test public void testDescription() { final MetaGroupImpl.Builder builder = new MetaGroupImpl.Builder(); builder.description(TEST_STRING); final MetaGroup testSubject = builder.build(); assertThat(testSubject.getMetaGroupID(), equalTo(0)); assertThat(testSubject.getMetaGroupName(), equalTo(EMPTY_STRING)); assertThat(testSubject.getDescription(), equalTo(TEST_STRING)); assertThat(testSubject.getIconID(), equalTo(0)); } /** * IconID test. */ @Test public void testIconNo() { final MetaGroupImpl.Builder builder = new MetaGroupImpl.Builder(); final int expected = randomInteger(0, Integer.MAX_VALUE - 1); builder.iconID(expected); final MetaGroup testSubject = builder.build(); assertThat(testSubject.getMetaGroupID(), equalTo(0)); assertThat(testSubject.getMetaGroupName(), equalTo(EMPTY_STRING)); assertThat(testSubject.getDescription(), equalTo(EMPTY_STRING)); assertThat(testSubject.getIconID(), equalTo(expected)); } /** * HashCode test. */ @Test public void testHashCode() { final MetaGroupImpl.Builder builder1 = new MetaGroupImpl.Builder(); final MetaGroupImpl.Builder builder2 = new MetaGroupImpl.Builder(); final MetaGroupImpl.Builder builder3 = new MetaGroupImpl.Builder(); builder1.metaGroupID(0); builder2.metaGroupID(0); builder3.metaGroupID(1); final MetaGroup testSubject1 = builder1.build(); final MetaGroup testSubject2 = builder2.build(); final MetaGroup testSubject3 = builder3.build(); assertThat(testSubject1.hashCode(), equalTo(testSubject1.hashCode())); assertThat(testSubject1.hashCode(), equalTo(testSubject2.hashCode())); assertThat(testSubject1.hashCode(), not(equalTo(testSubject3.hashCode()))); assertThat(testSubject2.hashCode(), equalTo(testSubject2.hashCode())); assertThat(testSubject2.hashCode(), equalTo(testSubject1.hashCode())); assertThat(testSubject2.hashCode(), not(equalTo(testSubject3.hashCode()))); assertThat(testSubject3.hashCode(), equalTo(testSubject3.hashCode())); assertThat(testSubject3.hashCode(), not(equalTo(testSubject1.hashCode()))); assertThat(testSubject3.hashCode(), not(equalTo(testSubject2.hashCode()))); } /** * Equals test. */ @Test public void testEquals() { final MetaGroupImpl.Builder builder1 = new MetaGroupImpl.Builder(); final MetaGroupImpl.Builder builder2 = new MetaGroupImpl.Builder(); final MetaGroupImpl.Builder builder3 = new MetaGroupImpl.Builder(); builder1.metaGroupID(0); builder2.metaGroupID(0); builder3.metaGroupID(1); final MetaGroup testSubject1 = builder1.build(); final MetaGroup testSubject2 = builder2.build(); final MetaGroup testSubject3 = builder3.build(); assertThat(testSubject1, equalTo(testSubject1)); assertThat(testSubject1, equalTo(testSubject2)); assertThat(testSubject1, not(equalTo(testSubject3))); assertThat(testSubject2, equalTo(testSubject2)); assertThat(testSubject2, equalTo(testSubject1)); assertThat(testSubject2, not(equalTo(testSubject3))); assertThat(testSubject3, equalTo(testSubject3)); assertThat(testSubject3, not(equalTo(testSubject1))); assertThat(testSubject3, not(equalTo(testSubject2))); assertThat(testSubject3, not(equalTo(null))); assertThat(testSubject3.equals(Boolean.TRUE), equalTo(false)); } }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.webapps; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.os.AsyncTask; import org.chromium.base.ThreadUtils; import org.chromium.base.VisibleForTesting; import org.chromium.chrome.browser.ShortcutHelper; import java.util.Map; /** * Stores data about an installed web app. Uses SharedPreferences to persist the data to disk. * Before this class is used, the web app must be registered in {@link WebappRegistry}. * * EXAMPLE USAGE: * * (1) UPDATING/RETRIEVING THE ICON (web app MUST have been registered in WebappRegistry) * WebappDataStorage storage = WebappDataStorage.open(context, id); * storage.updateSplashScreenImage(bitmap); * storage.getSplashScreenImage(callback); */ public class WebappDataStorage { static final String SHARED_PREFS_FILE_PREFIX = "webapp_"; static final String KEY_SPLASH_ICON = "splash_icon"; static final String KEY_LAST_USED = "last_used"; static final long INVALID_LAST_USED = -1; private static Factory sFactory = new Factory(); private final SharedPreferences mPreferences; /** * Opens an instance of WebappDataStorage for the web app specified. * @param context The context to open the SharedPreferences. * @param webappId The ID of the web app which is being opened. */ public static WebappDataStorage open(final Context context, final String webappId) { final WebappDataStorage storage = sFactory.create(context, webappId); new AsyncTask<Void, Void, Void>() { @Override protected final Void doInBackground(Void... nothing) { if (storage.getLastUsedTime() == INVALID_LAST_USED) { // If the last used time is invalid then assert that there is no data // in the WebappDataStorage which needs to be cleaned up. assert storage.getAllData().isEmpty(); } else { storage.updateLastUsedTime(); } return null; } }.execute(); return storage; } /** * Asynchronously retrieves the time which this WebappDataStorage was last * opened using {@link WebappDataStorage#open(Context, String)}. * @param context The context to read the SharedPreferences file. * @param webappId The ID of the web app the used time is being read for. * @param callback Called when the last used time has been retrieved. */ public static void getLastUsedTime(final Context context, final String webappId, final FetchCallback<Long> callback) { new AsyncTask<Void, Void, Long>() { @Override protected final Long doInBackground(Void... nothing) { long lastUsed = new WebappDataStorage(context.getApplicationContext(), webappId) .getLastUsedTime(); assert lastUsed != INVALID_LAST_USED; return lastUsed; } @Override protected final void onPostExecute(Long lastUsed) { callback.onDataRetrieved(lastUsed); } }.execute(); } /** * Deletes the data for a web app by clearing all the information inside the SharedPreferences * file. This does NOT delete the file itself but the file is left empty. * @param context The context to read the SharedPreferences file. * @param webappId The ID of the web app being deleted. */ static void deleteDataForWebapp(final Context context, final String webappId) { assert !ThreadUtils.runningOnUiThread(); openSharedPreferences(context, webappId).edit().clear().commit(); } /** * Sets the factory used to generate WebappDataStorage objects. */ @VisibleForTesting public static void setFactoryForTests(Factory factory) { sFactory = factory; } private static SharedPreferences openSharedPreferences(Context context, String webappId) { return context.getApplicationContext().getSharedPreferences( SHARED_PREFS_FILE_PREFIX + webappId, Context.MODE_PRIVATE); } protected WebappDataStorage(Context context, String webappId) { mPreferences = openSharedPreferences(context, webappId); } /* * Asynchronously retrieves the splash screen image associated with the * current web app. * @param callback Called when the splash screen image has been retrieved. * May be null if no image was found. */ public void getSplashScreenImage(FetchCallback<Bitmap> callback) { new BitmapFetchTask(KEY_SPLASH_ICON, callback).execute(); } /* * Update the information associated with the web app with the specified data. * @param splashScreenImage The image which should be shown on the splash screen of the web app. */ public void updateSplashScreenImage(Bitmap splashScreenImage) { new UpdateTask(splashScreenImage).execute(); } void updateLastUsedTime() { assert !ThreadUtils.runningOnUiThread(); mPreferences.edit().putLong(KEY_LAST_USED, System.currentTimeMillis()).commit(); } long getLastUsedTime() { assert !ThreadUtils.runningOnUiThread(); return mPreferences.getLong(KEY_LAST_USED, INVALID_LAST_USED); } private Map<String, ?> getAllData() { return mPreferences.getAll(); } /** * Called after data has been retrieved from storage. */ public interface FetchCallback<T> { public void onDataRetrieved(T readObject); } /** * Factory used to generate WebappDataStorage objects. * * It is used in tests to override methods in WebappDataStorage and inject the mocked objects. */ public static class Factory { /** * Generates a WebappDataStorage class for a specified web app. */ public WebappDataStorage create(final Context context, final String webappId) { return new WebappDataStorage(context, webappId); } } private final class BitmapFetchTask extends AsyncTask<Void, Void, Bitmap> { private final String mKey; private final FetchCallback<Bitmap> mCallback; public BitmapFetchTask(String key, FetchCallback<Bitmap> callback) { mKey = key; mCallback = callback; } @Override protected final Bitmap doInBackground(Void... nothing) { return ShortcutHelper.decodeBitmapFromString(mPreferences.getString(mKey, null)); } @Override protected final void onPostExecute(Bitmap result) { mCallback.onDataRetrieved(result); } } private final class UpdateTask extends AsyncTask<Void, Void, Void> { private final Bitmap mSplashImage; public UpdateTask(Bitmap splashImage) { mSplashImage = splashImage; } @Override protected Void doInBackground(Void... nothing) { mPreferences.edit() .putString(KEY_SPLASH_ICON, ShortcutHelper.encodeBitmapAsString(mSplashImage)) .commit(); return null; } } }
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.svn; import com.intellij.openapi.progress.EmptyProgressIndicator; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vcs.CheckoutProvider; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.VcsException; import com.intellij.openapi.vcs.VcsKey; import com.intellij.openapi.vcs.changes.Change; import com.intellij.openapi.vcs.changes.CurrentContentRevision; import com.intellij.openapi.vcs.update.UpdateSession; import com.intellij.openapi.vcs.update.UpdatedFiles; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.vcsUtil.VcsUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.svn.api.Depth; import org.jetbrains.idea.svn.api.Revision; import org.jetbrains.idea.svn.api.Url; import org.jetbrains.idea.svn.auth.*; import org.jetbrains.idea.svn.checkout.SvnCheckoutProvider; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static com.intellij.testFramework.UsefulTestCase.assertExists; import static org.jetbrains.idea.svn.SvnUtil.parseUrl; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @Ignore public class SvnNativeClientAuthTest extends SvnTestCase { private AcceptResult myCertificateAnswer = AcceptResult.ACCEPTED_TEMPORARILY; private boolean myCredentialsCorrect = true; private boolean mySaveCredentials = false; private boolean myCancelAuth = false; private static final String outHttpUser = "test"; private static final String outHttpPassword = "test"; private final static Url ourHTTP_URL = parseUrl("http://svnsrvtest/stuff/autoTest", false); private final static Url ourHTTPS_URL = parseUrl("https://svnsrvtest:443/TestSSL/autoTest", false); private int myCertificateAskedInteractivelyCount = 0; private int myCredentialsAskedInteractivelyCount = 0; private int myExpectedCreds = 0; private int myExpectedCert = 0; private boolean myIsSecure; @Override @Before public void setUp() throws Exception { super.setUp(); final File certFile = new File(myPluginRoot, getTestDataDir() + "/svn/____.pfx"); // replace authentication provider so that pass credentials without dialogs final SvnConfiguration configuration = SvnConfiguration.getInstance(myProject); final File svnconfig = FileUtil.createTempDirectory("svnconfig", ""); configuration.setConfigurationDirParameters(false, svnconfig.getPath()); final SvnAuthenticationManager interactiveManager = configuration.getInteractiveManager(vcs); final SvnTestInteractiveAuthentication authentication = new SvnTestInteractiveAuthentication() { @Override public AcceptResult acceptServerAuthentication(Url url, String realm, Object certificate, boolean canCache) { ++ myCertificateAskedInteractivelyCount; return myCertificateAnswer; } @Override public AuthenticationData requestClientAuthentication(String kind, Url url, String realm, boolean canCache) { if (myCancelAuth) return null; return super.requestClientAuthentication(kind, url, realm, canCache); } }; interactiveManager.setAuthenticationProvider(authentication); final SvnAuthenticationManager manager = configuration.getAuthenticationManager(vcs); // will be the same as in interactive -> authentication notifier is not used manager.setAuthenticationProvider(authentication); authentication.addAuthentication(SvnAuthenticationManager.PASSWORD, o -> { ++ myCredentialsAskedInteractivelyCount; if (myCancelAuth) return null; if (myCredentialsCorrect) { return new PasswordAuthenticationData(outHttpUser, outHttpPassword, mySaveCredentials); } else { myCredentialsCorrect = true;// only once return new PasswordAuthenticationData("1234214 23 4234", "324324", mySaveCredentials); } }); authentication.addAuthentication(SvnAuthenticationManager.SSL, o -> { ++ myCredentialsAskedInteractivelyCount; if (myCancelAuth) return null; if (myCredentialsCorrect) { return new CertificateAuthenticationData(certFile.getAbsolutePath(), "12345".toCharArray(), mySaveCredentials); } else { myCredentialsCorrect = true;// only once return new CertificateAuthenticationData("1232432423", "3245321532534235445".toCharArray(), mySaveCredentials); } }); myCertificateAskedInteractivelyCount = 0; myCredentialsAskedInteractivelyCount = 0; } @Test public void testTmpHttpUpdate() throws Exception { final File wc1 = testCheckoutImpl(ourHTTP_URL); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); final SvnConfiguration instance = SvnConfiguration.getInstance(myProject); clearAuthCache(instance); mySaveCredentials = false; updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); // credentials are cached now only updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); } @Test public void testTmpSSLUpdate() throws Exception { final File wc1 = testCheckoutImpl(ourHTTPS_URL); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); final SvnConfiguration instance = SvnConfiguration.getInstance(myProject); clearAuthCache(instance); mySaveCredentials = false; updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); // credentials are cached now only updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); } @Test public void testPermanentSSLUpdate() throws Exception { final File wc1 = testCheckoutImpl(ourHTTPS_URL); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); final SvnConfiguration instance = SvnConfiguration.getInstance(myProject); clearAuthCache(instance); mySaveCredentials = true; updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); // credentials are cached now only updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); } @Test public void testPermanentHttpUpdate() throws Exception { final File wc1 = testCheckoutImpl(ourHTTP_URL); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); final SvnConfiguration instance = SvnConfiguration.getInstance(myProject); clearAuthCache(instance); mySaveCredentials = true; updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); // credentials are cached now only updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); } @Test public void testTmpHttpCommit() throws Exception { final File wc1 = testCheckoutImpl(ourHTTP_URL); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); final SvnConfiguration instance = SvnConfiguration.getInstance(myProject); clearAuthCache(instance); mySaveCredentials = false; testCommitImpl(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); // credentials are cached now only testCommitImpl(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); } @Test public void testTmpSSLCommit() throws Exception { final File wc1 = testCheckoutImpl(ourHTTPS_URL); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); final SvnConfiguration instance = SvnConfiguration.getInstance(myProject); clearAuthCache(instance); mySaveCredentials = false; testCommitImpl(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); // credentials are cached now only testCommitImpl(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); } @Test public void testPermanentSSLCommit() throws Exception { final File wc1 = testCheckoutImpl(ourHTTPS_URL); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); final SvnConfiguration instance = SvnConfiguration.getInstance(myProject); clearAuthCache(instance); mySaveCredentials = true; testCommitImpl(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); // credentials are cached now only testCommitImpl(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); } @Test public void test2PermanentSSLCommit() throws Exception { final File wc1 = testCheckoutImpl(ourHTTPS_URL); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); final SvnConfiguration instance = SvnConfiguration.getInstance(myProject); clearAuthCache(instance); mySaveCredentials = true; myCertificateAnswer = AcceptResult.ACCEPTED_PERMANENTLY; testCommitImpl(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); // credentials are cached now only testCommitImpl(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); } private static void clearAuthCache(@NotNull SvnConfiguration instance) { SvnAuthenticationNotifier.clearAuthenticationDirectory(instance); instance.clearRuntimeStorage(); } @Test public void testMixedSSLCommit() throws Exception { final File wc1 = testCheckoutImpl(ourHTTPS_URL); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); final SvnConfiguration instance = SvnConfiguration.getInstance(myProject); clearAuthCache(instance); mySaveCredentials = false; myCertificateAnswer = AcceptResult.ACCEPTED_PERMANENTLY; testCommitImpl(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); // credentials are cached now only testCommitImpl(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); //------------ clearAuthCache(instance); mySaveCredentials = true; myCertificateAnswer = AcceptResult.ACCEPTED_TEMPORARILY; testCommitImpl(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); testCommitImpl(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); } @Test public void testPermanentHttpCommit() throws Exception { final File wc1 = testCheckoutImpl(ourHTTP_URL); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); final SvnConfiguration instance = SvnConfiguration.getInstance(myProject); clearAuthCache(instance); mySaveCredentials = true; testCommitImpl(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); // credentials are cached now only testCommitImpl(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); } @Test public void testFailedThenSuccessTmpHttpUpdate() throws Exception { final File wc1 = testCheckoutImpl(ourHTTP_URL); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); final SvnConfiguration instance = SvnConfiguration.getInstance(myProject); clearAuthCache(instance); mySaveCredentials = false; myCredentialsCorrect = false; updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); // credentials are cached now only updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); } @Test public void testFailedThenSuccessTmpSSLUpdate() throws Exception { final File wc1 = testCheckoutImpl(ourHTTPS_URL); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); final SvnConfiguration instance = SvnConfiguration.getInstance(myProject); clearAuthCache(instance); mySaveCredentials = false; myCredentialsCorrect = false; updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); // credentials wrong, but certificate was ok accepted //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); // credentials are cached now only updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); } @Test public void testCertificateRejectedThenCredentialsFailedThenSuccessTmpSSLUpdate() throws Exception { final File wc1 = testCheckoutImpl(ourHTTPS_URL); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); final SvnConfiguration instance = SvnConfiguration.getInstance(myProject); clearAuthCache(instance); mySaveCredentials = false; myCertificateAnswer = AcceptResult.REJECTED; updateExpectAuthCanceled(wc1, "Authentication canceled"); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); myCertificateAnswer = AcceptResult.ACCEPTED_TEMPORARILY; myCredentialsCorrect = false; updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); // credentials wrong, but certificate was ok accepted //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); // credentials are cached now only updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); } @Test public void testCanceledThenFailedThenSuccessTmpHttpUpdate() throws Exception { final File wc1 = testCheckoutImpl(ourHTTP_URL); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); final SvnConfiguration instance = SvnConfiguration.getInstance(myProject); clearAuthCache(instance); mySaveCredentials = false; myCredentialsCorrect = false; myCancelAuth = true; updateExpectAuthCanceled(wc1, "Authentication canceled"); myCancelAuth = false; updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); // credentials are cached now only updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); } @Test public void testCanceledThenFailedThenSuccessTmpSSLUpdate() throws Exception { final File wc1 = testCheckoutImpl(ourHTTPS_URL); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); final SvnConfiguration instance = SvnConfiguration.getInstance(myProject); clearAuthCache(instance); mySaveCredentials = false; myCredentialsCorrect = false; myCancelAuth = true; updateExpectAuthCanceled(wc1, "Authentication canceled"); myCancelAuth = false; updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); // credentials are cached now only updateSimple(wc1); //Assert.assertEquals(myExpectedCreds, myCredentialsAskedInteractivelyCount); //Assert.assertEquals(myExpectedCert, myCertificateAskedInteractivelyCount); } private File testCommitImpl(File wc1) throws IOException { assertTrue(wc1.isDirectory()); final File file = FileUtil.createTempFile(wc1, "file", ".txt"); final VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file); assertNotNull(vf); final ArrayList<VirtualFile> files = new ArrayList<>(); files.add(vf); final List<VcsException> exceptions = vcs.getCheckinEnvironment().scheduleUnversionedFilesForAddition(files); assertTrue(exceptions.isEmpty()); final Change change = new Change(null, new CurrentContentRevision(VcsUtil.getFilePath(vf))); commit(Collections.singletonList(change), "commit"); ++ myExpectedCreds; ++ myExpectedCert; return file; } private File testCheckoutImpl(@NotNull Url url) throws IOException { final File root = FileUtil.createTempDirectory("checkoutRoot", ""); root.deleteOnExit(); assertExists(root); SvnCheckoutProvider .checkout(myProject, root, url, Revision.HEAD, Depth.INFINITY, false, new CheckoutProvider.Listener() { @Override public void directoryCheckedOut(File directory, VcsKey vcs) { } @Override public void checkoutCompleted() { } }, WorkingCopyFormat.ONE_DOT_SEVEN); final int[] cnt = new int[1]; cnt[0] = 0; FileUtil.processFilesRecursively(root, file -> { ++ cnt[0]; return ! (cnt[0] > 1); }); assertTrue(cnt[0] > 1); myIsSecure = "https".equals(url.getProtocol()); if (myIsSecure) { ++ myExpectedCreds; ++ myExpectedCert; } vcsManager.setDirectoryMapping(root.getPath(), SvnVcs.VCS_NAME); refreshSvnMappingsSynchronously(); return root; } private void updateExpectAuthCanceled(File wc1, String expectedText) { assertTrue(wc1.isDirectory()); final VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(wc1); final UpdatedFiles files = UpdatedFiles.create(); final UpdateSession session = vcs.getUpdateEnvironment().updateDirectories(new FilePath[]{VcsUtil.getFilePath(vf)}, files, new EmptyProgressIndicator(), new Ref<>()); assertTrue(session.getExceptions() != null && !session.getExceptions().isEmpty()); assertTrue(!session.isCanceled()); assertTrue(session.getExceptions().get(0).getMessage().contains(expectedText)); if (myIsSecure) { ++ myExpectedCreds; ++ myExpectedCert; } } private void updateSimple(File wc1) { assertTrue(wc1.isDirectory()); final VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(wc1); final UpdatedFiles files = UpdatedFiles.create(); final UpdateSession session = vcs.getUpdateEnvironment().updateDirectories(new FilePath[]{VcsUtil.getFilePath(vf)}, files, new EmptyProgressIndicator(), new Ref<>()); assertTrue(session.getExceptions() == null || session.getExceptions().isEmpty()); assertTrue(!session.isCanceled()); if (myIsSecure) { ++ myExpectedCreds; ++ myExpectedCert; } } }
/* * Copyright (C) 2014 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.example.android.navigationdrawer; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Intent; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.widget.DrawerLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import com.comp4905.jasonfleischer.midimusic.R; import com.midisheetmusic.ChooseSongActivity; /** * This example illustrates a common usage of the DrawerLayout widget * in the Android support library. * <p/> * <p>When a navigation (left) drawer is present, the host activity should detect presses of * the action bar's Up affordance as a signal to open and close the navigation drawer. The * ActionBarDrawerToggle facilitates this behavior. * Items within the drawer should fall into one of two categories:</p> * <p/> * <ul> * <li><strong>View switches</strong>. A view switch follows the same basic policies as * list or tab navigation in that a view switch does not create navigation history. * This pattern should only be used at the root activity of a task, leaving some form * of Up navigation active for activities further down the navigation hierarchy.</li> * <li><strong>Selective Up</strong>. The drawer allows the user to choose an alternate * parent for Up navigation. This allows a user to jump across an app's navigation * hierarchy at will. The application should treat this as it treats Up navigation from * a different task, replacing the current task stack using TaskStackBuilder or similar. * This is the only form of navigation drawer that should be used outside of the root * activity of a task.</li> * </ul> * <p/> * <p>Right side drawers should be used for actions, not navigation. This follows the pattern * established by the Action Bar that navigation should be to the left and actions to the right. * An action should be an operation performed on the current contents of the window, * for example enabling or disabling a data overlay on top of the current content.</p> */ public class AboutUs extends Activity implements PlanetAdapter.OnItemClickListener { private DrawerLayout mDrawerLayout; private RecyclerView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private CharSequence mDrawerTitle; private CharSequence mTitle; private String[] mPlanetTitles; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.aboutus); WebView wv = (WebView) findViewById(R.id.aboutwebview); wv.loadUrl("http://202.125.255.1/finaltruetonev1/index.php/user/guestAbout"); WebSettings webSettings = wv.getSettings(); webSettings.setJavaScriptEnabled(true); mTitle = mDrawerTitle = getTitle(); mPlanetTitles = getResources().getStringArray(R.array.planets_array); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (RecyclerView) findViewById(R.id.left_drawer); // set a custom shadow that overlays the main content when the drawer opens // mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // improve performance by indicating the list if fixed size. mDrawerList.setHasFixedSize(true); mDrawerList.setLayoutManager(new LinearLayoutManager(this)); // set up the drawer's list view with items and click listener mDrawerList.setAdapter(new PlanetAdapter(mPlanetTitles, this)); // enable ActionBar app icon to behave as action to toggle nav drawer getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setHomeButtonEnabled(true); // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle( this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description for accessibility */ R.string.drawer_close /* "close drawer" description for accessibility */ ) { public void onDrawerClosed(View view) { getActionBar().setTitle(mTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } public void onDrawerOpened(View drawerView) { getActionBar().setTitle(mDrawerTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerLayout.setDrawerListener(mDrawerToggle); if (savedInstanceState == null) { selectItem(2); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.navigation_drawer, menu); return true; } /* Called whenever we call invalidateOptionsMenu() */ @Override public boolean onPrepareOptionsMenu(Menu menu) { // If the nav drawer is open, hide action items related to the content view boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // The action bar home/up action should open or close the drawer. // ActionBarDrawerToggle will take care of this. if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } // Handle action buttons switch (item.getItemId()) { default: return super.onOptionsItemSelected(item); } } /* The click listener for RecyclerView in the navigation drawer */ @Override public void onClick(View view, int position) { selectItem(position); Intent intent; switch (position) { case 0: intent = new Intent(this, com.comp4905.jasonfleischer.midimusic.MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); this.startActivity(intent); break; case 1: intent = new Intent(this, ChooseSongActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); this.startActivity(intent); break; case 2: intent = new Intent(this, AboutUs.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); this.startActivity(intent); break; case 3: intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://202.125.255.1/finaltruetonev1/index.php/user/tutorial")); this.startActivity(intent); } } private void selectItem(int position) { // update the main content by replacing fragments Fragment fragment = PlanetFragment.newInstance(position); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction ft = fragmentManager.beginTransaction(); ft.replace(R.id.content_frame, fragment); ft.commit(); // update selected item title, then close the drawer setTitle(mPlanetTitles[position]); mDrawerLayout.closeDrawer(mDrawerList); } @Override public void setTitle(CharSequence title) { mTitle = title; getActionBar().setTitle(mTitle); } /** * When using the ActionBarDrawerToggle, you must call it during * onPostCreate() and onConfigurationChanged()... */ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggls mDrawerToggle.onConfigurationChanged(newConfig); } /** * Fragment that appears in the "content_frame", shows a planet */ public static class PlanetFragment extends Fragment { public static final String ARG_PLANET_NUMBER = "planet_number"; public PlanetFragment() { // Empty constructor required for fragment subclasses } public static Fragment newInstance(int position) { Fragment fragment = new PlanetFragment(); Bundle args = new Bundle(); args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position); fragment.setArguments(args); return fragment; } } }
package com.role.grpc; import static io.grpc.stub.ClientCalls.asyncUnaryCall; import static io.grpc.stub.ClientCalls.asyncServerStreamingCall; import static io.grpc.stub.ClientCalls.asyncClientStreamingCall; import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall; import static io.grpc.stub.ClientCalls.blockingUnaryCall; import static io.grpc.stub.ClientCalls.blockingServerStreamingCall; import static io.grpc.stub.ClientCalls.futureUnaryCall; import static io.grpc.MethodDescriptor.generateFullMethodName; import static io.grpc.stub.ServerCalls.asyncUnaryCall; import static io.grpc.stub.ServerCalls.asyncServerStreamingCall; import static io.grpc.stub.ServerCalls.asyncClientStreamingCall; import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall; import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall; import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall; /** */ @javax.annotation.Generated( value = "by gRPC proto compiler (version 1.5.0)", comments = "Source: role.proto") public final class RoleServiceGrpc { private RoleServiceGrpc() {} public static final String SERVICE_NAME = "com.role.grpc.RoleService"; // Static method descriptors that strictly reflect the proto. @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static final io.grpc.MethodDescriptor<com.role.grpc.RoleRequest, com.role.grpc.RoleResponse> METHOD_LIST_ROLE = io.grpc.MethodDescriptor.<com.role.grpc.RoleRequest, com.role.grpc.RoleResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName( "com.role.grpc.RoleService", "listRole")) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.role.grpc.RoleRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.role.grpc.RoleResponse.getDefaultInstance())) .build(); @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static final io.grpc.MethodDescriptor<com.role.grpc.RoleRequest, com.role.grpc.RoleResponse> METHOD_ADD_ROLE = io.grpc.MethodDescriptor.<com.role.grpc.RoleRequest, com.role.grpc.RoleResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName( "com.role.grpc.RoleService", "addRole")) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.role.grpc.RoleRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.role.grpc.RoleResponse.getDefaultInstance())) .build(); @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static final io.grpc.MethodDescriptor<com.role.grpc.RoleRequest, com.role.grpc.RoleResponse> METHOD_REMOVE_ROLE = io.grpc.MethodDescriptor.<com.role.grpc.RoleRequest, com.role.grpc.RoleResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName( "com.role.grpc.RoleService", "removeRole")) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.role.grpc.RoleRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.role.grpc.RoleResponse.getDefaultInstance())) .build(); @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static final io.grpc.MethodDescriptor<com.role.grpc.RoleRequest, com.role.grpc.RoleResponse> METHOD_MODIFY_ROLE = io.grpc.MethodDescriptor.<com.role.grpc.RoleRequest, com.role.grpc.RoleResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName( "com.role.grpc.RoleService", "modifyRole")) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.role.grpc.RoleRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.role.grpc.RoleResponse.getDefaultInstance())) .build(); @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static final io.grpc.MethodDescriptor<com.role.grpc.RoleRequest, com.role.grpc.RoleResponse> METHOD_CHANGE_POWER = io.grpc.MethodDescriptor.<com.role.grpc.RoleRequest, com.role.grpc.RoleResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName( "com.role.grpc.RoleService", "changePower")) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.role.grpc.RoleRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.role.grpc.RoleResponse.getDefaultInstance())) .build(); @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") public static final io.grpc.MethodDescriptor<com.role.grpc.RoleRequest, com.role.grpc.RoleResponse> METHOD_GET_ROLE = io.grpc.MethodDescriptor.<com.role.grpc.RoleRequest, com.role.grpc.RoleResponse>newBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName( "com.role.grpc.RoleService", "getRole")) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.role.grpc.RoleRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( com.role.grpc.RoleResponse.getDefaultInstance())) .build(); /** * Creates a new async stub that supports all call types for the service */ public static RoleServiceStub newStub(io.grpc.Channel channel) { return new RoleServiceStub(channel); } /** * Creates a new blocking-style stub that supports unary and streaming output calls on the service */ public static RoleServiceBlockingStub newBlockingStub( io.grpc.Channel channel) { return new RoleServiceBlockingStub(channel); } /** * Creates a new ListenableFuture-style stub that supports unary calls on the service */ public static RoleServiceFutureStub newFutureStub( io.grpc.Channel channel) { return new RoleServiceFutureStub(channel); } /** */ public static abstract class RoleServiceImplBase implements io.grpc.BindableService { /** */ public void listRole(com.role.grpc.RoleRequest request, io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse> responseObserver) { asyncUnimplementedUnaryCall(METHOD_LIST_ROLE, responseObserver); } /** */ public void addRole(com.role.grpc.RoleRequest request, io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse> responseObserver) { asyncUnimplementedUnaryCall(METHOD_ADD_ROLE, responseObserver); } /** */ public void removeRole(com.role.grpc.RoleRequest request, io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse> responseObserver) { asyncUnimplementedUnaryCall(METHOD_REMOVE_ROLE, responseObserver); } /** */ public void modifyRole(com.role.grpc.RoleRequest request, io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse> responseObserver) { asyncUnimplementedUnaryCall(METHOD_MODIFY_ROLE, responseObserver); } /** */ public void changePower(com.role.grpc.RoleRequest request, io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse> responseObserver) { asyncUnimplementedUnaryCall(METHOD_CHANGE_POWER, responseObserver); } /** */ public void getRole(com.role.grpc.RoleRequest request, io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse> responseObserver) { asyncUnimplementedUnaryCall(METHOD_GET_ROLE, responseObserver); } @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) .addMethod( METHOD_LIST_ROLE, asyncUnaryCall( new MethodHandlers< com.role.grpc.RoleRequest, com.role.grpc.RoleResponse>( this, METHODID_LIST_ROLE))) .addMethod( METHOD_ADD_ROLE, asyncUnaryCall( new MethodHandlers< com.role.grpc.RoleRequest, com.role.grpc.RoleResponse>( this, METHODID_ADD_ROLE))) .addMethod( METHOD_REMOVE_ROLE, asyncUnaryCall( new MethodHandlers< com.role.grpc.RoleRequest, com.role.grpc.RoleResponse>( this, METHODID_REMOVE_ROLE))) .addMethod( METHOD_MODIFY_ROLE, asyncUnaryCall( new MethodHandlers< com.role.grpc.RoleRequest, com.role.grpc.RoleResponse>( this, METHODID_MODIFY_ROLE))) .addMethod( METHOD_CHANGE_POWER, asyncUnaryCall( new MethodHandlers< com.role.grpc.RoleRequest, com.role.grpc.RoleResponse>( this, METHODID_CHANGE_POWER))) .addMethod( METHOD_GET_ROLE, asyncUnaryCall( new MethodHandlers< com.role.grpc.RoleRequest, com.role.grpc.RoleResponse>( this, METHODID_GET_ROLE))) .build(); } } /** */ public static final class RoleServiceStub extends io.grpc.stub.AbstractStub<RoleServiceStub> { private RoleServiceStub(io.grpc.Channel channel) { super(channel); } private RoleServiceStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected RoleServiceStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new RoleServiceStub(channel, callOptions); } /** */ public void listRole(com.role.grpc.RoleRequest request, io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(METHOD_LIST_ROLE, getCallOptions()), request, responseObserver); } /** */ public void addRole(com.role.grpc.RoleRequest request, io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(METHOD_ADD_ROLE, getCallOptions()), request, responseObserver); } /** */ public void removeRole(com.role.grpc.RoleRequest request, io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(METHOD_REMOVE_ROLE, getCallOptions()), request, responseObserver); } /** */ public void modifyRole(com.role.grpc.RoleRequest request, io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(METHOD_MODIFY_ROLE, getCallOptions()), request, responseObserver); } /** */ public void changePower(com.role.grpc.RoleRequest request, io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(METHOD_CHANGE_POWER, getCallOptions()), request, responseObserver); } /** */ public void getRole(com.role.grpc.RoleRequest request, io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(METHOD_GET_ROLE, getCallOptions()), request, responseObserver); } } /** */ public static final class RoleServiceBlockingStub extends io.grpc.stub.AbstractStub<RoleServiceBlockingStub> { private RoleServiceBlockingStub(io.grpc.Channel channel) { super(channel); } private RoleServiceBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected RoleServiceBlockingStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new RoleServiceBlockingStub(channel, callOptions); } /** */ public com.role.grpc.RoleResponse listRole(com.role.grpc.RoleRequest request) { return blockingUnaryCall( getChannel(), METHOD_LIST_ROLE, getCallOptions(), request); } /** */ public com.role.grpc.RoleResponse addRole(com.role.grpc.RoleRequest request) { return blockingUnaryCall( getChannel(), METHOD_ADD_ROLE, getCallOptions(), request); } /** */ public com.role.grpc.RoleResponse removeRole(com.role.grpc.RoleRequest request) { return blockingUnaryCall( getChannel(), METHOD_REMOVE_ROLE, getCallOptions(), request); } /** */ public com.role.grpc.RoleResponse modifyRole(com.role.grpc.RoleRequest request) { return blockingUnaryCall( getChannel(), METHOD_MODIFY_ROLE, getCallOptions(), request); } /** */ public com.role.grpc.RoleResponse changePower(com.role.grpc.RoleRequest request) { return blockingUnaryCall( getChannel(), METHOD_CHANGE_POWER, getCallOptions(), request); } /** */ public com.role.grpc.RoleResponse getRole(com.role.grpc.RoleRequest request) { return blockingUnaryCall( getChannel(), METHOD_GET_ROLE, getCallOptions(), request); } } /** */ public static final class RoleServiceFutureStub extends io.grpc.stub.AbstractStub<RoleServiceFutureStub> { private RoleServiceFutureStub(io.grpc.Channel channel) { super(channel); } private RoleServiceFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); } @java.lang.Override protected RoleServiceFutureStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { return new RoleServiceFutureStub(channel, callOptions); } /** */ public com.google.common.util.concurrent.ListenableFuture<com.role.grpc.RoleResponse> listRole( com.role.grpc.RoleRequest request) { return futureUnaryCall( getChannel().newCall(METHOD_LIST_ROLE, getCallOptions()), request); } /** */ public com.google.common.util.concurrent.ListenableFuture<com.role.grpc.RoleResponse> addRole( com.role.grpc.RoleRequest request) { return futureUnaryCall( getChannel().newCall(METHOD_ADD_ROLE, getCallOptions()), request); } /** */ public com.google.common.util.concurrent.ListenableFuture<com.role.grpc.RoleResponse> removeRole( com.role.grpc.RoleRequest request) { return futureUnaryCall( getChannel().newCall(METHOD_REMOVE_ROLE, getCallOptions()), request); } /** */ public com.google.common.util.concurrent.ListenableFuture<com.role.grpc.RoleResponse> modifyRole( com.role.grpc.RoleRequest request) { return futureUnaryCall( getChannel().newCall(METHOD_MODIFY_ROLE, getCallOptions()), request); } /** */ public com.google.common.util.concurrent.ListenableFuture<com.role.grpc.RoleResponse> changePower( com.role.grpc.RoleRequest request) { return futureUnaryCall( getChannel().newCall(METHOD_CHANGE_POWER, getCallOptions()), request); } /** */ public com.google.common.util.concurrent.ListenableFuture<com.role.grpc.RoleResponse> getRole( com.role.grpc.RoleRequest request) { return futureUnaryCall( getChannel().newCall(METHOD_GET_ROLE, getCallOptions()), request); } } private static final int METHODID_LIST_ROLE = 0; private static final int METHODID_ADD_ROLE = 1; private static final int METHODID_REMOVE_ROLE = 2; private static final int METHODID_MODIFY_ROLE = 3; private static final int METHODID_CHANGE_POWER = 4; private static final int METHODID_GET_ROLE = 5; private static final class MethodHandlers<Req, Resp> implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>, io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>, io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> { private final RoleServiceImplBase serviceImpl; private final int methodId; MethodHandlers(RoleServiceImplBase serviceImpl, int methodId) { this.serviceImpl = serviceImpl; this.methodId = methodId; } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { case METHODID_LIST_ROLE: serviceImpl.listRole((com.role.grpc.RoleRequest) request, (io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse>) responseObserver); break; case METHODID_ADD_ROLE: serviceImpl.addRole((com.role.grpc.RoleRequest) request, (io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse>) responseObserver); break; case METHODID_REMOVE_ROLE: serviceImpl.removeRole((com.role.grpc.RoleRequest) request, (io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse>) responseObserver); break; case METHODID_MODIFY_ROLE: serviceImpl.modifyRole((com.role.grpc.RoleRequest) request, (io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse>) responseObserver); break; case METHODID_CHANGE_POWER: serviceImpl.changePower((com.role.grpc.RoleRequest) request, (io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse>) responseObserver); break; case METHODID_GET_ROLE: serviceImpl.getRole((com.role.grpc.RoleRequest) request, (io.grpc.stub.StreamObserver<com.role.grpc.RoleResponse>) responseObserver); break; default: throw new AssertionError(); } } @java.lang.Override @java.lang.SuppressWarnings("unchecked") public io.grpc.stub.StreamObserver<Req> invoke( io.grpc.stub.StreamObserver<Resp> responseObserver) { switch (methodId) { default: throw new AssertionError(); } } } private static final class RoleServiceDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier { @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return com.role.grpc.RoleOuterClass.getDescriptor(); } } private static volatile io.grpc.ServiceDescriptor serviceDescriptor; public static io.grpc.ServiceDescriptor getServiceDescriptor() { io.grpc.ServiceDescriptor result = serviceDescriptor; if (result == null) { synchronized (RoleServiceGrpc.class) { result = serviceDescriptor; if (result == null) { serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new RoleServiceDescriptorSupplier()) .addMethod(METHOD_LIST_ROLE) .addMethod(METHOD_ADD_ROLE) .addMethod(METHOD_REMOVE_ROLE) .addMethod(METHOD_MODIFY_ROLE) .addMethod(METHOD_CHANGE_POWER) .addMethod(METHOD_GET_ROLE) .build(); } } } return result; } }
package com.hotpatch; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.os.Build; import android.text.TextUtils; import android.util.DisplayMetrics; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.math.BigInteger; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Iterator; import java.util.List; public class Utils { /** * Get the Signature of apk file which is not installed. * * @param apkPath * @return */ public static String getApkSignature(String apkPath) { String PATH_PackageParser = "android.content.pm.PackageParser"; try { Class<?> pkgParserCls = Class.forName(PATH_PackageParser); Class<?>[] typeArgs = new Class[1]; typeArgs[0] = String.class; Object[] valueArgs = new Object[1]; valueArgs[0] = apkPath; Object pkgParser; if (Build.VERSION.SDK_INT > 19) { pkgParser = pkgParserCls.newInstance(); } else { Constructor constructor = pkgParserCls.getConstructor(typeArgs); pkgParser = constructor.newInstance(valueArgs); } DisplayMetrics metrics = new DisplayMetrics(); metrics.setToDefaults(); Object pkgParserPkg = null; if (Build.VERSION.SDK_INT > 19) { typeArgs = new Class[2]; typeArgs[0] = File.class; typeArgs[1] = int.class; Method pkgParser_parsePackageMtd = pkgParserCls.getDeclaredMethod( "parsePackage", typeArgs); pkgParser_parsePackageMtd.setAccessible(true); valueArgs = new Object[2]; valueArgs[0] = new File(apkPath); valueArgs[1] = PackageManager.GET_SIGNATURES; pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser, valueArgs); } else { typeArgs = new Class[4]; typeArgs[0] = File.class; typeArgs[1] = String.class; typeArgs[2] = DisplayMetrics.class; typeArgs[3] = int.class; Method pkgParser_parsePackageMtd = pkgParserCls.getDeclaredMethod( "parsePackage", typeArgs); pkgParser_parsePackageMtd.setAccessible(true); valueArgs = new Object[4]; valueArgs[0] = new File(apkPath); valueArgs[1] = apkPath; valueArgs[2] = metrics; valueArgs[3] = PackageManager.GET_SIGNATURES; pkgParserPkg = pkgParser_parsePackageMtd.invoke(pkgParser, valueArgs); } typeArgs = new Class[2]; typeArgs[0] = pkgParserPkg.getClass(); typeArgs[1] = int.class; Method pkgParser_collectCertificatesMtd = pkgParserCls.getDeclaredMethod("collectCertificates", typeArgs); valueArgs = new Object[2]; valueArgs[0] = pkgParserPkg; valueArgs[1] = PackageManager.GET_SIGNATURES; pkgParser_collectCertificatesMtd.invoke(pkgParser, valueArgs); Field packageInfoFld = pkgParserPkg.getClass().getDeclaredField( "mSignatures"); Signature[] info = (Signature[]) packageInfoFld.get(pkgParserPkg); return info[0].toCharsString(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * Get the Signature of the apk file which package name is @param packageName * * @param context * @param packageName * @return */ public static String getInstallPackageSignature(Context context, String packageName) { PackageManager pm = context.getPackageManager(); List<PackageInfo> apps = pm .getInstalledPackages(PackageManager.GET_SIGNATURES); Iterator<PackageInfo> iter = apps.iterator(); while (iter.hasNext()) { PackageInfo packageinfo = iter.next(); String thisName = packageinfo.packageName; if (thisName.equals(packageName)) { return packageinfo.signatures[0].toCharsString(); } } return null; } public static String getMd5ByFile(File file) { String value = null; FileInputStream in=null; try { in = new FileInputStream(file); MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length()); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(byteBuffer); BigInteger bi = new BigInteger(1, md5.digest()); value = bi.toString(16); } catch (Exception e) { e.printStackTrace(); } finally { if (null != in) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return value; } public static String md5(String string) { byte[] hash; try { hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Huh, MD5 should be supported?", e); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Huh, UTF-8 should be supported?", e); } StringBuilder hex = new StringBuilder(hash.length * 2); for (byte b : hash) { if ((b & 0xFF) < 0x10) hex.append("0"); hex.append(Integer.toHexString(b & 0xFF)); } return hex.toString(); } public static String getCacheApkFilePath(Context ctx,String fileUrl){ return ctx.getExternalCacheDir()+"/"+md5(fileUrl)+".apk"; } /** * * Compare the patch apk to the apk which package name is ctx.getPackageName() * @return the result of compare * **/ public static boolean isSignEqual(Context ctx,String apkFile){ String packageSign=getInstallPackageSignature(ctx,ctx.getPackageName()); String apkFileSign=getApkSignature(apkFile); return TextUtils.equals(packageSign,apkFileSign); } public static String getVersionName(Context context) { try { PackageManager packageManager = context.getPackageManager(); PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0); String version =String.valueOf(packInfo.versionName); return version; } catch (Exception e) { e.printStackTrace(); } return 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.codehaus.groovy.control; import groovy.util.GroovyTestCase; import org.codehaus.groovy.control.messages.WarningMessage; import java.io.File; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; /** * Make sure CompilerConfiguration works. */ public class CompilerConfigurationTest extends GroovyTestCase { Properties savedProperties; // Use setUp/tearDown to avoid mucking with system properties for other tests... public void setUp() { savedProperties = System.getProperties(); System.setProperties(new Properties(savedProperties)); } public void tearDown() { System.setProperties(savedProperties); } public void testDefaultConstructor() { final CompilerConfiguration config = CompilerConfiguration.DEFAULT; assertEquals(WarningMessage.LIKELY_ERRORS, config.getWarningLevel()); assertEquals(Boolean.getBoolean("groovy.output.debug"), config.getDebug()); assertEquals(Boolean.getBoolean("groovy.output.verbose"), config.getVerbose()); assertEquals(false, config.getDebug()); assertEquals(false, config.getVerbose()); assertEquals(10, config.getTolerance()); assertEquals(100, config.getMinimumRecompilationInterval()); assertNull(config.getScriptBaseClass()); assertEquals(getSystemEncoding(), config.getSourceEncoding()); assertEquals(getVMVersion(), config.getTargetBytecode()); assertEquals(false, config.getRecompileGroovySource()); { final List listCP = config.getClasspath(); assertNotNull(listCP); assertEquals(0, listCP.size()); } assertNull(config.getTargetDirectory()); assertEquals(".groovy", config.getDefaultScriptExtension()); assertNull(config.getJointCompilationOptions()); assertNotNull(config.getPluginFactory()); } private String getSystemEncoding() { return System.getProperty("file.encoding", "US-ASCII"); } private static String getVMVersion() { return CompilerConfiguration.POST_JDK5; } public void testSetViaSystemProperties() { System.setProperty("groovy.warnings", "PaRaNoiA"); System.setProperty("groovy.output.verbose", "trUE"); System.setProperty("groovy.recompile.minimumInterval", "867892345"); assertEquals("PaRaNoiA", System.getProperty("groovy.warnings")); final CompilerConfiguration config = new CompilerConfiguration(System.getProperties()); assertEquals(WarningMessage.PARANOIA, config.getWarningLevel()); assertEquals(false, config.getDebug()); assertEquals(true, config.getVerbose()); assertEquals(10, config.getTolerance()); assertEquals(867892345, config.getMinimumRecompilationInterval()); assertNull(config.getScriptBaseClass()); assertEquals(getSystemEncoding(), config.getSourceEncoding()); assertEquals(getVMVersion(), config.getTargetBytecode()); assertEquals(false, config.getRecompileGroovySource()); { final List listCP = config.getClasspath(); assertNotNull(listCP); assertEquals(0, listCP.size()); } assertNull(config.getTargetDirectory()); assertEquals(".groovy", config.getDefaultScriptExtension()); assertNull(config.getJointCompilationOptions()); assertNotNull(config.getPluginFactory()); } public void testCopyConstructor1() { final CompilerConfiguration init = new CompilerConfiguration(); init.setWarningLevel(WarningMessage.POSSIBLE_ERRORS); init.setDebug(true); init.setParameters(true); init.setVerbose(false); init.setTolerance(720); init.setMinimumRecompilationInterval(234); init.setScriptBaseClass("blarg.foo.WhatSit"); init.setSourceEncoding("LEAD-123"); init.setTargetBytecode(CompilerConfiguration.POST_JDK5); init.setRecompileGroovySource(true); init.setClasspath("File1" + File.pathSeparator + "Somewhere"); final File initTDFile = new File("A wandering path"); init.setTargetDirectory(initTDFile); init.setDefaultScriptExtension(".jpp"); final Map initJoint = new HashMap(); initJoint.put("somekey", "somevalue"); init.setJointCompilationOptions(initJoint); final ParserPluginFactory initPPF = ParserPluginFactory.newInstance(); init.setPluginFactory(initPPF); assertEquals(WarningMessage.POSSIBLE_ERRORS, init.getWarningLevel()); assertEquals(true, init.getDebug()); assertEquals(true, init.getParameters()); assertEquals(false, init.getVerbose()); assertEquals(720, init.getTolerance()); assertEquals(234, init.getMinimumRecompilationInterval()); assertEquals("blarg.foo.WhatSit", init.getScriptBaseClass()); assertEquals("LEAD-123", init.getSourceEncoding()); assertEquals(CompilerConfiguration.POST_JDK5, init.getTargetBytecode()); assertEquals(true, init.getRecompileGroovySource()); { final List listCP = init.getClasspath(); assertEquals("File1", listCP.get(0)); assertEquals("Somewhere", listCP.get(1)); } assertEquals(initTDFile, init.getTargetDirectory()); assertEquals(".jpp", init.getDefaultScriptExtension()); assertEquals(initJoint, init.getJointCompilationOptions()); assertEquals(initPPF, init.getPluginFactory()); final CompilerConfiguration config = new CompilerConfiguration(init); assertEquals(WarningMessage.POSSIBLE_ERRORS, config.getWarningLevel()); assertEquals(true, config.getDebug()); assertEquals(false, config.getVerbose()); assertEquals(720, config.getTolerance()); assertEquals(234, config.getMinimumRecompilationInterval()); assertEquals("blarg.foo.WhatSit", config.getScriptBaseClass()); assertEquals("LEAD-123", config.getSourceEncoding()); assertEquals(CompilerConfiguration.POST_JDK5, config.getTargetBytecode()); assertEquals(true, config.getRecompileGroovySource()); { final List listCP = config.getClasspath(); assertEquals("File1", listCP.get(0)); assertEquals("Somewhere", listCP.get(1)); } assertEquals(initTDFile, config.getTargetDirectory()); assertEquals(".jpp", config.getDefaultScriptExtension()); assertEquals(initJoint, config.getJointCompilationOptions()); assertEquals(initPPF, config.getPluginFactory()); } public void testCopyConstructor2() { final CompilerConfiguration init = new CompilerConfiguration(); init.setWarningLevel(WarningMessage.POSSIBLE_ERRORS); init.setDebug(false); init.setParameters(false); init.setVerbose(true); init.setTolerance(55); init.setMinimumRecompilationInterval(975); init.setScriptBaseClass(""); init.setSourceEncoding("Gutenberg"); init.setTargetBytecode(CompilerConfiguration.PRE_JDK5); init.setRecompileGroovySource(false); init.setClasspath(""); final File initTDFile = new File("A wandering path"); init.setTargetDirectory(initTDFile); assertEquals(WarningMessage.POSSIBLE_ERRORS, init.getWarningLevel()); assertEquals(false, init.getDebug()); assertEquals(false, init.getParameters()); assertEquals(true, init.getVerbose()); assertEquals(55, init.getTolerance()); assertEquals(975, init.getMinimumRecompilationInterval()); assertEquals("", init.getScriptBaseClass()); assertEquals("Gutenberg", init.getSourceEncoding()); assertEquals(CompilerConfiguration.PRE_JDK5, init.getTargetBytecode()); assertEquals(false, init.getRecompileGroovySource()); { final List listCP = init.getClasspath(); assertNotNull(listCP); assertEquals(0, listCP.size()); } assertEquals(initTDFile, init.getTargetDirectory()); final CompilerConfiguration config = new CompilerConfiguration(init); assertEquals(WarningMessage.POSSIBLE_ERRORS, config.getWarningLevel()); assertEquals(false, config.getDebug()); assertEquals(true, config.getVerbose()); assertEquals(55, config.getTolerance()); assertEquals(975, config.getMinimumRecompilationInterval()); assertEquals("", config.getScriptBaseClass()); assertEquals("Gutenberg", config.getSourceEncoding()); assertEquals(CompilerConfiguration.PRE_JDK5, config.getTargetBytecode()); assertEquals(false, config.getRecompileGroovySource()); { final List listCP = config.getClasspath(); assertEquals(0, listCP.size()); } assertEquals(initTDFile, config.getTargetDirectory()); } }
/** * Copyright 2017 - 2018 Syncleus, 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.syncleus.aethermud.items; import com.google.common.collect.Sets; import com.syncleus.aethermud.core.service.TimeTracker; import com.syncleus.aethermud.spawner.SpawnRule; import com.syncleus.aethermud.stats.Stats; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; public class ItemBuilder { private String itemName; private String itemDescription; private String internalItemName; private List<String> itemTriggers; private String restingName; private String itemId; private int numberOfUses; private boolean isWithPlayer; private Loot loot; private int itemHalfLifeTicks; private Equipment equipment; private Rarity rarity; private int valueInGold; private Set<Effect> effects; private boolean hasBeenWithPlayer; private int maxUses; private boolean isDisposable; private Set<TimeTracker.TimeOfDay> validTimeOfDays; private Stats itemApplyStats; private Set<SpawnRule> spawnRules; private Set<Forage> forages; public ItemBuilder from(Item item) { this.internalItemName = item.getInternalItemName(); this.itemName = item.getItemName(); this.itemDescription = item.getItemDescription(); this.itemTriggers = item.getItemTriggers(); this.restingName = item.getRestingName(); this.itemId = UUID.randomUUID().toString(); // zero uses, its new. this.numberOfUses = 0; this.isWithPlayer = false; this.itemHalfLifeTicks = item.getItemHalfLifeTicks(); this.rarity = item.getRarity(); this.valueInGold = item.getValueInGold(); this.maxUses = item.getMaxUses(); this.loot = null; this.isDisposable = item.isDisposable(); this.equipment = item.getEquipment(); this.validTimeOfDays = new HashSet<>(item.getValidTimeOfDays()); Set<Effect> effects = item.getEffects(); this.effects = (effects != null ? Sets.newHashSet(item.getEffects()) : null ); this.itemApplyStats = item.getItemApplyStats(); this.spawnRules = (spawnRules != null ? Sets.newHashSet(item.getSpawnRules()) : null); this.forages = (forages != null ? Sets.newHashSet(item.getForages()) : null); return this; } public ItemBuilder from(ItemInstance origItem) { this.internalItemName = origItem.getInternalItemName(); this.itemName = origItem.getItemName(); this.itemDescription = origItem.getItemDescription(); this.itemTriggers = origItem.getItemTriggers(); this.restingName = origItem.getRestingName(); this.itemId = origItem.getItemId(); this.numberOfUses = new Integer(origItem.getNumberOfUses()); this.loot = origItem.getLoot(); this.itemHalfLifeTicks = origItem.getItemHalfLifeTicks(); this.isWithPlayer = new Boolean(origItem.isWithPlayer()); if (origItem.getEquipment() != null) { this.equipment = new Equipment(origItem.getEquipment()); } this.rarity = origItem.getRarity(); this.valueInGold = origItem.getValueInGold(); this.effects = origItem.getEffects(); this.hasBeenWithPlayer = new Boolean(origItem.isHasBeenWithPlayer()); this.maxUses = origItem.getMaxUses(); this.isDisposable = origItem.isDisposable(); this.validTimeOfDays = Sets.newHashSet(origItem.getValidTimeOfDays()); this.itemApplyStats = origItem.getItemApplyStats(); this.spawnRules = (spawnRules != null ? Sets.newHashSet(origItem.getSpawnRules()) : null); this.forages = (forages != null ? Sets.newHashSet(origItem.getForages()) : null); return this; } public ItemBuilder itemName(String itemName) { this.itemName = itemName; return this; } public ItemBuilder itemDescription(String itemDescription) { this.itemDescription = itemDescription; return this; } public ItemBuilder internalItemName(String internalItemName) { this.internalItemName = internalItemName; return this; } public ItemBuilder itemTriggers(List<String> itemTriggers) { this.itemTriggers = itemTriggers; return this; } public ItemBuilder restingName(String restingName) { this.restingName = restingName; return this; } public ItemBuilder itemId(String itemId) { this.itemId = itemId; return this; } public ItemBuilder numberOfUses(int numberOfUses) { this.numberOfUses = numberOfUses; return this; } public ItemBuilder isWithPlayer(boolean isWithPlayer) { this.isWithPlayer = isWithPlayer; return this; } public ItemBuilder loot(Loot loot) { this.loot = loot; return this; } public ItemBuilder itemHalfLifeTicks(int itemHalfLifeTicks) { this.itemHalfLifeTicks = itemHalfLifeTicks; return this; } public ItemBuilder equipment(Equipment equipment) { this.equipment = equipment; return this; } public ItemBuilder rarity(Rarity rarity) { this.rarity = rarity; return this; } public ItemBuilder valueInGold(int valueInGold) { this.valueInGold = valueInGold; return this; } public ItemBuilder effects(Set<Effect> effects) { this.effects = effects; return this; } public ItemBuilder hasBeenWithPlayer(boolean hasBeenWithPlayer) { this.hasBeenWithPlayer = hasBeenWithPlayer; return this; } public ItemBuilder maxUses(int maxUses) { this.maxUses = maxUses; return this; } public ItemBuilder isDisposable(boolean isDisposable) { this.isDisposable = isDisposable; return this; } public ItemBuilder validTimeOfDays(Set<TimeTracker.TimeOfDay> validTimeOfDays) { this.validTimeOfDays = validTimeOfDays; return this; } public ItemBuilder itemApplyStats(Stats itemApplyStats) { this.itemApplyStats = itemApplyStats; return this; } public ItemInstance create() { Item item = new ItemImpl(itemName, itemDescription, internalItemName, itemTriggers, restingName, loot, itemHalfLifeTicks, equipment, rarity, valueInGold, effects, maxUses, isDisposable, validTimeOfDays, itemApplyStats, spawnRules, forages); return new ItemInstanceImpl(item, itemId, numberOfUses, isWithPlayer, hasBeenWithPlayer); } }
/* * 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.tinkerpop.gremlin.driver; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.ChannelOption; import org.apache.commons.configuration.Configuration; import org.apache.tinkerpop.gremlin.driver.ser.Serializers; import io.netty.bootstrap.Bootstrap; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import org.apache.commons.lang3.concurrent.BasicThreadFactory; import javax.net.ssl.TrustManager; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.URI; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; /** * A connection to a set of one or more Gremlin Server instances. * * @author Stephen Mallette (http://stephen.genoprime.com) */ public final class Cluster { private Manager manager; private Cluster(final List<InetSocketAddress> contactPoints, final MessageSerializer serializer, final int nioPoolSize, final int workerPoolSize, final Settings.ConnectionPoolSettings connectionPoolSettings, final LoadBalancingStrategy loadBalancingStrategy, final AuthProperties authProps) { this.manager = new Manager(contactPoints, serializer, nioPoolSize, workerPoolSize, connectionPoolSettings, loadBalancingStrategy, authProps); } public synchronized void init() { if (!manager.initialized) manager.init(); } /** * Creates a {@link Client.ClusteredClient} instance to this {@code Cluster}, meaning requests will be routed to * one or more servers (depending on the cluster configuration), where each request represents the entirety of a * transaction. A commit or rollback (in case of error) is automatically executed at the end of the request. * <p/> * Note that calling this method does not imply that a connection is made to the server itself at this point. * Therefore, if there is only one server specified in the {@code Cluster} and that server is not available an * error will not be raised at this point. Connections get initialized in the {@link Client} when a request is * submitted or can be directly initialized via {@link Client#init()}. */ public <T extends Client> T connect() { return (T) new Client.ClusteredClient(this, Client.Settings.build().create()); } /** * Creates a {@link Client.SessionedClient} instance to this {@code Cluster}, meaning requests will be routed to * a single server (randomly selected from the cluster), where the same bindings will be available on each request. * Requests are bound to the same thread on the server and thus transactions may extend beyond the bounds of a * single request. The transactions are managed by the user and must be committed or rolled-back manually. * <p/> * Note that calling this method does not imply that a connection is made to the server itself at this point. * Therefore, if there is only one server specified in the {@code Cluster} and that server is not available an * error will not be raised at this point. Connections get initialized in the {@link Client} when a request is * submitted or can be directly initialized via {@link Client#init()}. * * @param sessionId user supplied id for the session which should be unique (a UUID is ideal). */ public <T extends Client> T connect(final String sessionId) { return connect(sessionId, false); } /** * Creates a {@link Client.SessionedClient} instance to this {@code Cluster}, meaning requests will be routed to * a single server (randomly selected from the cluster), where the same bindings will be available on each request. * Requests are bound to the same thread on the server and thus transactions may extend beyond the bounds of a * single request. If {@code manageTransactions} is set to {@code false} then transactions are managed by the * user and must be committed or rolled-back manually. When set to {@code true} the transaction is committed or * rolled-back at the end of each request. * <p/> * Note that calling this method does not imply that a connection is made to the server itself at this point. * Therefore, if there is only one server specified in the {@code Cluster} and that server is not available an * error will not be raised at this point. Connections get initialized in the {@link Client} when a request is * submitted or can be directly initialized via {@link Client#init()}. * * @param sessionId user supplied id for the session which should be unique (a UUID is ideal). * @param manageTransactions enables auto-transactions when set to true */ public <T extends Client> T connect(final String sessionId, final boolean manageTransactions) { final Client.SessionSettings sessionSettings = Client.SessionSettings.build() .manageTransactions(manageTransactions) .sessionId(sessionId).create(); final Client.Settings settings = Client.Settings.build().useSession(sessionSettings).create(); return connect(settings); } /** * Creates a new {@link Client} based on the settings provided. */ public <T extends Client> T connect(final Client.Settings settings) { return settings.getSession().isPresent() ? (T) new Client.SessionedClient(this, settings) : (T) new Client.ClusteredClient(this, settings); } @Override public String toString() { return manager.toString(); } public static Builder build() { return new Builder(); } public static Builder build(final String address) { return new Builder(address); } public static Builder build(final File configurationFile) throws FileNotFoundException { final Settings settings = Settings.read(new FileInputStream(configurationFile)); return getBuilderFromSettings(settings); } private static Builder getBuilderFromSettings(final Settings settings) { final List<String> addresses = settings.hosts; if (addresses.size() == 0) throw new IllegalStateException("At least one value must be specified to the hosts setting"); final Builder builder = new Builder(settings.hosts.get(0)) .port(settings.port) .enableSsl(settings.connectionPool.enableSsl) .trustCertificateChainFile(settings.connectionPool.trustCertChainFile) .nioPoolSize(settings.nioPoolSize) .workerPoolSize(settings.workerPoolSize) .reconnectInterval(settings.connectionPool.reconnectInterval) .reconnectIntialDelay(settings.connectionPool.reconnectInitialDelay) .resultIterationBatchSize(settings.connectionPool.resultIterationBatchSize) .channelizer(settings.connectionPool.channelizer) .maxContentLength(settings.connectionPool.maxContentLength) .maxWaitForConnection(settings.connectionPool.maxWaitForConnection) .maxInProcessPerConnection(settings.connectionPool.maxInProcessPerConnection) .minInProcessPerConnection(settings.connectionPool.minInProcessPerConnection) .maxSimultaneousUsagePerConnection(settings.connectionPool.maxSimultaneousUsagePerConnection) .minSimultaneousUsagePerConnection(settings.connectionPool.minSimultaneousUsagePerConnection) .maxConnectionPoolSize(settings.connectionPool.maxSize) .minConnectionPoolSize(settings.connectionPool.minSize); if (settings.username != null && settings.password != null) builder.credentials(settings.username, settings.password); if (settings.jaasEntry != null) builder.jaasEntry(settings.jaasEntry); if (settings.protocol != null) builder.protocol(settings.protocol); // the first address was added above in the constructor, so skip it if there are more if (addresses.size() > 1) addresses.stream().skip(1).forEach(builder::addContactPoint); try { builder.serializer(settings.serializer.create()); } catch (Exception ex) { throw new IllegalStateException("Could not establish serializer - " + ex.getMessage()); } return builder; } /** * Create a {@code Cluster} with all default settings which will connect to one contact point at {@code localhost}. */ public static Cluster open() { return build("localhost").create(); } /** * Create a {@code Cluster} from Apache Configurations. */ public static Cluster open(final Configuration conf) { return getBuilderFromSettings(Settings.from(conf)).create(); } /** * Create a {@code Cluster} using a YAML-based configuration file. */ public static Cluster open(final String configurationFile) throws Exception { final File file = new File(configurationFile); if (!file.exists()) throw new IllegalArgumentException(String.format("Configuration file at %s does not exist", configurationFile)); return build(file).create(); } public void close() { closeAsync().join(); } public CompletableFuture<Void> closeAsync() { return manager.close(); } /** * Determines if the {@code Cluster} is in the process of closing given a call to {@link #close} or * {@link #closeAsync()}. */ public boolean isClosing() { return manager.isClosing(); } /** * Determines if the {@code Cluster} has completed its closing process after a call to {@link #close} or * {@link #closeAsync()}. */ public boolean isClosed() { return manager.isClosing() && manager.close().isDone(); } /** * Gets the list of hosts that the {@code Cluster} was able to connect to. A {@link Host} is assumed unavailable * until a connection to it is proven to be present. This will not happen until the the {@link Client} submits * requests that succeed in reaching a server at the {@link Host} or {@link Client#init()} is called which * initializes the {@link ConnectionPool} for the {@link Client} itself. The number of available hosts returned * from this method will change as different servers come on and offline. */ public List<URI> availableHosts() { return Collections.unmodifiableList(allHosts().stream() .filter(Host::isAvailable) .map(Host::getHostUri) .collect(Collectors.toList())); } Factory getFactory() { return manager.factory; } MessageSerializer getSerializer() { return manager.serializer; } ScheduledExecutorService executor() { return manager.executor; } Settings.ConnectionPoolSettings connectionPoolSettings() { return manager.connectionPoolSettings; } LoadBalancingStrategy loadBalancingStrategy() { return manager.loadBalancingStrategy; } AuthProperties authProperties() { return manager.authProps; } Collection<Host> allHosts() { return manager.allHosts(); } public final static class Builder { private List<InetAddress> addresses = new ArrayList<>(); private int port = 8182; private MessageSerializer serializer = Serializers.GRYO_V1D0.simpleInstance(); private int nioPoolSize = Runtime.getRuntime().availableProcessors(); private int workerPoolSize = Runtime.getRuntime().availableProcessors() * 2; private int minConnectionPoolSize = ConnectionPool.MIN_POOL_SIZE; private int maxConnectionPoolSize = ConnectionPool.MAX_POOL_SIZE; private int minSimultaneousUsagePerConnection = ConnectionPool.MIN_SIMULTANEOUS_USAGE_PER_CONNECTION; private int maxSimultaneousUsagePerConnection = ConnectionPool.MAX_SIMULTANEOUS_USAGE_PER_CONNECTION; private int maxInProcessPerConnection = Connection.MAX_IN_PROCESS; private int minInProcessPerConnection = Connection.MIN_IN_PROCESS; private int maxWaitForConnection = Connection.MAX_WAIT_FOR_CONNECTION; private int maxWaitForSessionClose = Connection.MAX_WAIT_FOR_SESSION_CLOSE; private int maxContentLength = Connection.MAX_CONTENT_LENGTH; private int reconnectInitialDelay = Connection.RECONNECT_INITIAL_DELAY; private int reconnectInterval = Connection.RECONNECT_INTERVAL; private int resultIterationBatchSize = Connection.RESULT_ITERATION_BATCH_SIZE; private String channelizer = Channelizer.WebSocketChannelizer.class.getName(); private boolean enableSsl = false; private String trustCertChainFile = null; private LoadBalancingStrategy loadBalancingStrategy = new LoadBalancingStrategy.RoundRobin(); private AuthProperties authProps = new AuthProperties(); private Builder() { // empty to prevent direct instantiation } private Builder(final String address) { addContactPoint(address); } /** * Size of the pool for handling request/response operations. Defaults to the number of available processors. */ public Builder nioPoolSize(final int nioPoolSize) { if (nioPoolSize < 1) throw new IllegalArgumentException("The workerPoolSize must be greater than zero"); this.nioPoolSize = nioPoolSize; return this; } /** * Size of the pool for handling background work. Defaults to the number of available processors multiplied * by 2 */ public Builder workerPoolSize(final int workerPoolSize) { if (workerPoolSize < 1) throw new IllegalArgumentException("The workerPoolSize must be greater than zero"); this.workerPoolSize = workerPoolSize; return this; } /** * Set the {@link MessageSerializer} to use given its MIME type. Note that setting this value this way * will not allow specific configuration of the serializer itself. If specific configuration is required * please use {@link #serializer(MessageSerializer)}. */ public Builder serializer(final String mimeType) { serializer = Serializers.valueOf(mimeType).simpleInstance(); return this; } /** * Set the {@link MessageSerializer} to use via the {@link Serializers} enum. If specific configuration is * required please use {@link #serializer(MessageSerializer)}. */ public Builder serializer(final Serializers mimeType) { serializer = mimeType.simpleInstance(); return this; } /** * Sets the {@link MessageSerializer} to use. */ public Builder serializer(final MessageSerializer serializer) { this.serializer = serializer; return this; } /** * Enables connectivity over SSL - note that the server should be configured with SSL turned on for this * setting to work properly. */ public Builder enableSsl(final boolean enable) { this.enableSsl = enable; return this; } /** * File location for a SSL Certificate Chain to use when SSL is enabled. If this value is not provided and * SSL is enabled, the {@link TrustManager} will be established with a self-signed certificate which is NOT * suitable for production purposes. */ public Builder trustCertificateChainFile(final String certificateChainFile) { this.trustCertChainFile = certificateChainFile; return this; } /** * The minimum number of in-flight requests that can occur on a {@link Connection} before it is considered * for closing on return to the {@link ConnectionPool}. */ public Builder minInProcessPerConnection(final int minInProcessPerConnection) { this.minInProcessPerConnection = minInProcessPerConnection; return this; } /** * The maximum number of in-flight requests that can occur on a {@link Connection}. This represents an * indication of how busy a {@link Connection} is allowed to be. This number is linked to the * {@link #maxSimultaneousUsagePerConnection} setting, but is slightly different in that it refers to * the total number of requests on a {@link Connection}. In other words, a {@link Connection} might * be borrowed once to have multiple requests executed against it. This number controls the maximum * number of requests whereas {@link #maxInProcessPerConnection} controls the times borrowed. */ public Builder maxInProcessPerConnection(final int maxInProcessPerConnection) { this.maxInProcessPerConnection = maxInProcessPerConnection; return this; } /** * The maximum number of times that a {@link Connection} can be borrowed from the pool simultaneously. * This represents an indication of how busy a {@link Connection} is allowed to be. Set too large and the * {@link Connection} may queue requests too quickly, rather than wait for an available {@link Connection} * or create a fresh one. If set too small, the {@link Connection} will show as busy very quickly thus * forcing waits for available {@link Connection} instances in the pool when there is more capacity available. */ public Builder maxSimultaneousUsagePerConnection(final int maxSimultaneousUsagePerConnection) { this.maxSimultaneousUsagePerConnection = maxSimultaneousUsagePerConnection; return this; } /** * The minimum number of times that a {@link Connection} should be borrowed from the pool before it falls * under consideration for closing. If a {@link Connection} is not busy and the * {@link #minConnectionPoolSize} is exceeded, then there is no reason to keep that connection open. Set * too large and {@link Connection} that isn't busy will continue to consume resources when it is not being * used. Set too small and {@link Connection} instances will be destroyed when the driver might still be * busy. */ public Builder minSimultaneousUsagePerConnection(final int minSimultaneousUsagePerConnection) { this.minSimultaneousUsagePerConnection = minSimultaneousUsagePerConnection; return this; } /** * The maximum size that the {@link ConnectionPool} can grow. */ public Builder maxConnectionPoolSize(final int maxSize) { this.maxConnectionPoolSize = maxSize; return this; } /** * The minimum size of the {@link ConnectionPool}. When the {@link Client} is started, {@link Connection} * objects will be initially constructed to this size. */ public Builder minConnectionPoolSize(final int minSize) { this.minConnectionPoolSize = minSize; return this; } /** * Override the server setting that determines how many results are returned per batch. */ public Builder resultIterationBatchSize(final int size) { this.resultIterationBatchSize = size; return this; } /** * The maximum amount of time to wait for a connection to be borrowed from the connection pool. */ public Builder maxWaitForConnection(final int maxWait) { this.maxWaitForConnection = maxWait; return this; } /** * If the connection is using a "session" this setting represents the amount of time in milliseconds to wait * for that session to close before timing out where the default value is 3000. Note that the server will * eventually clean up dead sessions itself on expiration of the session or during shutdown. */ public Builder maxWaitForSessionClose(final int maxWait) { this.maxWaitForSessionClose = maxWait; return this; } /** * The maximum size in bytes of any request sent to the server. This number should not exceed the same * setting defined on the server. */ public Builder maxContentLength(final int maxContentLength) { this.maxContentLength = maxContentLength; return this; } /** * Specify the {@link Channelizer} implementation to use on the client when creating a {@link Connection}. */ public Builder channelizer(final String channelizerClass) { this.channelizer = channelizerClass; return this; } /** * Specify the {@link Channelizer} implementation to use on the client when creating a {@link Connection}. */ public Builder channelizer(final Class channelizerClass) { return channelizer(channelizerClass.getCanonicalName()); } /** * Time in milliseconds to wait before attempting to reconnect to a dead host after it has been marked dead. */ public Builder reconnectIntialDelay(final int initialDelay) { this.reconnectInitialDelay = initialDelay; return this; } /** * Time in milliseconds to wait between retries when attempting to reconnect to a dead host. */ public Builder reconnectInterval(final int interval) { this.reconnectInterval = interval; return this; } /** * Specifies the load balancing strategy to use on the client side. */ public Builder loadBalancingStrategy(final LoadBalancingStrategy loadBalancingStrategy) { this.loadBalancingStrategy = loadBalancingStrategy; return this; } /** * Specifies parameters for authentication to Gremlin Server. */ public Builder authProperties(final AuthProperties authProps) { this.authProps = authProps; return this; } /** * Sets the {@link AuthProperties.Property#USERNAME} and {@link AuthProperties.Property#PASSWORD} properties * for authentication to Gremlin Server. */ public Builder credentials(final String username, final String password) { authProps = authProps.with(AuthProperties.Property.USERNAME, username).with(AuthProperties.Property.PASSWORD, password); return this; } /** * Sets the {@link AuthProperties.Property#PROTOCOL} properties for authentication to Gremlin Server. */ public Builder protocol(final String protocol) { this.authProps = authProps.with(AuthProperties.Property.PROTOCOL, protocol); return this; } /** * Sets the {@link AuthProperties.Property#JAAS_ENTRY} properties for authentication to Gremlin Server. */ public Builder jaasEntry(final String jaasEntry) { this.authProps = authProps.with(AuthProperties.Property.JAAS_ENTRY, jaasEntry); return this; } /** * Adds the address of a Gremlin Server to the list of servers a {@link Client} will try to contact to send * requests to. The address should be parseable by {@link InetAddress#getByName(String)}. That's the only * validation performed at this point. No connection to the host is attempted. */ public Builder addContactPoint(final String address) { try { this.addresses.add(InetAddress.getByName(address)); return this; } catch (UnknownHostException e) { throw new IllegalArgumentException(e.getMessage()); } } /** * Add one or more the addresses of a Gremlin Servers to the list of servers a {@link Client} will try to * contact to send requests to. The address should be parseable by {@link InetAddress#getByName(String)}. * That's the only validation performed at this point. No connection to the host is attempted. */ public Builder addContactPoints(final String... addresses) { for (String address : addresses) addContactPoint(address); return this; } /** * Sets the port that the Gremlin Servers will be listening on. */ public Builder port(final int port) { this.port = port; return this; } private List<InetSocketAddress> getContactPoints() { return addresses.stream().map(addy -> new InetSocketAddress(addy, port)).collect(Collectors.toList()); } public Cluster create() { if (addresses.size() == 0) addContactPoint("localhost"); final Settings.ConnectionPoolSettings connectionPoolSettings = new Settings.ConnectionPoolSettings(); connectionPoolSettings.maxInProcessPerConnection = this.maxInProcessPerConnection; connectionPoolSettings.minInProcessPerConnection = this.minInProcessPerConnection; connectionPoolSettings.maxSimultaneousUsagePerConnection = this.maxSimultaneousUsagePerConnection; connectionPoolSettings.minSimultaneousUsagePerConnection = this.minSimultaneousUsagePerConnection; connectionPoolSettings.maxSize = this.maxConnectionPoolSize; connectionPoolSettings.minSize = this.minConnectionPoolSize; connectionPoolSettings.maxWaitForConnection = this.maxWaitForConnection; connectionPoolSettings.maxWaitForSessionClose = this.maxWaitForSessionClose; connectionPoolSettings.maxContentLength = this.maxContentLength; connectionPoolSettings.reconnectInitialDelay = this.reconnectInitialDelay; connectionPoolSettings.reconnectInterval = this.reconnectInterval; connectionPoolSettings.resultIterationBatchSize = this.resultIterationBatchSize; connectionPoolSettings.enableSsl = this.enableSsl; connectionPoolSettings.trustCertChainFile = this.trustCertChainFile; connectionPoolSettings.channelizer = this.channelizer; return new Cluster(getContactPoints(), serializer, this.nioPoolSize, this.workerPoolSize, connectionPoolSettings, loadBalancingStrategy, authProps); } } static class Factory { private final EventLoopGroup group; public Factory(final int nioPoolSize) { final BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("gremlin-driver-loop-%d").build(); group = new NioEventLoopGroup(nioPoolSize, threadFactory); } Bootstrap createBootstrap() { final Bootstrap b = new Bootstrap().group(group); b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); return b; } void shutdown() { group.shutdownGracefully().awaitUninterruptibly(); } } class Manager { private final ConcurrentMap<InetSocketAddress, Host> hosts = new ConcurrentHashMap<>(); private boolean initialized; private final List<InetSocketAddress> contactPoints; private final Factory factory; private final MessageSerializer serializer; private final Settings.ConnectionPoolSettings connectionPoolSettings; private final LoadBalancingStrategy loadBalancingStrategy; private final AuthProperties authProps; private final ScheduledExecutorService executor; private final AtomicReference<CompletableFuture<Void>> closeFuture = new AtomicReference<>(); private Manager(final List<InetSocketAddress> contactPoints, final MessageSerializer serializer, final int nioPoolSize, final int workerPoolSize, final Settings.ConnectionPoolSettings connectionPoolSettings, final LoadBalancingStrategy loadBalancingStrategy, final AuthProperties authProps) { this.loadBalancingStrategy = loadBalancingStrategy; this.authProps = authProps; this.contactPoints = contactPoints; this.connectionPoolSettings = connectionPoolSettings; this.factory = new Factory(nioPoolSize); this.serializer = serializer; this.executor = Executors.newScheduledThreadPool(workerPoolSize, new BasicThreadFactory.Builder().namingPattern("gremlin-driver-worker-%d").build()); } synchronized void init() { if (initialized) return; initialized = true; contactPoints.forEach(address -> { final Host host = add(address); if (host != null) host.makeAvailable(); }); } public Host add(final InetSocketAddress address) { final Host newHost = new Host(address, Cluster.this); final Host previous = hosts.putIfAbsent(address, newHost); return previous == null ? newHost : null; } Collection<Host> allHosts() { return hosts.values(); } synchronized CompletableFuture<Void> close() { // this method is exposed publicly in both blocking and non-blocking forms. if (closeFuture.get() != null) return closeFuture.get(); final CompletableFuture<Void> closeIt = new CompletableFuture<>(); closeFuture.set(closeIt); executor().submit(() -> { factory.shutdown(); closeIt.complete(null); }); // Prevent the executor from accepting new tasks while still allowing enqueued tasks to complete executor.shutdown(); return closeIt; } boolean isClosing() { return closeFuture.get() != null; } @Override public String toString() { return String.join(", ", contactPoints.stream().map(InetSocketAddress::toString).collect(Collectors.<String>toList())); } } }
// ---------------------------------------------------------------------------- // Copyright 2007-2017, GeoTelematic Solutions, Inc. // All rights reserved // ---------------------------------------------------------------------------- // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ---------------------------------------------------------------------------- // Change History: // 2008/05/14 Martin D. Flynn // -Initial release // 2009/05/24 Martin D. Flynn // -Added command-line Reverse-Geocoder test. // 2012/05/27 Martin D. Flynn // -Updated failover support // 2013/08/06 Martin D. Flynn // -Added ability for subclass to specify a failover timeout value. // 2016/01/04 Martin D. Flynn // -Added "failoverQuiet" hint [2.6.1-B03] // ---------------------------------------------------------------------------- package org.opengts.geocoder; import java.util.*; import org.opengts.util.*; import org.opengts.dbtools.*; import org.opengts.db.*; import org.opengts.db.tables.Account; import org.opengts.db.tables.EventData; public abstract class ReverseGeocodeProviderAdapter implements ReverseGeocodeProvider { // ------------------------------------------------------------------------ public static final String PROP_ReverseGeocodeProvider_ = "ReverseGeocodeProvider."; public static final String _PROP_isEnabled = ".isEnabled"; public static final String PROP_alwaysFast[] = new String[] { "alwaysFast", "forceAlwaysFast" }; // Boolean: false public static final String PROP_maxFailoverSeconds[] = new String[] { "maxFailoverSeconds" }; // Long: public static final String PROP_failoverQuiet[] = new String[] { "failoverQuiet" }; // Boolean: // ------------------------------------------------------------------------ public static long DEFAULT_MAX_FAILOVER_SECONDS = DateTime.HourSeconds(1); public static long MIN_FAILOVER_SECONDS = DateTime.MinuteSeconds(10); // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ private String name = null; private TriState isEnabled = TriState.UNKNOWN; private String accessKey = null; private RTProperties properties = null; private int failoverQuiet = -1; // quiet failover hint private ReverseGeocodeProvider rgFailoverRGP = null; private Object rgFailoverLock = new Object(); private long rgFailoverTime = 0L; // Epoch time of failover private long rgFailoverTimeoutSec = 0L; // failover timeout /** *** Constructor *** @param name The name of this reverse-geocode provider *** @param key The access key (may be null) *** @param rtProps The properties (may be null) **/ public ReverseGeocodeProviderAdapter(String name, String key, RTProperties rtProps) { super(); this.setName(name); this.setAuthorization(key); this.setProperties(rtProps); } // ------------------------------------------------------------------------ /** *** Sets the name of this ReverseGeocodeProvider *** @param name The name of this reverse-geocode provider **/ public void setName(String name) { this.name = (name != null)? name : ""; } /** *** Gets the name of this ReverseGeocodeProvider *** @return The name of this reverse-geocode provider **/ public String getName() { return (this.name != null)? this.name : ""; } // ------------------------------------------------------------------------ /** *** Sets the authorization key of this ReverseGeocodeProvider *** @param key The key of this reverse-geocode provider **/ public void setAuthorization(String key) { this.accessKey = key; } /** *** Gets the authorization key of this ReverseGeocodeProvider *** @return The access key of this reverse-geocode provider **/ public String getAuthorization() { return this.accessKey; } /** *** Returns true if the authorization key has been defined *** @return True if the authorization key has been defined, false otherwise. **/ public boolean hasAuthorization() { return !StringTools.isBlank(this.getAuthorization()); } // ------------------------------------------------------------------------ /** *** Sets the failover ReverseGeocodeProvider *** @param rgp The failover ReverseGeocodeProvider **/ public void setFailoverReverseGeocodeProvider(ReverseGeocodeProvider rgp) { this.rgFailoverRGP = rgp; } /** *** Gets the failover ReverseGeocodeProvider *** @return The failover ReverseGeocodeProvider **/ public ReverseGeocodeProvider getFailoverReverseGeocodeProvider() { return this.rgFailoverRGP; } /** *** Gets the failover ReverseGeocodeProvider name *** @return The failover ReverseGeocodeProvider name, or an empty string if *** no failover is defined. **/ public String getFailoverReverseGeocodeProviderName() { return (this.rgFailoverRGP != null)? this.rgFailoverRGP.getName() : ""; } /** *** Has a failover ReverseGeocodeProvider *** @return True if this instance has a failover ReverseGeocodeProvider **/ public boolean hasFailoverReverseGeocodeProvider() { return (this.rgFailoverRGP != null); } // ------------------------------------------------------------------------ /** *** Start failover mode (with default timeout) **/ protected void startReverseGeocodeFailoverMode() { this.startReverseGeocodeFailoverMode(-1L); } /** *** Start failover mode (with specified timeout) *** @param failoverTimeoutSec The explicit failover timeout, or <= 0 for the default timeout. **/ protected void startReverseGeocodeFailoverMode(long failoverTimeoutSec) { synchronized (this.rgFailoverLock) { this.rgFailoverTime = DateTime.getCurrentTimeSec(); this.rgFailoverTimeoutSec = (failoverTimeoutSec > 0L)? failoverTimeoutSec : this.getMaximumFailoverElapsedSec(); } } /** *** Returns true if failover mode is active **/ protected boolean isReverseGeocodeFailoverMode() { if (this.hasFailoverReverseGeocodeProvider()) { boolean rtn; synchronized (this.rgFailoverLock) { if (this.rgFailoverTime <= 0L) { rtn = false; } else { long deltaSec = DateTime.getCurrentTimeSec() - this.rgFailoverTime; long maxFailoverSec = (this.rgFailoverTimeoutSec > 0L)? this.rgFailoverTimeoutSec : this.getMaximumFailoverElapsedSec(); rtn = (deltaSec < maxFailoverSec)? true : false; if (!rtn) { // no longer in failover timeout mode this.rgFailoverTime = 0L; this.rgFailoverTimeoutSec = 0L; } } } return rtn; } else { return false; } } // ------------------------------------------------------------------------ /** *** Sets the failover "quiet" mode hint. **/ public void setFailoverQuiet(boolean quiet) { this.failoverQuiet = quiet? 1 : 0; } /** *** Gets the failover "quiet" mode hint. **/ public boolean getFailoverQuiet() { if (this.failoverQuiet >= 0) { return (this.failoverQuiet != 0)? true : false; } else { RTProperties rtp = this.getProperties(); return rtp.getBoolean(PROP_failoverQuiet, false); } } // ------------------------------------------------------------------------ /** *** Parse and return the user name and password *** @return The username and password (always a 2 element array) **/ protected String[] _getUserPass() { String username = null; String password = null; String key = this.getAuthorization(); if ((key != null) && !key.equals("")) { int p = key.indexOf(":"); if (p >= 0) { username = key.substring(0,p); password = key.substring(p+1); } else { username = key; password = ""; } } else { username = null; password = null; } return new String[] { username, password }; } /** *** Return authorization username. This assumes that the username and password are *** separated by a ':' character *** @return The username **/ protected String getUsername() { return this._getUserPass()[0]; } /** *** Return authorization password. This assumes that the username and password are *** separated by a ':' character *** @return The password **/ protected String getPassword() { return this._getUserPass()[1]; } // ------------------------------------------------------------------------ /** *** Sets the properties for this ReverseGeocodeProvider *** @param rtProps The properties for this reverse-geocode provider **/ public void setProperties(RTProperties rtProps) { this.properties = rtProps; } /** *** Gets the properties for this ReverseGeocodeProvider *** @return The properties for this reverse-geocode provider **/ public RTProperties getProperties() { if (this.properties == null) { this.properties = new RTProperties(); } return this.properties; } // ------------------------------------------------------------------------ /** *** Returns a String representation of this instance *** @return A String representation of this instance **/ public String toString() { StringBuffer sb= new StringBuffer(); sb.append(this.getName()); String auth = this.getAuthorization(); if (!StringTools.isBlank(auth)) { sb.append(" ["); sb.append(auth); sb.append("]"); } return sb.toString(); } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ /** *** Returns true if this ReverseGeocodeProvider is enabled *** @return True if enabled **/ public boolean isEnabled() { if (this.isEnabled.isUnknown()) { String key = PROP_ReverseGeocodeProvider_ + this.getName() + _PROP_isEnabled; if (RTConfig.getBoolean(key,true)) { this.isEnabled = TriState.TRUE; } else { this.isEnabled = TriState.FALSE; Print.logWarn("ReverseGeocodeProvider disabled: " + this.getName()); } } //Print.logInfo("Checking RGP 'isEnabled': " + this.getName() + " ==> " + this.isEnabled.isTrue()); return this.isEnabled.isTrue(); } // ------------------------------------------------------------------------ /* Fast operation? */ public boolean isFastOperation(boolean dft) { RTProperties rtp = this.getProperties(); return rtp.getBoolean(PROP_alwaysFast, dft); } /* Fast operation? */ public boolean isFastOperation() { // -- default to a slow operation return this.isFastOperation(false); } /* Maximum failover elapsed seconds */ public long getMaximumFailoverElapsedSec() { RTProperties rtp = this.getProperties(); long sec = rtp.getLong(PROP_maxFailoverSeconds, DEFAULT_MAX_FAILOVER_SECONDS); return (sec > MIN_FAILOVER_SECONDS)? sec : MIN_FAILOVER_SECONDS; } /* get reverse-geocode */ public abstract ReverseGeocode getReverseGeocode(GeoPoint gp, String localeStr, boolean cache); // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ private static final String ARG_ACCOUNT[] = new String[] { "account" , "acct" }; private static final String ARG_PLN[] = new String[] { "privateLabelName" , "pln" , "pl" }; private static final String ARG_GEOPOINT[] = new String[] { "geoPoint" , "gp" }; private static final String ARG_ADDRESS[] = new String[] { "address" , "addr", "a" }; private static final String ARG_COUNTRY[] = new String[] { "country" , "c" }; private static final String ARG_CACHE[] = new String[] { "cache" , "save" }; private static void usage() { String n = ReverseGeocodeProviderAdapter.class.getName(); Print.sysPrintln(""); Print.sysPrintln("Description:"); Print.sysPrintln(" Reverse-Geocode Testing Tool ..."); Print.sysPrintln(""); Print.sysPrintln("Usage:"); Print.sysPrintln(" java ... " + n + " -geoPoint=<gp> -account=<id>"); Print.sysPrintln(" or"); Print.sysPrintln(" java ... " + n + " -geoPoint=<gp> -pln=<name>"); Print.sysPrintln(""); Print.sysPrintln("Common Options:"); Print.sysPrintln(" -account=<id> Acount ID from which to obtain the ReverseGeocodeProvider"); Print.sysPrintln(" -pln=<name> PrivateLabel name/host"); Print.sysPrintln(" -geoPoint=<gp> GeoPoint in the form <latitude>/<longitude>"); Print.sysPrintln(" -addr=<addr> Address to Geocode"); Print.sysPrintln(""); System.exit(1); } public static void _main() { /* get GeoPoint(s) */ GeoPoint GPA[] = null; if (RTConfig.hasProperty(ARG_GEOPOINT)) { String gpa[] = StringTools.split(RTConfig.getString(ARG_GEOPOINT,""),','); Vector<GeoPoint> gpList = new Vector<GeoPoint>(); for (String gps : gpa) { Print.sysPrintln("Parsing: " + gps); GeoPoint gp = new GeoPoint(gps); if (gp.isValid()) { gpList.add(gp); } } GPA = gpList.toArray(new GeoPoint[gpList.size()]); } if (ListTools.isEmpty(GPA)) { Print.sysPrintln("ERROR: No GeoPoint specified"); usage(); } /* get PrivateLabel */ BasicPrivateLabel privLabel = null; String accountID = RTConfig.getString(ARG_ACCOUNT, ""); if (!StringTools.isBlank(accountID)) { Account acct = null; try { acct = Account.getAccount(accountID); // may throw DBException if (acct == null) { Print.sysPrintln("ERROR: Account-ID does not exist: " + accountID); usage(); } privLabel = acct.getPrivateLabel(); } catch (DBException dbe) { Print.logException("Error loading Account: " + accountID, dbe); //dbe.printException(); System.exit(99); } } else { String pln = RTConfig.getString(ARG_PLN,"default"); if (StringTools.isBlank(pln)) { Print.sysPrintln("ERROR: Must specify '-account=<Account>'"); usage(); } else { privLabel = BasicPrivateLabelLoader.getPrivateLabel(pln); if (privLabel == null) { Print.sysPrintln("ERROR: PrivateLabel name not found: %s", pln); usage(); } } } /* get reverse-geocoder */ ReverseGeocodeProvider rgp = privLabel.getReverseGeocodeProvider(); if (rgp == null) { Print.sysPrintln("ERROR: No ReverseGeocodeProvider for PrivateLabel: %s", privLabel.getName()); System.exit(99); } else if (!rgp.isEnabled()) { Print.sysPrintln("WARNING: ReverseGeocodeProvider disabled: " + rgp.getName()); System.exit(0); } /* get ReverseGeocode */ Print.sysPrintln(""); try { // -- make sure the Domain properties are available to RTConfig privLabel.pushRTProperties(); // stack properties (may be redundant in servlet environment) boolean cache = RTConfig.getBoolean(ARG_CACHE, false); for (GeoPoint gp : GPA) { Print.sysPrintln("------------------------------------------------"); Print.sysPrintln(rgp.getName() + "] ReverseGeocode: " + gp + (cache?" (cache)":"")); long startTimeMS = DateTime.getCurrentTimeMillis(); ReverseGeocode rg = rgp.getReverseGeocode(gp, privLabel.getLocaleString(), cache); // get the reverse-geocode long deltaMS = DateTime.getCurrentTimeMillis() - startTimeMS; if (rg != null) { double kph = rg.getSpeedLimitKPH(); double mph = kph * GeoPoint.MILES_PER_KILOMETER; Print.sysPrintln("Address: " + rg.toString()); Print.sysPrintln("City : " + rg.getCity()); Print.sysPrintln("State : " + rg.getStateProvince()); Print.sysPrintln("Postal : " + rg.getPostalCode()); Print.sysPrintln("Country : " + rg.getCountryCode()); Print.sysPrintln("SpeedLim: " + StringTools.format(kph,"0.0") + " km/h ["+StringTools.format(mph,"0.0")+" mph]"); Print.sysPrintln("Time : " + deltaMS + " ms"); } else { Print.sysPrintln("Unable to reverse-geocode point"); } } Print.sysPrintln("------------------------------------------------"); } catch (Throwable th) { // -- ignore } finally { privLabel.popRTProperties(); // remove from stack } Print.sysPrintln(""); } public static void main(String args[]) { DBConfig.cmdLineInit(args,true); // main if (RTConfig.hasProperty(ARG_ADDRESS)) { GeocodeProviderAdapter._main(); } else { ReverseGeocodeProviderAdapter._main(); } } }
/******************************************************************************* * Copyright 2011, 2012 Chris Banes. * * 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.handmark.pulltorefresh.library; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.ContextMenu.ContextMenuInfo; import android.view.View; import android.widget.FrameLayout; import android.widget.ListAdapter; import android.widget.ListView; import com.handmark.pulltorefresh.library.internal.EmptyViewMethodAccessor; import com.handmark.pulltorefresh.library.internal.LoadingLayout; public class PullToRefreshListView extends PullToRefreshAdapterViewBase<ListView> { private LoadingLayout mHeaderLoadingView; private LoadingLayout mFooterLoadingView; private FrameLayout mLvFooterLoadingFrame; public PullToRefreshListView(Context context) { super(context); setDisableScrollingWhileRefreshing(false); } public PullToRefreshListView(Context context, AttributeSet attrs) { super(context, attrs); setDisableScrollingWhileRefreshing(false); } public PullToRefreshListView(Context context, Mode mode) { super(context, mode); setDisableScrollingWhileRefreshing(false); } @Override public ContextMenuInfo getContextMenuInfo() { return ((InternalListView) getRefreshableView()).getContextMenuInfo(); } public void setPullLabel(String pullLabel, Mode mode) { super.setPullLabel(pullLabel, mode); if (null != mHeaderLoadingView && mode.canPullDown()) { mHeaderLoadingView.setPullLabel(pullLabel); } if (null != mFooterLoadingView && mode.canPullUp()) { mFooterLoadingView.setPullLabel(pullLabel); } } public void setRefreshingLabel(String refreshingLabel, Mode mode) { super.setRefreshingLabel(refreshingLabel, mode); if (null != mHeaderLoadingView && mode.canPullDown()) { mHeaderLoadingView.setRefreshingLabel(refreshingLabel); } if (null != mFooterLoadingView && mode.canPullUp()) { mFooterLoadingView.setRefreshingLabel(refreshingLabel); } } public void setReleaseLabel(String releaseLabel, Mode mode) { super.setReleaseLabel(releaseLabel, mode); if (null != mHeaderLoadingView && mode.canPullDown()) { mHeaderLoadingView.setReleaseLabel(releaseLabel); } if (null != mFooterLoadingView && mode.canPullUp()) { mFooterLoadingView.setReleaseLabel(releaseLabel); } } @Override protected final ListView createRefreshableView(Context context, AttributeSet attrs) { ListView lv = new InternalListView(context, attrs); // Get Styles from attrs TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PullToRefresh); // Create Loading Views ready for use later FrameLayout frame = new FrameLayout(context); mHeaderLoadingView = new LoadingLayout(context, Mode.PULL_DOWN_TO_REFRESH, a); frame.addView(mHeaderLoadingView, FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT); mHeaderLoadingView.setVisibility(View.GONE); lv.addHeaderView(frame, null, false); mLvFooterLoadingFrame = new FrameLayout(context); mFooterLoadingView = new LoadingLayout(context, Mode.PULL_UP_TO_REFRESH, a); mLvFooterLoadingFrame.addView(mFooterLoadingView, FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT); mFooterLoadingView.setVisibility(View.GONE); a.recycle(); // Set it to this so it can be used in ListActivity/ListFragment lv.setId(android.R.id.list); return lv; } protected int getNumberInternalFooterViews() { return null != mFooterLoadingView ? 1 : 0; } protected int getNumberInternalHeaderViews() { return null != mHeaderLoadingView ? 1 : 0; } @Override protected void resetHeader() { // If we're not showing the Refreshing view, or the list is empty, then // the header/footer views won't show so we use the // normal method ListAdapter adapter = mRefreshableView.getAdapter(); if (!getShowViewWhileRefreshing() || null == adapter || adapter.isEmpty()) { super.resetHeader(); return; } LoadingLayout originalLoadingLayout; LoadingLayout listViewLoadingLayout; int scrollToHeight = getHeaderHeight(); int selection; boolean scroll; switch (getCurrentMode()) { case PULL_UP_TO_REFRESH: originalLoadingLayout = getFooterLayout(); listViewLoadingLayout = mFooterLoadingView; selection = mRefreshableView.getCount() - 1; scroll = mRefreshableView.getLastVisiblePosition() == selection; break; case PULL_DOWN_TO_REFRESH: default: originalLoadingLayout = getHeaderLayout(); listViewLoadingLayout = mHeaderLoadingView; scrollToHeight *= -1; selection = 0; scroll = mRefreshableView.getFirstVisiblePosition() == selection; break; } // Set our Original View to Visible originalLoadingLayout.setVisibility(View.VISIBLE); /** * Scroll so the View is at the same Y as the ListView header/footer, * but only scroll if we've pulled to refresh and it's positioned * correctly */ if (scroll && getState() != MANUAL_REFRESHING) { mRefreshableView.setSelection(selection); setHeaderScroll(scrollToHeight); } // Hide the ListView Header/Footer listViewLoadingLayout.setVisibility(View.GONE); super.resetHeader(); } @Override protected void setRefreshingInternal(boolean doScroll) { // If we're not showing the Refreshing view, or the list is empty, then // the header/footer views won't show so we use the // normal method ListAdapter adapter = mRefreshableView.getAdapter(); if (!getShowViewWhileRefreshing() || null == adapter || adapter.isEmpty()) { super.setRefreshingInternal(doScroll); return; } super.setRefreshingInternal(false); final LoadingLayout originalLoadingLayout, listViewLoadingLayout; final int selection, scrollToY; switch (getCurrentMode()) { case PULL_UP_TO_REFRESH: originalLoadingLayout = getFooterLayout(); listViewLoadingLayout = mFooterLoadingView; selection = mRefreshableView.getCount() - 1; scrollToY = getScrollY() - getHeaderHeight(); break; case PULL_DOWN_TO_REFRESH: default: originalLoadingLayout = getHeaderLayout(); listViewLoadingLayout = mHeaderLoadingView; selection = 0; scrollToY = getScrollY() + getHeaderHeight(); break; } if (doScroll) { // We scroll slightly so that the ListView's header/footer is at the // same Y position as our normal header/footer setHeaderScroll(scrollToY); } // Hide our original Loading View originalLoadingLayout.setVisibility(View.INVISIBLE); // Show the ListView Loading View and set it to refresh listViewLoadingLayout.setVisibility(View.VISIBLE); listViewLoadingLayout.refreshing(); if (doScroll) { // Make sure the ListView is scrolled to show the loading // header/footer mRefreshableView.setSelection(selection); // Smooth scroll as normal smoothScrollTo(0); } } class InternalListView extends ListView implements EmptyViewMethodAccessor { private boolean mAddedLvFooter = false; public InternalListView(Context context, AttributeSet attrs) { super(context, attrs); } @Override public void draw(Canvas canvas) { /** * This is a bit hacky, but ListView has got a bug in it when using * Header/Footer Views and the list is empty. This masks the issue * so that it doesn't cause an FC. See Issue #66. */ try { super.draw(canvas); } catch (Exception e) { e.printStackTrace(); } } public ContextMenuInfo getContextMenuInfo() { return super.getContextMenuInfo(); } @Override public void setAdapter(ListAdapter adapter) { // Add the Footer View at the last possible moment if (!mAddedLvFooter) { addFooterView(mLvFooterLoadingFrame, null, false); mAddedLvFooter = true; } super.setAdapter(adapter); } @Override public void setEmptyView(View emptyView) { PullToRefreshListView.this.setEmptyView(emptyView); } @Override public void setEmptyViewInternal(View emptyView) { super.setEmptyView(emptyView); } } public LoadingLayout getHeaderLoadingView() { return mHeaderLoadingView; } public LoadingLayout getFooterLoadingView() { return mFooterLoadingView; } }
package org.craft.client.gui; import static org.lwjgl.opengl.GL11.*; import java.io.*; import org.craft.client.*; import org.craft.client.gui.widgets.*; import org.craft.client.render.*; import org.craft.client.render.texture.*; import org.craft.maths.*; import org.craft.modding.events.gui.*; import org.craft.resources.*; public abstract class Gui extends GuiPanel { public static ResourceLocation widgetsTexture = new ResourceLocation("ourcraft", "textures/gui/widgets.png"); private static OpenGLBuffer buffer; private static Texture backgroundTexture; private GuiPopupMenu popupMenu; public Gui(OurCraft game) { super(0, 0, game.getDisplayWidth(), game.getDisplayHeight(), game, game.getFontRenderer()); popupMenu = new GuiPopupMenu(this); popupMenu.visible = false; forceDrawAll = true; if(backgroundTexture == null) { try { backgroundTexture = OpenGLHelper.loadTexture(oc.getAssetsLoader().getResource(new ResourceLocation("ourcraft", "textures/gui/background.png"))); } catch(IOException e) { e.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } } } private static Vector3 bottomLeftCornerPos = Vector3.get(0, 0, 0); private static Vector3 bottomRightCornerPos = Vector3.get(0, 0, 0); private static Vector3 topLeftCornerPos = Vector3.get(0, 0, 0); private static Vector3 topRightCornerPos = Vector3.get(0, 0, 0); private static Vector2 bottomLeftCornerUV = Vector2.get(0, 0); private static Vector2 bottomRightCornerUV = Vector2.get(0, 0); private static Vector2 topLeftCornerUV = Vector2.get(0, 0); private static Vector2 topRightCornerUV = Vector2.get(0, 0); private static Quaternion bottomLeftCornerColor = Quaternion.get(1, 1, 1, 1); private static Quaternion bottomRightCornerColor = Quaternion.get(1, 1, 1, 1); private static Quaternion topLeftCornerColor = Quaternion.get(1, 1, 1, 1); private static Quaternion topRightCornerColor = Quaternion.get(1, 1, 1, 1); /** * Draws textured rect at given coordinates */ public static void drawTexturedRect(RenderEngine engine, int x, int y, int w, int h, float minU, float minV, float maxU, float maxV) { bottomLeftCornerColor.set(1, 1, 1, 1); bottomRightCornerColor.set(1, 1, 1, 1); topLeftCornerColor.set(1, 1, 1, 1); topRightCornerColor.set(1, 1, 1, 1); drawRect(engine, x, y, w, h, minU, minV, maxU, maxV); } private static void drawRect(RenderEngine engine, int x, int y, int w, int h, float minU, float minV, float maxU, float maxV) { initBufferIfNeeded(); bottomLeftCornerPos.set(x, y, 0); bottomRightCornerPos.set(x + w, y, 0); topLeftCornerPos.set(x + w, y + h, 0); topRightCornerPos.set(x, y + h, 0); bottomLeftCornerUV.set(minU, minV); bottomRightCornerUV.set(maxU, minV); topLeftCornerUV.set(maxU, maxV); topRightCornerUV.set(minU, maxV); buffer.upload(); engine.renderBuffer(buffer); } public static void drawBezierCurve(RenderEngine engine, int color, int segments, float lineWidth, Vector2... points) { double[] x = new double[points.length]; double[] y = new double[points.length]; double[] z = new double[points.length]; for(int i = 0; i < x.length; i++ ) { Vector2 point = points[i]; x[i] = point.getX(); y[i] = point.getY(); z[i] = 0; } CasteljauAlgorithm algo = new CasteljauAlgorithm(x, y, z, x.length); double step = 1.0 / segments; Vector2 previous = null; for(double t = 0; t <= 1.0; t += step) { double[] values = algo.getXYZvalues(t); Vector2 current = Vector2.get((float) values[0], (float) values[1]); if(previous != null) { drawColoredLine(engine, (int) current.getX(), (int) current.getY(), (int) previous.getX(), (int) previous.getY(), color, lineWidth); // previous.dispose(); } previous = current; } } /** * Returns true if the updating of the game should be paused when this gui is opened ( */ public boolean pausesGame() { return false; } @Override public void pack() { ; } /** * Returns true if mouse needs to be ungrabbed */ public abstract boolean requiresMouse(); /** * Creates this gui (adds buttons'n'stuff) */ public abstract void init(); /** * Draws default background on screen */ public void drawBackground(int mx, int my, RenderEngine renderEngine) { renderEngine.bindTexture(backgroundTexture, 0); drawTexturedRect(renderEngine, 0, 0, oc.getDisplayWidth(), oc.getDisplayHeight(), 0, 0, (float) oc.getDisplayWidth() / (float) backgroundTexture.getWidth(), (float) oc.getDisplayHeight() / (float) backgroundTexture.getHeight()); } /** * Clears widget list */ public void build() { widgets.clear(); setWidth(oc.getDisplayWidth()); setHeight(oc.getDisplayHeight()); if(!OurCraft.getOurCraft().getEventBus().fireEvent(new GuiBuildingEvent.Pre(OurCraft.getOurCraft(), this))) { init(); popupMenu.clear(); if(!OurCraft.getOurCraft().getEventBus().fireEvent(new GuiBuildingEvent.PopupMenu.Pre(OurCraft.getOurCraft(), this, popupMenu))) { buildMenu(popupMenu); OurCraft.getOurCraft().getEventBus().fireEvent(new GuiBuildingEvent.PopupMenu.Post(OurCraft.getOurCraft(), this, popupMenu)); } OurCraft.getOurCraft().getEventBus().fireEvent(new GuiBuildingEvent.Post(OurCraft.getOurCraft(), this)); } } public GuiPopupMenu getPopupMenu() { return popupMenu; } public static void drawColoredLine(RenderEngine engine, int x, int y, int x2, int y2, int color, float lineWidth) { engine.bindTexture(Texture.empty); float a = (float) (color >> 24 & 0xFF) / 255f; float r = (float) (color >> 16 & 0xFF) / 255f; float g = (float) (color >> 8 & 0xFF) / 255f; float b = (float) (color & 0xFF) / 255f; bottomLeftCornerColor.set(r, g, b, a); bottomRightCornerColor.set(r, g, b, a); topLeftCornerColor.set(r, g, b, a); topRightCornerColor.set(r, g, b, a); drawLine(engine, x, y, x2, y2, 0, 0, 1, 1, lineWidth); engine.bindLocation(widgetsTexture); } private static void initBufferIfNeeded() { bottomLeftCornerPos.setDisposable(false); bottomLeftCornerUV.setDisposable(false); bottomRightCornerPos.setDisposable(false); bottomRightCornerUV.setDisposable(false); topLeftCornerPos.setDisposable(false); topLeftCornerUV.setDisposable(false); topRightCornerPos.setDisposable(false); topRightCornerUV.setDisposable(false); if(buffer == null) { buffer = new OpenGLBuffer(); Vertex a = Vertex.get(bottomLeftCornerPos, bottomLeftCornerUV, bottomLeftCornerColor); a.setDisposable(false); buffer.addVertex(a); Vertex b = Vertex.get(bottomRightCornerPos, bottomRightCornerUV, bottomRightCornerColor); b.setDisposable(false); buffer.addVertex(b); Vertex c = Vertex.get(topLeftCornerPos, topLeftCornerUV, topLeftCornerColor); c.setDisposable(false); buffer.addVertex(c); Vertex d = Vertex.get(topRightCornerPos, topRightCornerUV, topRightCornerColor); d.setDisposable(false); buffer.addVertex(d); buffer.addIndex(0); buffer.addIndex(1); buffer.addIndex(2); buffer.addIndex(2); buffer.addIndex(3); buffer.addIndex(0); } } public static void drawLine(RenderEngine engine, int x, int y, int x2, int y2, float minU, float minV, float maxU, float maxV, float lineWidth) { initBufferIfNeeded(); bottomLeftCornerPos.set(x, y, 0); bottomRightCornerPos.set(x2, y2, 0); topLeftCornerPos.set(x2, y2, 0); topRightCornerPos.set(x2, y2, 0); bottomLeftCornerUV.set(minU, minV); bottomRightCornerUV.set(maxU, minV); topLeftCornerUV.set(maxU, maxV); topRightCornerUV.set(minU, maxV); buffer.upload(); glLineWidth(lineWidth); engine.renderBuffer(buffer, GL_LINES); glLineWidth(1); } public static void drawColoredRect(RenderEngine engine, int x, int y, int w, int h, int color) { engine.bindTexture(Texture.empty); float a = (float) (color >> 24 & 0xFF) / 255f; float r = (float) (color >> 16 & 0xFF) / 255f; float g = (float) (color >> 8 & 0xFF) / 255f; float b = (float) (color & 0xFF) / 255f; bottomLeftCornerColor.set(r, g, b, a); bottomRightCornerColor.set(r, g, b, a); topLeftCornerColor.set(r, g, b, a); topRightCornerColor.set(r, g, b, a); drawRect(engine, x, y, w, h, 0, 0, 1, 1); engine.bindLocation(widgetsTexture); } public void buildMenu(GuiPopupMenu popupMenu) { } @Override public boolean onButtonReleased(int x, int y, int button) { boolean result = super.onButtonReleased(x, y, button); if(!result && button == 1) { showPopupMenu(x, y); return true; } else if(popupMenu.visible) { if(!popupMenu.onButtonReleased(x, y, button)) { hidePopupMenu(); } } return result; } private void hidePopupMenu() { popupMenu.visible = false; } private void showPopupMenu(int x, int y) { popupMenu.visible = true; popupMenu.pack(); popupMenu.setLocation(x, y); } @Override public void render(int mx, int my, RenderEngine engine) { super.render(mx, my, engine); if(popupMenu.visible) popupMenu.render(mx, my, engine); } @Override public boolean keyPressed(int id, char c) { boolean result = super.keyPressed(id, c); if(!result && popupMenu.visible) { return popupMenu.keyPressed(id, c); } return result; } @Override public boolean keyReleased(int id, char c) { boolean result = super.keyReleased(id, c); if(!result && popupMenu.visible) { return popupMenu.keyReleased(id, c); } return result; } @Override public boolean onButtonPressed(int x, int y, int button) { boolean result = super.onButtonPressed(x, y, button); if(!result && popupMenu.visible) { return popupMenu.onButtonPressed(x, y, button); } return result; } @Override public boolean handleMouseMovement(int mx, int my, int dx, int dy) { boolean result = super.handleMouseMovement(mx, my, dx, dy); if(!result && popupMenu.visible) { return popupMenu.handleMouseMovement(mx, my, dx, dy); } return result; } @Override public boolean handleMouseWheelMovement(int mx, int my, int deltaWheel) { boolean result = super.handleMouseWheelMovement(mx, my, deltaWheel); if(!result && popupMenu.visible) { return popupMenu.handleMouseWheelMovement(mx, my, deltaWheel); } return result; } @Override public void update() { popupMenu.update(); super.update(); } public void onPopupMenuClicked(GuiPopupElement clicked) { hidePopupMenu(); } }
/** * 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 */ package nl.gridline.zieook.workflow; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantReadWriteLock; import nl.gridline.zieook.mapreduce.TaskConfig; import nl.gridline.zieook.tasks.ZieOokTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; /** * [purpose] * <p /> * Project zieook-backend-workflow<br /> * RunningTasksCollection.java created 24 nov. 2011 * <p /> * Copyright, all rights reserved 2011 GridLine Amsterdam * @author <a href="mailto:job@gridline.nl">Job</a> * @version $Revision:$, $Date:$ */ public class ZieOokTaskExecutor { private final ThreadPoolExecutor executor; private final List<TaskRunner> delegate; private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private final ReentrantReadWriteLock.ReadLock readLock = lock.readLock(); private final ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock(); private final int size; public ZieOokTaskExecutor(int size) { this.size = size; delegate = new ArrayList<TaskRunner>(size); executor = new ThreadPoolExecutor(size, size, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); } public boolean canExecuteNow() { return executor.getActiveCount() < size; } /** * get the maximum size of tasks executing * @return */ public int getSize() { return size; } /** * return the approximate count of executing tasks * @return the number of threads * @see ThreadPoolExecutor#getActiveCount() */ public int getActiveCount() { return executor.getActiveCount(); } /** * shutdown the threadpool */ public void shutdown() { executor.shutdown(); } /** * execute a task * @param runnable */ public void executeTask(ZieOokTask task) { writeLock.lock(); try { TaskRunner runnable = new TaskRunner(task); delegate.add(runnable); executor.execute(runnable); } finally { writeLock.unlock(); } } public boolean deleteTask(long id) { writeLock.lock(); try { TaskRunner task = findTask(id); return delegate.remove(task); } finally { writeLock.unlock(); } } public boolean removeTask(long id) { boolean result = false; writeLock.lock(); try { Iterator<TaskRunner> i = delegate.iterator(); while (i.hasNext()) { final TaskRunner r = i.next(); if (r.getId() == id) { i.remove(); result = r.getConfig().isCancelled() || r.getConfig().isSucceeded() || r.getConfig().isFailed(); break; } } } finally { writeLock.unlock(); } return result; } public boolean cancelTask(long id) { readLock.lock(); try { TaskRunner task = findTask(id); task.getConfig().setCancelled(); return task.getConfig().isCancelled(); } finally { readLock.unlock(); } } public boolean killTask(long id) throws IOException { readLock.lock(); try { TaskRunner task = findTask(id); // throw interrupt: task.stop(); // this should cancel the task, soon... return task.getConfig().isCancelled(); } finally { readLock.unlock(); } } public List<TaskRunner> findTask(String cp) { Preconditions.checkNotNull(cp, "you need to provide a content provider"); List<TaskRunner> result = new ArrayList<TaskRunner>(size); readLock.lock(); try { for (TaskRunner r : delegate) { if (cp.equals(r.getConfig().get(TaskConfig.CP))) { result.add(r); } } } finally { readLock.unlock(); } return result; } public TaskRunner findTask(long id) { readLock.lock(); try { for (TaskRunner r : delegate) { if (r.getId() == id) { return r; } } } finally { readLock.unlock(); } return null; } public List<TaskConfig> getTasks() { List<TaskConfig> result = new ArrayList<TaskConfig>(size); readLock.lock(); try { for (TaskRunner r : delegate) { result.add(r.getConfig()); } } finally { readLock.unlock(); } return result; } /** * Wraps a ZieOok task in a runnable and catches all exception, if thrown: set task to failed */ public static class TaskRunner implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(ZieOokTaskExecutor.TaskRunner.class); private final ZieOokTask task; public TaskRunner(ZieOokTask task) { this.task = task; } @Override public void run() { LOG.debug("TASK START for <{},{}>", task.getConfig().get(TaskConfig.TASK_TYPE), task.getConfig().getId()); try { task.call(); LOG.debug("TASK SUCCEED for: <{},{}>", task.getConfig().get(TaskConfig.TASK_TYPE), task.getConfig().getId()); } catch (Exception e) { String msg = task.getConfig().get(TaskConfig.TASK_MESSAGE); task.getConfig().setProperty( TaskConfig.TASK_MESSAGE, "task execution failed with error, task message: \"" + msg + "\" error message: \"" + e.getMessage() + "\""); task.getConfig().setFailed(); LOG.error("TASK FAILED for <" + task.getConfig().get(TaskConfig.TASK_TYPE) + "," + task.getConfig().getId() + ">", e); } } public long getId() { return task.getConfig().getId(); } public void stop() throws IOException { LOG.debug("Killing hadoop Job: {} in thread", task.getId(), Thread.currentThread().getName()); task.getCurrentJob().killJob(); LOG.debug("Interrupting task {} in thread", task.getId(), Thread.currentThread().getName()); Thread.currentThread().interrupt(); } public TaskConfig getConfig() { return task.getConfig(); } public ZieOokTask getTask() { return task; } } /** * @return */ public int getCorePoolSize() { // TODO Auto-generated method stub return 0; } /** * @return */ public long getCompletedTaskCount() { // TODO Auto-generated method stub return 0; } }
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * User: anna * Date: 11-Nov-2008 */ package org.jetbrains.idea.eclipse.conversion; import com.intellij.openapi.components.ExpandMacroToPathMap; import com.intellij.openapi.components.PathMacroManager; import com.intellij.openapi.components.impl.BasePathMacroManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.ProjectJdkTable; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.projectRoots.ex.JavaSdkUtil; import com.intellij.openapi.roots.*; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.roots.libraries.LibraryTable; import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.util.ArrayUtil; import com.intellij.util.containers.hash.HashSet; import gnu.trove.THashSet; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.idea.eclipse.*; import org.jetbrains.idea.eclipse.config.EclipseModuleManagerImpl; import org.jetbrains.idea.eclipse.importWizard.EclipseNatureImporter; import org.jetbrains.idea.eclipse.util.ErrorLog; import java.io.IOException; import java.util.Collection; import java.util.List; import java.util.Set; public class EclipseClasspathReader extends AbstractEclipseClasspathReader<ModifiableRootModel> { private final Project myProject; private ContentEntry myContentEntry; public EclipseClasspathReader(@NotNull String rootPath, @NotNull Project project, @Nullable List<String> currentRoots) { this(rootPath, project, currentRoots, null); } public EclipseClasspathReader(@NotNull String rootPath, @NotNull Project project, @Nullable List<String> currentRoots, @Nullable Set<String> moduleNames) { super(rootPath, currentRoots, moduleNames); myProject = project; } public void init(@NotNull ModifiableRootModel model) { myContentEntry = model.addContentEntry(pathToUrl(myRootPath)); } public static void collectVariables(Set<String> usedVariables, Element classpathElement, final String rootPath) { for (Element element : classpathElement.getChildren(EclipseXml.CLASSPATHENTRY_TAG)) { String path = element.getAttributeValue(EclipseXml.PATH_ATTR); if (path == null) { continue; } String kind = element.getAttributeValue(EclipseXml.KIND_ATTR); if (Comparing.strEqual(kind, EclipseXml.VAR_KIND)) { createEPathVariable(path, 0); String srcPath = element.getAttributeValue(EclipseXml.SOURCEPATH_ATTR); if (srcPath != null) { createEPathVariable(srcPath, srcVarStart(srcPath)); } } else if (Comparing.strEqual(kind, EclipseXml.SRC_KIND) || Comparing.strEqual(kind, EclipseXml.OUTPUT_KIND)) { EclipseProjectFinder.LinkedResource linkedResource = EclipseProjectFinder.findLinkedResource(rootPath, path); if (linkedResource != null && linkedResource.containsPathVariable()) { usedVariables.add(linkedResource.getVariableName()); } } } } public void readClasspath(@NotNull ModifiableRootModel model, @NotNull Element classpathElement) throws IOException, ConversionException { Set<String> sink = new THashSet<String>(); readClasspath(model, sink, sink, sink, null, classpathElement); } public void readClasspath(@NotNull ModifiableRootModel model, @NotNull Collection<String> unknownLibraries, @NotNull Collection<String> unknownJdks, Set<String> refsToModules, final String testPattern, Element classpathElement) throws IOException, ConversionException { for (OrderEntry orderEntry : model.getOrderEntries()) { if (!(orderEntry instanceof ModuleSourceOrderEntry)) { model.removeOrderEntry(orderEntry); } } int idx = 0; EclipseModuleManagerImpl eclipseModuleManager = EclipseModuleManagerImpl.getInstance(model.getModule()); Set<String> libs = new HashSet<String>(); for (Element o : classpathElement.getChildren(EclipseXml.CLASSPATHENTRY_TAG)) { try { readClasspathEntry(model, unknownLibraries, unknownJdks, refsToModules, testPattern, o, idx++, eclipseModuleManager, ((BasePathMacroManager)PathMacroManager.getInstance(model.getModule())).getExpandMacroMap(), libs); } catch (ConversionException e) { ErrorLog.rethrow(ErrorLog.Level.Warning, null, EclipseXml.CLASSPATH_FILE, e); } } if (!model.isSdkInherited() && model.getSdkName() == null) { eclipseModuleManager.setForceConfigureJDK(); model.inheritSdk(); } } @Override protected int rearrange(ModifiableRootModel rootModel) { return rearrangeOrderEntryOfType(rootModel, ModuleSourceOrderEntry.class); } @Override protected String expandEclipsePath2Url(ModifiableRootModel rootModel, String path) { final VirtualFile contentRoot = myContentEntry.getFile(); if (contentRoot != null) { return EPathUtil.expandEclipsePath2Url(path, rootModel, myCurrentRoots, contentRoot); } return EPathUtil.expandEclipsePath2Url(path, rootModel, myCurrentRoots); } @Override protected Set<String> getDefinedCons() { return EclipseNatureImporter.getAllDefinedCons(); } @Override protected void addModuleLibrary(ModifiableRootModel rootModel, Element element, boolean exported, String libName, String url, String srcUrl, String nativeRoot, ExpandMacroToPathMap macroMap) { final Library library = rootModel.getModuleLibraryTable().getModifiableModel().createLibrary(libName); final Library.ModifiableModel modifiableModel = library.getModifiableModel(); modifiableModel.addRoot(url, OrderRootType.CLASSES); if (srcUrl != null) { modifiableModel.addRoot(srcUrl, OrderRootType.SOURCES); } if (nativeRoot != null) { modifiableModel.addRoot(nativeRoot, NativeLibraryOrderRootType.getInstance()); } EJavadocUtil.appendJavadocRoots(element, rootModel, myCurrentRoots, modifiableModel); modifiableModel.commit(); setLibraryEntryExported(rootModel, exported, library); } @Override protected void addJUnitDefaultLib(ModifiableRootModel rootModel, String junitName, ExpandMacroToPathMap macroMap) { final Library library = rootModel.getModuleLibraryTable().getModifiableModel().createLibrary(junitName); final Library.ModifiableModel modifiableModel = library.getModifiableModel(); modifiableModel.addRoot(getJunitClsUrl(junitName.contains("4")), OrderRootType.CLASSES); modifiableModel.commit(); } @Override protected void addSourceFolderToCurrentContentRoot(ModifiableRootModel rootModel, String srcUrl, boolean testFolder) { myContentEntry.addSourceFolder(srcUrl, testFolder); } @Override protected void addSourceFolder(ModifiableRootModel rootModel, String srcUrl, boolean testFolder) { rootModel.addContentEntry(srcUrl).addSourceFolder(srcUrl, testFolder); } @Override protected void setUpModuleJdk(ModifiableRootModel rootModel, Collection<String> unknownJdks, EclipseModuleManager eclipseModuleManager, String jdkName) { if (jdkName == null) { rootModel.inheritSdk(); } else { final Sdk moduleJdk = ProjectJdkTable.getInstance().findJdk(jdkName); if (moduleJdk != null) { rootModel.setSdk(moduleJdk); } else { rootModel.setInvalidSdk(jdkName, IdeaXml.JAVA_SDK_TYPE); eclipseModuleManager.setInvalidJdk(jdkName); unknownJdks.add(jdkName); } } rearrangeOrderEntryOfType(rootModel, JdkOrderEntry.class); } @Override protected void addInvalidModuleEntry(ModifiableRootModel rootModel, boolean exported, String moduleName) { rootModel.addInvalidModuleEntry(moduleName).setExported(exported); } private static int rearrangeOrderEntryOfType(ModifiableRootModel rootModel, Class<? extends OrderEntry> orderEntryClass) { OrderEntry[] orderEntries = rootModel.getOrderEntries(); int moduleSourcesIdx = 0; for (OrderEntry orderEntry : orderEntries) { if (orderEntryClass.isAssignableFrom(orderEntry.getClass())) { break; } moduleSourcesIdx++; } orderEntries = ArrayUtil.append(orderEntries, orderEntries[moduleSourcesIdx]); orderEntries = ArrayUtil.remove(orderEntries, moduleSourcesIdx); rootModel.rearrangeOrderEntries(orderEntries); return orderEntries.length - 1; } @Override public void setupOutput(ModifiableRootModel rootModel, final String path) { setOutputUrl(rootModel, path); } public static void setOutputUrl(@NotNull ModifiableRootModel rootModel, @NotNull String path) { CompilerModuleExtension compilerModuleExtension = rootModel.getModuleExtension(CompilerModuleExtension.class); compilerModuleExtension.setCompilerOutputPath(pathToUrl(path)); compilerModuleExtension.inheritCompilerOutputPath(false); } private static void setLibraryEntryExported(ModifiableRootModel rootModel, boolean exported, Library library) { for (OrderEntry orderEntry : rootModel.getOrderEntries()) { if (orderEntry instanceof LibraryOrderEntry && ((LibraryOrderEntry)orderEntry).isModuleLevel() && Comparing.equal(((LibraryOrderEntry)orderEntry).getLibrary(), library)) { ((LibraryOrderEntry)orderEntry).setExported(exported); break; } } } @Override protected void addNamedLibrary(final ModifiableRootModel rootModel, final Collection<String> unknownLibraries, final boolean exported, final String name, final boolean applicationLevel) { Library lib = findLibraryByName(myProject, name); if (lib != null) { rootModel.addLibraryEntry(lib).setExported(exported); } else { unknownLibraries.add(name); rootModel.addInvalidLibrary(name, applicationLevel ? LibraryTablesRegistrar.APPLICATION_LEVEL : LibraryTablesRegistrar.PROJECT_LEVEL).setExported(exported); } } public static Library findLibraryByName(Project project, String name) { final LibraryTablesRegistrar tablesRegistrar = LibraryTablesRegistrar.getInstance(); Library lib = tablesRegistrar.getLibraryTable().getLibraryByName(name); if (lib == null) { lib = tablesRegistrar.getLibraryTable(project).getLibraryByName(name); } if (lib == null) { for (LibraryTable table : tablesRegistrar.getCustomLibraryTables()) { lib = table.getLibraryByName(name); if (lib != null) { break; } } } return lib; } static String getJunitClsUrl(final boolean version4) { String url = version4 ? JavaSdkUtil.getJunit4JarPath() : JavaSdkUtil.getJunit3JarPath(); final VirtualFile localFile = VirtualFileManager.getInstance().findFileByUrl(pathToUrl(url)); if (localFile != null) { final VirtualFile jarFile = JarFileSystem.getInstance().getJarRootForLocalFile(localFile); url = jarFile != null ? jarFile.getUrl() : localFile.getUrl(); } return url; } protected String prepareValidUrlInsideJar(String url) { final VirtualFile localFile = VirtualFileManager.getInstance().findFileByUrl(url); if (localFile != null) { final VirtualFile jarFile = JarFileSystem.getInstance().getJarRootForLocalFile(localFile); if (jarFile != null) { return jarFile.getUrl(); } } return url; } }
/* * Copyright (C) 2015 Daniel Nilsson * * 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. * * * * Change Log: * * 1.1 * - Fixed buggy measure and layout code. You can now make the view any size you want. * - Optimization of the drawing using a bitmap cache, a lot faster! * - Support for hardware acceleration for all but the problematic * part of the view will still be software rendered but much faster! * See comment in drawSatValPanel() for more info. * - Support for declaring some variables in xml. * * 1.2 - 2015-05-08 * - More bugs in onMeasure() have been fixed, should handle all cases properly now. * - View automatically saves its state now. * - Automatic border color depending on current theme. * - Code cleanup, trackball support removed since they do not exist anymore. * * 1.3 - 2015-05-10 * - Fixed hue bar selection did not align with what was shown in the sat/val panel. * Fixed by replacing the linear gardient used before. Now drawing individual lines * of different colors. This was expensive so we now use a bitmap cache for the hue * panel too. * - Replaced all RectF used in the layout process with Rect since the * floating point values was causing layout issues (perfect alignment). */ package com.github.danielnilsson9.colorpickerview.view; import com.github.danielnilsson9.colorpickerview.R; import com.github.danielnilsson9.colorpickerview.drawable.AlphaPatternDrawable; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ComposeShader; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.Point; import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.Shader.TileMode; import android.os.Bundle; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; /** * Displays a color picker to the user and allow them * to select a color. A slider for the alpha channel is * also available. Enable it by setting * setAlphaSliderVisible(boolean) to true. * @author Daniel Nilsson */ public class ColorPickerView extends View{ public interface OnColorChangedListener{ public void onColorChanged(int newColor); } private final static int DEFAULT_BORDER_COLOR = 0xFF6E6E6E; private final static int DEFAULT_SLIDER_COLOR = 0xFFBDBDBD; private final static int HUE_PANEL_WDITH_DP = 30; private final static int ALPHA_PANEL_HEIGH_DP = 20; private final static int PANEL_SPACING_DP = 10; private final static int CIRCLE_TRACKER_RADIUS_DP = 5; private final static int SLIDER_TRACKER_SIZE_DP = 4; private final static int SLIDER_TRACKER_OFFSET_DP = 2; /** * The width in pixels of the border * surrounding all color panels. */ private final static int BORDER_WIDTH_PX = 1; /** * The width in px of the hue panel. */ private int mHuePanelWidthPx; /** * The height in px of the alpha panel */ private int mAlphaPanelHeightPx; /** * The distance in px between the different * color panels. */ private int mPanelSpacingPx; /** * The radius in px of the color palette tracker circle. */ private int mCircleTrackerRadiusPx; /** * The px which the tracker of the hue or alpha panel * will extend outside of its bounds. */ private int mSliderTrackerOffsetPx; /** * Height of slider tracker on hue panel, * width of slider on alpha panel. */ private int mSliderTrackerSizePx; private Paint mSatValPaint; private Paint mSatValTrackerPaint; private Paint mAlphaPaint; private Paint mAlphaTextPaint; private Paint mHueAlphaTrackerPaint; private Paint mBorderPaint; private Shader mValShader; private Shader mSatShader; private Shader mAlphaShader; /* * We cache a bitmap of the sat/val panel which is expensive to draw each time. * We can reuse it when the user is sliding the circle picker as long as the hue isn't changed. */ private BitmapCache mSatValBackgroundCache; /* We cache the hue background to since its also very expensive now. */ private BitmapCache mHueBackgroundCache; /* Current values */ private int mAlpha = 0xff; private float mHue = 360f; private float mSat = 0f; private float mVal = 0f; private boolean mShowAlphaPanel = false; private String mAlphaSliderText = null; private int mSliderTrackerColor = DEFAULT_SLIDER_COLOR; private int mBorderColor = DEFAULT_BORDER_COLOR; /** * Minimum required padding. The offset from the * edge we must have or else the finger tracker will * get clipped when it's drawn outside of the view. */ private int mRequiredPadding; /** * The Rect in which we are allowed to draw. * Trackers can extend outside slightly, * due to the required padding we have set. */ private Rect mDrawingRect; private Rect mSatValRect; private Rect mHueRect; private Rect mAlphaRect; private Point mStartTouchPoint = null; private AlphaPatternDrawable mAlphaPattern; private OnColorChangedListener mListener; public ColorPickerView(Context context){ this(context, null); } public ColorPickerView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ColorPickerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs); } @Override public Parcelable onSaveInstanceState() { Bundle state = new Bundle(); state.putParcelable("instanceState", super.onSaveInstanceState()); state.putInt("alpha", mAlpha); state.putFloat("hue", mHue); state.putFloat("sat", mSat); state.putFloat("val", mVal); state.putBoolean("show_alpha", mShowAlphaPanel); state.putString("alpha_text", mAlphaSliderText); return state; } @Override public void onRestoreInstanceState(Parcelable state) { if (state instanceof Bundle) { Bundle bundle = (Bundle) state; mAlpha = bundle.getInt("alpha"); mHue = bundle.getFloat("hue"); mSat = bundle.getFloat("sat"); mVal = bundle.getFloat("val"); mShowAlphaPanel = bundle.getBoolean("show_alpha"); mAlphaSliderText = bundle.getString("alpha_text"); state = bundle.getParcelable("instanceState"); } super.onRestoreInstanceState(state); } private void init(Context context, AttributeSet attrs) { //Load those if set in xml resource file. TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.colorpickerview__ColorPickerView); mShowAlphaPanel = a.getBoolean(R.styleable.colorpickerview__ColorPickerView_alphaChannelVisible, false); mAlphaSliderText = a.getString(R.styleable.colorpickerview__ColorPickerView_alphaChannelText); mSliderTrackerColor = a.getColor(R.styleable.colorpickerview__ColorPickerView_sliderColor, 0xFFBDBDBD); mBorderColor = a.getColor(R.styleable.colorpickerview__ColorPickerView_borderColor, 0xFF6E6E6E); a.recycle(); applyThemeColors(context); mHuePanelWidthPx = DrawingUtils.dpToPx(getContext(), HUE_PANEL_WDITH_DP); mAlphaPanelHeightPx = DrawingUtils.dpToPx(getContext(), ALPHA_PANEL_HEIGH_DP); mPanelSpacingPx = DrawingUtils.dpToPx(getContext(), PANEL_SPACING_DP); mCircleTrackerRadiusPx = DrawingUtils.dpToPx(getContext(), CIRCLE_TRACKER_RADIUS_DP); mSliderTrackerSizePx = DrawingUtils.dpToPx(getContext(), SLIDER_TRACKER_SIZE_DP); mSliderTrackerOffsetPx = DrawingUtils.dpToPx(getContext(), SLIDER_TRACKER_OFFSET_DP); mRequiredPadding = getResources().getDimensionPixelSize(R.dimen.colorpickerview__required_padding); initPaintTools(); //Needed for receiving trackball motion events. setFocusable(true); setFocusableInTouchMode(true); } private void applyThemeColors(Context c) { // If no specific border/slider color has been // set we take the default secondary text color // as border/slider color. Thus it will adopt // to theme changes automatically. final TypedValue value = new TypedValue (); TypedArray a = c.obtainStyledAttributes(value.data, new int[] { android.R.attr.textColorSecondary }); if(mBorderColor == DEFAULT_BORDER_COLOR) { mBorderColor = a.getColor(0, DEFAULT_BORDER_COLOR); } if(mSliderTrackerColor == DEFAULT_SLIDER_COLOR) { mSliderTrackerColor = a.getColor(0, DEFAULT_SLIDER_COLOR); } a.recycle(); } private void initPaintTools(){ mSatValPaint = new Paint(); mSatValTrackerPaint = new Paint(); mHueAlphaTrackerPaint = new Paint(); mAlphaPaint = new Paint(); mAlphaTextPaint = new Paint(); mBorderPaint = new Paint(); mSatValTrackerPaint.setStyle(Style.STROKE); mSatValTrackerPaint.setStrokeWidth(DrawingUtils.dpToPx(getContext(), 2)); mSatValTrackerPaint.setAntiAlias(true); mHueAlphaTrackerPaint.setColor(mSliderTrackerColor); mHueAlphaTrackerPaint.setStyle(Style.STROKE); mHueAlphaTrackerPaint.setStrokeWidth(DrawingUtils.dpToPx(getContext(), 2)); mHueAlphaTrackerPaint.setAntiAlias(true); mAlphaTextPaint.setColor(0xff1c1c1c); mAlphaTextPaint.setTextSize(DrawingUtils.dpToPx(getContext(), 14)); mAlphaTextPaint.setAntiAlias(true); mAlphaTextPaint.setTextAlign(Align.CENTER); mAlphaTextPaint.setFakeBoldText(true); } @Override protected void onDraw(Canvas canvas) { if(mDrawingRect.width() <= 0 || mDrawingRect.height() <= 0) { return; } drawSatValPanel(canvas); drawHuePanel(canvas); drawAlphaPanel(canvas); } private void drawSatValPanel(Canvas canvas){ final Rect rect = mSatValRect; if(BORDER_WIDTH_PX > 0){ mBorderPaint.setColor(mBorderColor); canvas.drawRect(mDrawingRect.left, mDrawingRect.top, rect.right + BORDER_WIDTH_PX, rect.bottom + BORDER_WIDTH_PX, mBorderPaint); } if(mValShader == null) { //Black gradient has either not been created or the view has been resized. mValShader = new LinearGradient( rect.left, rect.top, rect.left, rect.bottom, 0xffffffff, 0xff000000, TileMode.CLAMP); } //If the hue has changed we need to recreate the cache. if(mSatValBackgroundCache == null || mSatValBackgroundCache.value != mHue) { if(mSatValBackgroundCache == null) { mSatValBackgroundCache = new BitmapCache(); } //We create our bitmap in the cache if it doesn't exist. if(mSatValBackgroundCache.bitmap == null) { mSatValBackgroundCache.bitmap = Bitmap .createBitmap(rect.width(), rect.height(), Config.ARGB_8888); } //We create the canvas once so we can draw on our bitmap and the hold on to it. if(mSatValBackgroundCache.canvas == null) { mSatValBackgroundCache.canvas = new Canvas(mSatValBackgroundCache.bitmap); } int rgb = Color.HSVToColor(new float[]{mHue,1f,1f}); mSatShader = new LinearGradient( rect.left, rect.top, rect.right, rect.top, 0xffffffff, rgb, TileMode.CLAMP); ComposeShader mShader = new ComposeShader( mValShader, mSatShader, PorterDuff.Mode.MULTIPLY); mSatValPaint.setShader(mShader); // Finally we draw on our canvas, the result will be // stored in our bitmap which is already in the cache. // Since this is drawn on a canvas not rendered on // screen it will automatically not be using the // hardware acceleration. And this was the code that // wasn't supported by hardware acceleration which mean // there is no need to turn it of anymore. The rest of // the view will still be hw accelerated. mSatValBackgroundCache.canvas.drawRect(0, 0, mSatValBackgroundCache.bitmap.getWidth(), mSatValBackgroundCache.bitmap.getHeight(), mSatValPaint); //We set the hue value in our cache to which hue it was drawn with, //then we know that if it hasn't changed we can reuse our cached bitmap. mSatValBackgroundCache.value = mHue; } // We draw our bitmap from the cached, if the hue has changed // then it was just recreated otherwise the old one will be used. canvas.drawBitmap(mSatValBackgroundCache.bitmap, null, rect, null); Point p = satValToPoint(mSat, mVal); mSatValTrackerPaint.setColor(0xff000000); canvas.drawCircle(p.x, p.y, mCircleTrackerRadiusPx - DrawingUtils.dpToPx(getContext(), 1), mSatValTrackerPaint); mSatValTrackerPaint.setColor(0xffdddddd); canvas.drawCircle(p.x, p.y, mCircleTrackerRadiusPx, mSatValTrackerPaint); } private void drawHuePanel(Canvas canvas){ final Rect rect = mHueRect; if(BORDER_WIDTH_PX > 0) { mBorderPaint.setColor(mBorderColor); canvas.drawRect(rect.left - BORDER_WIDTH_PX, rect.top - BORDER_WIDTH_PX, rect.right + BORDER_WIDTH_PX, rect.bottom + BORDER_WIDTH_PX, mBorderPaint); } if(mHueBackgroundCache == null) { mHueBackgroundCache = new BitmapCache(); mHueBackgroundCache.bitmap = Bitmap.createBitmap(rect.width(), rect.height(), Config.ARGB_8888); mHueBackgroundCache.canvas = new Canvas(mHueBackgroundCache.bitmap); int[] hueColors = new int[(int)(rect.height() + 0.5f)]; // Generate array of all colors, will be drawn as individual lines. float h = 360f; for(int i = 0; i < hueColors.length; i++) { hueColors[i] = Color.HSVToColor(new float[]{h, 1f,1f}); h -= 360f / hueColors.length; } // Time to draw the hue color gradient, // its drawn as individual lines which // will be quite many when the resolution is high // and/or the panel is large. Paint linePaint = new Paint(); linePaint.setStrokeWidth(0); for(int i = 0; i < hueColors.length; i++) { linePaint.setColor(hueColors[i]); mHueBackgroundCache.canvas.drawLine(0, i, mHueBackgroundCache.bitmap.getWidth(), i, linePaint); } } canvas.drawBitmap(mHueBackgroundCache.bitmap, null, rect, null); Point p = hueToPoint(mHue); RectF r = new RectF(); r.left = rect.left - mSliderTrackerOffsetPx; r.right = rect.right + mSliderTrackerOffsetPx; r.top = p.y - (mSliderTrackerSizePx / 2); r.bottom = p.y + (mSliderTrackerSizePx / 2); canvas.drawRoundRect(r, 2, 2, mHueAlphaTrackerPaint); } private void drawAlphaPanel(Canvas canvas) { /* * Will be drawn with hw acceleration, very fast. * Also the AlphaPatternDrawable is backed by a bitmap * generated only once if the size does not change. */ if(!mShowAlphaPanel || mAlphaRect == null || mAlphaPattern == null) return; final Rect rect = mAlphaRect; if(BORDER_WIDTH_PX > 0){ mBorderPaint.setColor(mBorderColor); canvas.drawRect(rect.left - BORDER_WIDTH_PX, rect.top - BORDER_WIDTH_PX, rect.right + BORDER_WIDTH_PX, rect.bottom + BORDER_WIDTH_PX, mBorderPaint); } mAlphaPattern.draw(canvas); float[] hsv = new float[]{mHue,mSat,mVal}; int color = Color.HSVToColor(hsv); int acolor = Color.HSVToColor(0, hsv); mAlphaShader = new LinearGradient(rect.left, rect.top, rect.right, rect.top, color, acolor, TileMode.CLAMP); mAlphaPaint.setShader(mAlphaShader); canvas.drawRect(rect, mAlphaPaint); if(mAlphaSliderText != null && !mAlphaSliderText.equals("")){ canvas.drawText(mAlphaSliderText, rect.centerX(), rect.centerY() + DrawingUtils.dpToPx(getContext(), 4), mAlphaTextPaint); } Point p = alphaToPoint(mAlpha); RectF r = new RectF(); r.left = p.x - (mSliderTrackerSizePx / 2); r.right = p.x + (mSliderTrackerSizePx / 2); r.top = rect.top - mSliderTrackerOffsetPx; r.bottom = rect.bottom + mSliderTrackerOffsetPx; canvas.drawRoundRect(r, 2, 2, mHueAlphaTrackerPaint); } private Point hueToPoint(float hue){ final Rect rect = mHueRect; final float height = rect.height(); Point p = new Point(); p.y = (int) (height - (hue * height / 360f) + rect.top); p.x = (int) rect.left; return p; } private Point satValToPoint(float sat, float val){ final Rect rect = mSatValRect; final float height = rect.height(); final float width = rect.width(); Point p = new Point(); p.x = (int) (sat * width + rect.left); p.y = (int) ((1f - val) * height + rect.top); return p; } private Point alphaToPoint(int alpha){ final Rect rect = mAlphaRect; final float width = rect.width(); Point p = new Point(); p.x = (int) (width - (alpha * width / 0xff) + rect.left); p.y = (int) rect.top; return p; } private float[] pointToSatVal(float x, float y){ final Rect rect = mSatValRect; float[] result = new float[2]; float width = rect.width(); float height = rect.height(); if (x < rect.left){ x = 0f; } else if(x > rect.right){ x = width; } else{ x = x - rect.left; } if (y < rect.top){ y = 0f; } else if(y > rect.bottom){ y = height; } else{ y = y - rect.top; } result[0] = 1.f / width * x; result[1] = 1.f - (1.f / height * y); return result; } private float pointToHue(float y){ final Rect rect = mHueRect; float height = rect.height(); if (y < rect.top){ y = 0f; } else if(y > rect.bottom){ y = height; } else{ y = y - rect.top; } float hue = 360f - (y * 360f / height); Log.d("color-picker-view", "Hue: " + hue); return hue; } private int pointToAlpha(int x){ final Rect rect = mAlphaRect; final int width = (int) rect.width(); if(x < rect.left){ x = 0; } else if(x > rect.right){ x = width; } else{ x = x - (int)rect.left; } return 0xff - (x * 0xff / width); } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent event) { boolean update = false; switch(event.getAction()){ case MotionEvent.ACTION_DOWN: mStartTouchPoint = new Point((int)event.getX(), (int)event.getY()); update = moveTrackersIfNeeded(event); break; case MotionEvent.ACTION_MOVE: update = moveTrackersIfNeeded(event); break; case MotionEvent.ACTION_UP: mStartTouchPoint = null; update = moveTrackersIfNeeded(event); break; } if(update){ if(mListener != null){ mListener.onColorChanged(Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal})); } invalidate(); return true; } return super.onTouchEvent(event); } private boolean moveTrackersIfNeeded(MotionEvent event){ if(mStartTouchPoint == null) { return false; } boolean update = false; int startX = mStartTouchPoint.x; int startY = mStartTouchPoint.y; if(mHueRect.contains(startX, startY)){ mHue = pointToHue(event.getY()); update = true; } else if(mSatValRect.contains(startX, startY)){ float[] result = pointToSatVal(event.getX(), event.getY()); mSat = result[0]; mVal = result[1]; update = true; } else if(mAlphaRect != null && mAlphaRect.contains(startX, startY)){ mAlpha = pointToAlpha((int)event.getX()); update = true; } return update; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int finalWidth = 0; int finalHeight = 0; int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthAllowed = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight(); int heightAllowed = MeasureSpec.getSize(heightMeasureSpec) - getPaddingBottom() - getPaddingTop(); //Log.d("color-picker-view", "widthMode: " + modeToString(widthMode) + " heightMode: " + modeToString(heightMode) + " widthAllowed: " + widthAllowed + " heightAllowed: " + heightAllowed); if(widthMode == MeasureSpec.EXACTLY || heightMode == MeasureSpec.EXACTLY) { //A exact value has been set in either direction, we need to stay within this size. if(widthMode == MeasureSpec.EXACTLY && heightMode != MeasureSpec.EXACTLY) { //The with has been specified exactly, we need to adopt the height to fit. int h = (int) (widthAllowed - mPanelSpacingPx - mHuePanelWidthPx); if(mShowAlphaPanel) { h += mPanelSpacingPx + mAlphaPanelHeightPx; } if(h > heightAllowed) { //We can't fit the view in this container, set the size to whatever was allowed. finalHeight = heightAllowed; } else { finalHeight = h; } finalWidth = widthAllowed; } else if(heightMode == MeasureSpec.EXACTLY && widthMode != MeasureSpec.EXACTLY) { //The height has been specified exactly, we need to stay within this height and adopt the width. int w = (int) (heightAllowed + mPanelSpacingPx + mHuePanelWidthPx); if(mShowAlphaPanel) { w -= (mPanelSpacingPx + mAlphaPanelHeightPx); } if(w > widthAllowed) { //we can't fit within this container, set the size to whatever was allowed. finalWidth = widthAllowed; } else { finalWidth = w; } finalHeight = heightAllowed; } else { //If we get here the dev has set the width and height to exact sizes. For example match_parent or 300dp. //This will mean that the sat/val panel will not be square but it doesn't matter. It will work anyway. //In all other senarios our goal is to make that panel square. //We set the sizes to exactly what we were told. finalWidth = widthAllowed; finalHeight = heightAllowed; } } else { //If no exact size has been set we try to make our view as big as possible //within the allowed space. //Calculate the needed width to layout using max allowed height. int widthNeeded = (int) (heightAllowed + mPanelSpacingPx + mHuePanelWidthPx); //Calculate the needed height to layout using max allowed width. int heightNeeded = (int) (widthAllowed - mPanelSpacingPx - mHuePanelWidthPx); if(mShowAlphaPanel) { widthNeeded -= (mPanelSpacingPx + mAlphaPanelHeightPx); heightNeeded += mPanelSpacingPx + mAlphaPanelHeightPx; } boolean widthOk = false; boolean heightOk = false; if(widthNeeded <= widthAllowed) { widthOk = true; } if(heightNeeded <= heightAllowed) { heightOk = true; } //Log.d("color-picker-view", "Size - Allowed w: " + widthAllowed + " h: " + heightAllowed + " Needed w:" + widthNeeded + " h: " + heightNeeded); if(widthOk && heightOk) { finalWidth = widthAllowed; finalHeight = heightNeeded; } else if(!heightOk && widthOk) { finalHeight = heightAllowed; finalWidth = widthNeeded; } else if(!widthOk && heightOk) { finalHeight = heightNeeded; finalWidth = widthAllowed; } else { finalHeight = heightAllowed; finalWidth = widthAllowed; } } //Log.d("color-picker-view", "Final Size: " + finalWidth + "x" + finalHeight); setMeasuredDimension(finalWidth + getPaddingLeft() + getPaddingRight(), finalHeight + getPaddingTop() + getPaddingBottom()); } private int getPreferredWidth(){ //Our preferred width and height is 200dp for the square sat / val rectangle. int width = DrawingUtils.dpToPx(getContext(), 200); return (int) (width + mHuePanelWidthPx + mPanelSpacingPx); } private int getPreferredHeight(){ int height = DrawingUtils.dpToPx(getContext(), 200); if(mShowAlphaPanel){ height += mPanelSpacingPx + mAlphaPanelHeightPx; } return height; } @Override public int getPaddingTop() { return Math.max(super.getPaddingTop(), mRequiredPadding); } @Override public int getPaddingBottom() { return Math.max(super.getPaddingBottom(), mRequiredPadding); } @Override public int getPaddingLeft() { return Math.max(super.getPaddingLeft(), mRequiredPadding); } @Override public int getPaddingRight() { return Math.max(super.getPaddingRight(), mRequiredPadding); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mDrawingRect = new Rect(); mDrawingRect.left = getPaddingLeft(); mDrawingRect.right = w - getPaddingRight(); mDrawingRect.top = getPaddingTop(); mDrawingRect.bottom = h - getPaddingBottom(); //The need to be recreated because they depend on the size of the view. mValShader = null; mSatShader = null; mAlphaShader = null;; // Clear those bitmap caches since the size may have changed. mSatValBackgroundCache = null; mHueBackgroundCache = null; //Log.d("color-picker-view", "Size: " + w + "x" + h); setUpSatValRect(); setUpHueRect(); setUpAlphaRect(); } private void setUpSatValRect(){ //Calculate the size for the big color rectangle. final Rect dRect = mDrawingRect; int left = dRect.left + BORDER_WIDTH_PX; int top = dRect.top + BORDER_WIDTH_PX; int bottom = dRect.bottom - BORDER_WIDTH_PX; int right = dRect.right - BORDER_WIDTH_PX - mPanelSpacingPx - mHuePanelWidthPx; if(mShowAlphaPanel) { bottom -= (mAlphaPanelHeightPx + mPanelSpacingPx); } mSatValRect = new Rect(left,top, right, bottom); } private void setUpHueRect(){ //Calculate the size for the hue slider on the left. final Rect dRect = mDrawingRect; int left = dRect.right - mHuePanelWidthPx + BORDER_WIDTH_PX; int top = dRect.top + BORDER_WIDTH_PX; int bottom = dRect.bottom - BORDER_WIDTH_PX - (mShowAlphaPanel ? (mPanelSpacingPx + mAlphaPanelHeightPx) : 0); int right = dRect.right - BORDER_WIDTH_PX; mHueRect = new Rect(left, top, right, bottom); } private void setUpAlphaRect(){ if(!mShowAlphaPanel) return; final Rect dRect = mDrawingRect; int left = dRect.left + BORDER_WIDTH_PX; int top = dRect.bottom - mAlphaPanelHeightPx + BORDER_WIDTH_PX; int bottom = dRect.bottom - BORDER_WIDTH_PX; int right = dRect.right - BORDER_WIDTH_PX; mAlphaRect = new Rect(left, top, right, bottom); mAlphaPattern = new AlphaPatternDrawable(DrawingUtils.dpToPx(getContext(), 5)); mAlphaPattern.setBounds(Math.round(mAlphaRect.left), Math .round(mAlphaRect.top), Math.round(mAlphaRect.right), Math .round(mAlphaRect.bottom)); } /** * Set a OnColorChangedListener to get notified when the color * selected by the user has changed. * @param listener */ public void setOnColorChangedListener(OnColorChangedListener listener){ mListener = listener; } /** * Get the current color this view is showing. * @return the current color. */ public int getColor(){ return Color.HSVToColor(mAlpha, new float[]{mHue,mSat,mVal}); } /** * Set the color the view should show. * @param color The color that should be selected. #argb */ public void setColor(int color){ setColor(color, false); } /** * Set the color this view should show. * @param color The color that should be selected. #argb * @param callback If you want to get a callback to * your OnColorChangedListener. */ public void setColor(int color, boolean callback){ int alpha = Color.alpha(color); int red = Color.red(color); int blue = Color.blue(color); int green = Color.green(color); float[] hsv = new float[3]; Color.RGBToHSV(red, green, blue, hsv); mAlpha = alpha; mHue = hsv[0]; mSat = hsv[1]; mVal = hsv[2]; if(callback && mListener != null){ mListener.onColorChanged(Color.HSVToColor(mAlpha, new float[]{mHue, mSat, mVal})); } invalidate(); } /** * Set if the user is allowed to adjust the alpha panel. Default is false. * If it is set to false no alpha will be set. * @param visible */ public void setAlphaSliderVisible(boolean visible){ if(mShowAlphaPanel != visible){ mShowAlphaPanel = visible; /* * Force recreation. */ mValShader = null; mSatShader = null; mAlphaShader = null; mHueBackgroundCache = null; mSatValBackgroundCache = null; requestLayout(); } } /** * Set the color of the tracker slider on the hue and alpha panel. * @param color */ public void setSliderTrackerColor(int color){ mSliderTrackerColor = color; mHueAlphaTrackerPaint.setColor(mSliderTrackerColor); invalidate(); } /** * Get color of the tracker slider on the hue and alpha panel. * @return */ public int getSliderTrackerColor(){ return mSliderTrackerColor; } /** * Set the color of the border surrounding all panels. * @param color */ public void setBorderColor(int color){ mBorderColor = color; invalidate(); } /** * Get the color of the border surrounding all panels. */ public int getBorderColor(){ return mBorderColor; } /** * Set the text that should be shown in the * alpha slider. Set to null to disable text. * @param res string resource id. */ public void setAlphaSliderText(int res){ String text = getContext().getString(res); setAlphaSliderText(text); } /** * Set the text that should be shown in the * alpha slider. Set to null to disable text. * @param text Text that should be shown. */ public void setAlphaSliderText(String text){ mAlphaSliderText = text; invalidate(); } /** * Get the current value of the text * that will be shown in the alpha * slider. * @return */ public String getAlphaSliderText(){ return mAlphaSliderText; } private class BitmapCache { public Canvas canvas; public Bitmap bitmap; public float value; } }
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package org.lwjgl.vulkan; import javax.annotation.*; import java.nio.*; import org.lwjgl.*; import org.lwjgl.system.*; import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.MemoryStack.*; /** * Structure describing conservative raster properties that can be supported by an implementation. * * <h5>Description</h5> * * <p>If the {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT} structure is included in the {@code pNext} chain of the {@link VkPhysicalDeviceProperties2} structure passed to {@link VK11#vkGetPhysicalDeviceProperties2 GetPhysicalDeviceProperties2}, it is filled in with each corresponding implementation-dependent property.</p> * * <h5>Valid Usage (Implicit)</h5> * * <ul> * <li>{@code sType} <b>must</b> be {@link EXTConservativeRasterization#VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT}</li> * </ul> * * <h3>Layout</h3> * * <pre><code> * struct VkPhysicalDeviceConservativeRasterizationPropertiesEXT { * VkStructureType {@link #sType}; * void * {@link #pNext}; * float {@link #primitiveOverestimationSize}; * float {@link #maxExtraPrimitiveOverestimationSize}; * float {@link #extraPrimitiveOverestimationSizeGranularity}; * VkBool32 {@link #primitiveUnderestimation}; * VkBool32 {@link #conservativePointAndLineRasterization}; * VkBool32 {@link #degenerateTrianglesRasterized}; * VkBool32 {@link #degenerateLinesRasterized}; * VkBool32 {@link #fullyCoveredFragmentShaderInputVariable}; * VkBool32 {@link #conservativeRasterizationPostDepthCoverage}; * }</code></pre> */ public class VkPhysicalDeviceConservativeRasterizationPropertiesEXT extends Struct implements NativeResource { /** The struct size in bytes. */ public static final int SIZEOF; /** The struct alignment in bytes. */ public static final int ALIGNOF; /** The struct member offsets. */ public static final int STYPE, PNEXT, PRIMITIVEOVERESTIMATIONSIZE, MAXEXTRAPRIMITIVEOVERESTIMATIONSIZE, EXTRAPRIMITIVEOVERESTIMATIONSIZEGRANULARITY, PRIMITIVEUNDERESTIMATION, CONSERVATIVEPOINTANDLINERASTERIZATION, DEGENERATETRIANGLESRASTERIZED, DEGENERATELINESRASTERIZED, FULLYCOVEREDFRAGMENTSHADERINPUTVARIABLE, CONSERVATIVERASTERIZATIONPOSTDEPTHCOVERAGE; static { Layout layout = __struct( __member(4), __member(POINTER_SIZE), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4), __member(4) ); SIZEOF = layout.getSize(); ALIGNOF = layout.getAlignment(); STYPE = layout.offsetof(0); PNEXT = layout.offsetof(1); PRIMITIVEOVERESTIMATIONSIZE = layout.offsetof(2); MAXEXTRAPRIMITIVEOVERESTIMATIONSIZE = layout.offsetof(3); EXTRAPRIMITIVEOVERESTIMATIONSIZEGRANULARITY = layout.offsetof(4); PRIMITIVEUNDERESTIMATION = layout.offsetof(5); CONSERVATIVEPOINTANDLINERASTERIZATION = layout.offsetof(6); DEGENERATETRIANGLESRASTERIZED = layout.offsetof(7); DEGENERATELINESRASTERIZED = layout.offsetof(8); FULLYCOVEREDFRAGMENTSHADERINPUTVARIABLE = layout.offsetof(9); CONSERVATIVERASTERIZATIONPOSTDEPTHCOVERAGE = layout.offsetof(10); } /** * Creates a {@code VkPhysicalDeviceConservativeRasterizationPropertiesEXT} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be * visible to the struct instance and vice versa. * * <p>The created instance holds a strong reference to the container object.</p> */ public VkPhysicalDeviceConservativeRasterizationPropertiesEXT(ByteBuffer container) { super(memAddress(container), __checkContainer(container, SIZEOF)); } @Override public int sizeof() { return SIZEOF; } /** the type of this structure. */ @NativeType("VkStructureType") public int sType() { return nsType(address()); } /** {@code NULL} or a pointer to a structure extending this structure. */ @NativeType("void *") public long pNext() { return npNext(address()); } /** the size in pixels the generating primitive is increased at each of its edges during conservative rasterization overestimation mode. Even with a size of 0.0, conservative rasterization overestimation rules still apply and if any part of the pixel rectangle is covered by the generating primitive, fragments are generated for the entire pixel. However implementations <b>may</b> make the pixel coverage area even more conservative by increasing the size of the generating primitive. */ public float primitiveOverestimationSize() { return nprimitiveOverestimationSize(address()); } /** the maximum size in pixels of extra overestimation the implementation supports in the pipeline state. A value of 0.0 means the implementation does not support any additional overestimation of the generating primitive during conservative rasterization. A value above 0.0 allows the application to further increase the size of the generating primitive during conservative rasterization overestimation. */ public float maxExtraPrimitiveOverestimationSize() { return nmaxExtraPrimitiveOverestimationSize(address()); } /** the granularity of extra overestimation that can be specified in the pipeline state between 0.0 and {@code maxExtraPrimitiveOverestimationSize} inclusive. A value of 0.0 means the implementation can use the smallest representable non-zero value in the screen space pixel fixed-point grid. */ public float extraPrimitiveOverestimationSizeGranularity() { return nextraPrimitiveOverestimationSizeGranularity(address()); } /** {@link VK10#VK_TRUE TRUE} if the implementation supports the {@link EXTConservativeRasterization#VK_CONSERVATIVE_RASTERIZATION_MODE_UNDERESTIMATE_EXT CONSERVATIVE_RASTERIZATION_MODE_UNDERESTIMATE_EXT} conservative rasterization mode in addition to {@link EXTConservativeRasterization#VK_CONSERVATIVE_RASTERIZATION_MODE_OVERESTIMATE_EXT CONSERVATIVE_RASTERIZATION_MODE_OVERESTIMATE_EXT}. Otherwise the implementation only supports {@link EXTConservativeRasterization#VK_CONSERVATIVE_RASTERIZATION_MODE_OVERESTIMATE_EXT CONSERVATIVE_RASTERIZATION_MODE_OVERESTIMATE_EXT}. */ @NativeType("VkBool32") public boolean primitiveUnderestimation() { return nprimitiveUnderestimation(address()) != 0; } /** {@link VK10#VK_TRUE TRUE} if the implementation supports conservative rasterization of point and line primitives as well as triangle primitives. Otherwise the implementation only supports triangle primitives. */ @NativeType("VkBool32") public boolean conservativePointAndLineRasterization() { return nconservativePointAndLineRasterization(address()) != 0; } /** {@link VK10#VK_FALSE FALSE} if the implementation culls primitives generated from triangles that become zero area after they are quantized to the fixed-point rasterization pixel grid. {@code degenerateTrianglesRasterized} is {@link VK10#VK_TRUE TRUE} if these primitives are not culled and the provoking vertex attributes and depth value are used for the fragments. The primitive area calculation is done on the primitive generated from the clipped triangle if applicable. Zero area primitives are backfacing and the application <b>can</b> enable backface culling if desired. */ @NativeType("VkBool32") public boolean degenerateTrianglesRasterized() { return ndegenerateTrianglesRasterized(address()) != 0; } /** {@link VK10#VK_FALSE FALSE} if the implementation culls lines that become zero length after they are quantized to the fixed-point rasterization pixel grid. {@code degenerateLinesRasterized} is {@link VK10#VK_TRUE TRUE} if zero length lines are not culled and the provoking vertex attributes and depth value are used for the fragments. */ @NativeType("VkBool32") public boolean degenerateLinesRasterized() { return ndegenerateLinesRasterized(address()) != 0; } /** {@link VK10#VK_TRUE TRUE} if the implementation supports the SPIR-V builtin fragment shader input variable {@code FullyCoveredEXT} which specifies that conservative rasterization is enabled and the fragment area is fully covered by the generating primitive. */ @NativeType("VkBool32") public boolean fullyCoveredFragmentShaderInputVariable() { return nfullyCoveredFragmentShaderInputVariable(address()) != 0; } /** {@link VK10#VK_TRUE TRUE} if the implementation supports conservative rasterization with the {@code PostDepthCoverage} execution mode enabled. Otherwise the {@code PostDepthCoverage} execution mode <b>must</b> not be used when conservative rasterization is enabled. */ @NativeType("VkBool32") public boolean conservativeRasterizationPostDepthCoverage() { return nconservativeRasterizationPostDepthCoverage(address()) != 0; } /** Sets the specified value to the {@link #sType} field. */ public VkPhysicalDeviceConservativeRasterizationPropertiesEXT sType(@NativeType("VkStructureType") int value) { nsType(address(), value); return this; } /** Sets the {@link EXTConservativeRasterization#VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT} value to the {@link #sType} field. */ public VkPhysicalDeviceConservativeRasterizationPropertiesEXT sType$Default() { return sType(EXTConservativeRasterization.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT); } /** Sets the specified value to the {@link #pNext} field. */ public VkPhysicalDeviceConservativeRasterizationPropertiesEXT pNext(@NativeType("void *") long value) { npNext(address(), value); return this; } /** Initializes this struct with the specified values. */ public VkPhysicalDeviceConservativeRasterizationPropertiesEXT set( int sType, long pNext ) { sType(sType); pNext(pNext); return this; } /** * Copies the specified struct data to this struct. * * @param src the source struct * * @return this struct */ public VkPhysicalDeviceConservativeRasterizationPropertiesEXT set(VkPhysicalDeviceConservativeRasterizationPropertiesEXT src) { memCopy(src.address(), address(), SIZEOF); return this; } // ----------------------------------- /** Returns a new {@code VkPhysicalDeviceConservativeRasterizationPropertiesEXT} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */ public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT malloc() { return wrap(VkPhysicalDeviceConservativeRasterizationPropertiesEXT.class, nmemAllocChecked(SIZEOF)); } /** Returns a new {@code VkPhysicalDeviceConservativeRasterizationPropertiesEXT} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */ public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT calloc() { return wrap(VkPhysicalDeviceConservativeRasterizationPropertiesEXT.class, nmemCallocChecked(1, SIZEOF)); } /** Returns a new {@code VkPhysicalDeviceConservativeRasterizationPropertiesEXT} instance allocated with {@link BufferUtils}. */ public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT create() { ByteBuffer container = BufferUtils.createByteBuffer(SIZEOF); return wrap(VkPhysicalDeviceConservativeRasterizationPropertiesEXT.class, memAddress(container), container); } /** Returns a new {@code VkPhysicalDeviceConservativeRasterizationPropertiesEXT} instance for the specified memory address. */ public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT create(long address) { return wrap(VkPhysicalDeviceConservativeRasterizationPropertiesEXT.class, address); } /** Like {@link #create(long) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT createSafe(long address) { return address == NULL ? null : wrap(VkPhysicalDeviceConservativeRasterizationPropertiesEXT.class, address); } /** * Returns a new {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer malloc(int capacity) { return wrap(Buffer.class, nmemAllocChecked(__checkMalloc(capacity, SIZEOF)), capacity); } /** * Returns a new {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. * * @param capacity the buffer capacity */ public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer calloc(int capacity) { return wrap(Buffer.class, nmemCallocChecked(capacity, SIZEOF), capacity); } /** * Returns a new {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer} instance allocated with {@link BufferUtils}. * * @param capacity the buffer capacity */ public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer create(int capacity) { ByteBuffer container = __create(capacity, SIZEOF); return wrap(Buffer.class, memAddress(container), capacity, container); } /** * Create a {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer} instance at the specified memory. * * @param address the memory address * @param capacity the buffer capacity */ public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer create(long address, int capacity) { return wrap(Buffer.class, address, capacity); } /** Like {@link #create(long, int) create}, but returns {@code null} if {@code address} is {@code NULL}. */ @Nullable public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer createSafe(long address, int capacity) { return address == NULL ? null : wrap(Buffer.class, address, capacity); } // ----------------------------------- /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */ @Deprecated public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT mallocStack() { return malloc(stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */ @Deprecated public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT callocStack() { return calloc(stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(MemoryStack)} instead. */ @Deprecated public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT mallocStack(MemoryStack stack) { return malloc(stack); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(MemoryStack)} instead. */ @Deprecated public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT callocStack(MemoryStack stack) { return calloc(stack); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */ @Deprecated public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer mallocStack(int capacity) { return malloc(capacity, stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */ @Deprecated public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer callocStack(int capacity) { return calloc(capacity, stackGet()); } /** Deprecated for removal in 3.4.0. Use {@link #malloc(int, MemoryStack)} instead. */ @Deprecated public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer mallocStack(int capacity, MemoryStack stack) { return malloc(capacity, stack); } /** Deprecated for removal in 3.4.0. Use {@link #calloc(int, MemoryStack)} instead. */ @Deprecated public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer callocStack(int capacity, MemoryStack stack) { return calloc(capacity, stack); } /** * Returns a new {@code VkPhysicalDeviceConservativeRasterizationPropertiesEXT} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate */ public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT malloc(MemoryStack stack) { return wrap(VkPhysicalDeviceConservativeRasterizationPropertiesEXT.class, stack.nmalloc(ALIGNOF, SIZEOF)); } /** * Returns a new {@code VkPhysicalDeviceConservativeRasterizationPropertiesEXT} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate */ public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT calloc(MemoryStack stack) { return wrap(VkPhysicalDeviceConservativeRasterizationPropertiesEXT.class, stack.ncalloc(ALIGNOF, 1, SIZEOF)); } /** * Returns a new {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer} instance allocated on the specified {@link MemoryStack}. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer malloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity); } /** * Returns a new {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero. * * @param stack the stack from which to allocate * @param capacity the buffer capacity */ public static VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer calloc(int capacity, MemoryStack stack) { return wrap(Buffer.class, stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity); } // ----------------------------------- /** Unsafe version of {@link #sType}. */ public static int nsType(long struct) { return UNSAFE.getInt(null, struct + VkPhysicalDeviceConservativeRasterizationPropertiesEXT.STYPE); } /** Unsafe version of {@link #pNext}. */ public static long npNext(long struct) { return memGetAddress(struct + VkPhysicalDeviceConservativeRasterizationPropertiesEXT.PNEXT); } /** Unsafe version of {@link #primitiveOverestimationSize}. */ public static float nprimitiveOverestimationSize(long struct) { return UNSAFE.getFloat(null, struct + VkPhysicalDeviceConservativeRasterizationPropertiesEXT.PRIMITIVEOVERESTIMATIONSIZE); } /** Unsafe version of {@link #maxExtraPrimitiveOverestimationSize}. */ public static float nmaxExtraPrimitiveOverestimationSize(long struct) { return UNSAFE.getFloat(null, struct + VkPhysicalDeviceConservativeRasterizationPropertiesEXT.MAXEXTRAPRIMITIVEOVERESTIMATIONSIZE); } /** Unsafe version of {@link #extraPrimitiveOverestimationSizeGranularity}. */ public static float nextraPrimitiveOverestimationSizeGranularity(long struct) { return UNSAFE.getFloat(null, struct + VkPhysicalDeviceConservativeRasterizationPropertiesEXT.EXTRAPRIMITIVEOVERESTIMATIONSIZEGRANULARITY); } /** Unsafe version of {@link #primitiveUnderestimation}. */ public static int nprimitiveUnderestimation(long struct) { return UNSAFE.getInt(null, struct + VkPhysicalDeviceConservativeRasterizationPropertiesEXT.PRIMITIVEUNDERESTIMATION); } /** Unsafe version of {@link #conservativePointAndLineRasterization}. */ public static int nconservativePointAndLineRasterization(long struct) { return UNSAFE.getInt(null, struct + VkPhysicalDeviceConservativeRasterizationPropertiesEXT.CONSERVATIVEPOINTANDLINERASTERIZATION); } /** Unsafe version of {@link #degenerateTrianglesRasterized}. */ public static int ndegenerateTrianglesRasterized(long struct) { return UNSAFE.getInt(null, struct + VkPhysicalDeviceConservativeRasterizationPropertiesEXT.DEGENERATETRIANGLESRASTERIZED); } /** Unsafe version of {@link #degenerateLinesRasterized}. */ public static int ndegenerateLinesRasterized(long struct) { return UNSAFE.getInt(null, struct + VkPhysicalDeviceConservativeRasterizationPropertiesEXT.DEGENERATELINESRASTERIZED); } /** Unsafe version of {@link #fullyCoveredFragmentShaderInputVariable}. */ public static int nfullyCoveredFragmentShaderInputVariable(long struct) { return UNSAFE.getInt(null, struct + VkPhysicalDeviceConservativeRasterizationPropertiesEXT.FULLYCOVEREDFRAGMENTSHADERINPUTVARIABLE); } /** Unsafe version of {@link #conservativeRasterizationPostDepthCoverage}. */ public static int nconservativeRasterizationPostDepthCoverage(long struct) { return UNSAFE.getInt(null, struct + VkPhysicalDeviceConservativeRasterizationPropertiesEXT.CONSERVATIVERASTERIZATIONPOSTDEPTHCOVERAGE); } /** Unsafe version of {@link #sType(int) sType}. */ public static void nsType(long struct, int value) { UNSAFE.putInt(null, struct + VkPhysicalDeviceConservativeRasterizationPropertiesEXT.STYPE, value); } /** Unsafe version of {@link #pNext(long) pNext}. */ public static void npNext(long struct, long value) { memPutAddress(struct + VkPhysicalDeviceConservativeRasterizationPropertiesEXT.PNEXT, value); } // ----------------------------------- /** An array of {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT} structs. */ public static class Buffer extends StructBuffer<VkPhysicalDeviceConservativeRasterizationPropertiesEXT, Buffer> implements NativeResource { private static final VkPhysicalDeviceConservativeRasterizationPropertiesEXT ELEMENT_FACTORY = VkPhysicalDeviceConservativeRasterizationPropertiesEXT.create(-1L); /** * Creates a new {@code VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer} instance backed by the specified container. * * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided * by {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT#SIZEOF}, and its mark will be undefined. * * <p>The created buffer instance holds a strong reference to the container object.</p> */ public Buffer(ByteBuffer container) { super(container, container.remaining() / SIZEOF); } public Buffer(long address, int cap) { super(address, null, -1, 0, cap, cap); } Buffer(long address, @Nullable ByteBuffer container, int mark, int pos, int lim, int cap) { super(address, container, mark, pos, lim, cap); } @Override protected Buffer self() { return this; } @Override protected VkPhysicalDeviceConservativeRasterizationPropertiesEXT getElementFactory() { return ELEMENT_FACTORY; } /** @return the value of the {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT#sType} field. */ @NativeType("VkStructureType") public int sType() { return VkPhysicalDeviceConservativeRasterizationPropertiesEXT.nsType(address()); } /** @return the value of the {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT#pNext} field. */ @NativeType("void *") public long pNext() { return VkPhysicalDeviceConservativeRasterizationPropertiesEXT.npNext(address()); } /** @return the value of the {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT#primitiveOverestimationSize} field. */ public float primitiveOverestimationSize() { return VkPhysicalDeviceConservativeRasterizationPropertiesEXT.nprimitiveOverestimationSize(address()); } /** @return the value of the {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT#maxExtraPrimitiveOverestimationSize} field. */ public float maxExtraPrimitiveOverestimationSize() { return VkPhysicalDeviceConservativeRasterizationPropertiesEXT.nmaxExtraPrimitiveOverestimationSize(address()); } /** @return the value of the {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT#extraPrimitiveOverestimationSizeGranularity} field. */ public float extraPrimitiveOverestimationSizeGranularity() { return VkPhysicalDeviceConservativeRasterizationPropertiesEXT.nextraPrimitiveOverestimationSizeGranularity(address()); } /** @return the value of the {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT#primitiveUnderestimation} field. */ @NativeType("VkBool32") public boolean primitiveUnderestimation() { return VkPhysicalDeviceConservativeRasterizationPropertiesEXT.nprimitiveUnderestimation(address()) != 0; } /** @return the value of the {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT#conservativePointAndLineRasterization} field. */ @NativeType("VkBool32") public boolean conservativePointAndLineRasterization() { return VkPhysicalDeviceConservativeRasterizationPropertiesEXT.nconservativePointAndLineRasterization(address()) != 0; } /** @return the value of the {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT#degenerateTrianglesRasterized} field. */ @NativeType("VkBool32") public boolean degenerateTrianglesRasterized() { return VkPhysicalDeviceConservativeRasterizationPropertiesEXT.ndegenerateTrianglesRasterized(address()) != 0; } /** @return the value of the {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT#degenerateLinesRasterized} field. */ @NativeType("VkBool32") public boolean degenerateLinesRasterized() { return VkPhysicalDeviceConservativeRasterizationPropertiesEXT.ndegenerateLinesRasterized(address()) != 0; } /** @return the value of the {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT#fullyCoveredFragmentShaderInputVariable} field. */ @NativeType("VkBool32") public boolean fullyCoveredFragmentShaderInputVariable() { return VkPhysicalDeviceConservativeRasterizationPropertiesEXT.nfullyCoveredFragmentShaderInputVariable(address()) != 0; } /** @return the value of the {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT#conservativeRasterizationPostDepthCoverage} field. */ @NativeType("VkBool32") public boolean conservativeRasterizationPostDepthCoverage() { return VkPhysicalDeviceConservativeRasterizationPropertiesEXT.nconservativeRasterizationPostDepthCoverage(address()) != 0; } /** Sets the specified value to the {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT#sType} field. */ public VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer sType(@NativeType("VkStructureType") int value) { VkPhysicalDeviceConservativeRasterizationPropertiesEXT.nsType(address(), value); return this; } /** Sets the {@link EXTConservativeRasterization#VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT} value to the {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT#sType} field. */ public VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer sType$Default() { return sType(EXTConservativeRasterization.VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONSERVATIVE_RASTERIZATION_PROPERTIES_EXT); } /** Sets the specified value to the {@link VkPhysicalDeviceConservativeRasterizationPropertiesEXT#pNext} field. */ public VkPhysicalDeviceConservativeRasterizationPropertiesEXT.Buffer pNext(@NativeType("void *") long value) { VkPhysicalDeviceConservativeRasterizationPropertiesEXT.npNext(address(), value); return this; } } }
/** * Copyright 2012 multibit.org * * Licensed under the MIT license (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.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.multibit.file; import com.google.leafcoin.core.BlockChain; import com.google.leafcoin.core.ECKey; import com.google.leafcoin.core.Wallet; import com.google.leafcoin.crypto.KeyCrypterException; import org.multibit.ApplicationDataDirectoryLocator; import org.multibit.controller.Controller; import org.multibit.controller.bitcoin.BitcoinController; import org.multibit.message.Message; import org.multibit.message.MessageManager; import org.multibit.model.bitcoin.BitcoinModel; import org.multibit.model.bitcoin.WalletData; import org.multibit.model.bitcoin.WalletInfoData; import org.multibit.model.core.CoreModel; import org.multibit.network.MultiBitService; import org.multibit.store.MultiBitWalletProtobufSerializer; import org.multibit.store.MultiBitWalletVersion; import org.multibit.store.WalletVersionException; import org.multibit.utils.DateUtils; import org.multibit.viewsystem.View; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.nio.channels.FileChannel; import java.util.*; /** * Class consolidating the File IO in MultiBit for wallets and wallet infos. * * @author jim * */ public class FileHandler { private static Logger log = LoggerFactory.getLogger(FileHandler.class); public static final String USER_PROPERTIES_FILE_NAME = "multileaf.properties"; public static final String USER_PROPERTIES_HEADER_TEXT = "multileaf"; private final Controller controller; private final BitcoinController bitcoinController; private static final int MAX_FILE_SIZE = 1024 * 1024 * 1024; // Dont read files greater than 1 gigabyte. private MultiBitWalletProtobufSerializer walletProtobufSerializer; // Nonsense bytes to fill up deleted files - these have no meaning. private static byte[] NONSENSE_BYTES = new byte[] { (byte) 0xF0, (byte) 0xA6, (byte) 0x55, (byte) 0xAA, (byte) 0x33, (byte) 0x77, (byte) 0x33, (byte) 0x37, (byte) 0x12, (byte) 0x34, (byte) 0x56, (byte) 0x78, (byte) 0xC2, (byte) 0xB3, (byte) 0xA4, (byte) 0x9A, (byte) 0x30, (byte) 0x7F, (byte) 0xE5, (byte) 0x5A, (byte) 0x23, (byte) 0x47, (byte) 0x13, (byte) 0x17, (byte) 0x15, (byte) 0x32, (byte) 0x5C, (byte) 0x77, (byte) 0xC9, (byte) 0x73, (byte) 0x04, (byte) 0x2D, (byte) 0x40, (byte) 0x0F, (byte) 0xA5, (byte) 0xA6, (byte) 0x43, (byte) 0x77, (byte) 0x33, (byte) 0x3B, (byte) 0x62, (byte) 0x34, (byte) 0xB6, (byte) 0x72, (byte) 0x32, (byte) 0xB3, (byte) 0xA4, (byte) 0x4B, (byte) 0x80, (byte) 0x7F, (byte) 0xC5, (byte) 0x43, (byte) 0x23, (byte) 0x47, (byte) 0x13, (byte) 0xB7, (byte) 0xA5, (byte) 0x32, (byte) 0xDC, (byte) 0x79, (byte) 0x19, (byte) 0xB1, (byte) 0x03, (byte) 0x9D }; private static int BULKING_UP_FACTOR = 16; private static byte[] SECURE_DELETE_FILL_BYTES = new byte[NONSENSE_BYTES.length * BULKING_UP_FACTOR]; static { // Make some SECURE_DELETE_FILL_BYTES bytes = x BULKING_UP_FACTOR the // NONSENSE just to save write time. for (int i = 0; i < BULKING_UP_FACTOR; i++) { System.arraycopy(NONSENSE_BYTES, 0, SECURE_DELETE_FILL_BYTES, NONSENSE_BYTES.length * i, NONSENSE_BYTES.length); } } public FileHandler(BitcoinController bitcoinController) { this.bitcoinController = bitcoinController; this.controller = this.bitcoinController; walletProtobufSerializer = new MultiBitWalletProtobufSerializer(); } /** * Load up a WalletData from a specified wallet file. * If the main wallet cannot be loaded, the most recent backup is tried, * followed by the next recent. * * @param walletFile * @return WalletData - the walletData for the created wallet * @throws WalletLoadException * @throws WalletVersionException */ public WalletData loadFromFile(File walletFile) throws WalletLoadException, WalletVersionException { if (walletFile == null) { return null; } String walletFilenameToUseInModel = walletFile.getAbsolutePath(); try { // See if the wallet is serialized or protobuf. WalletInfoData walletInfo; if (isWalletSerialised(walletFile)) { // Serialised wallets are no longer supported. throw new WalletLoadException("Could not load wallet '" + walletFilenameToUseInModel + "'. Serialized wallets are no longer supported."); } else { walletInfo = new WalletInfoData(walletFilenameToUseInModel, null, MultiBitWalletVersion.PROTOBUF_ENCRYPTED); } // If the wallet file is missing or empty but the backup file exists // load that instead. This indicates that the write was interrupted // (e.g. power loss). boolean useBackupWallets = ( !walletFile.exists() || walletFile.length() == 0 ); boolean walletWasLoadedSuccessfully = false; Collection<String> errorMessages = new ArrayList<String>(); Wallet wallet = null; // Try the main wallet first unless it is obviously broken. if (!useBackupWallets) { FileInputStream fileInputStream = new FileInputStream(walletFile); InputStream stream = null; try { stream = new BufferedInputStream(fileInputStream); wallet = Wallet.loadFromFileStream(stream); walletWasLoadedSuccessfully = true; } catch (WalletVersionException wve) { // We want this exception to propagate out. throw wve; } catch (Exception e) { e.printStackTrace(); String description = e.getClass().getCanonicalName() + " " + e.getMessage(); log.error(description); errorMessages.add(description); } finally { if (stream != null) { stream.close(); } fileInputStream.close(); } } if (!walletWasLoadedSuccessfully) { // If the main wallet was not loaded successfully, work out the best backup // wallets to try and load them. useBackupWallets = true; Collection<String> backupWalletsToTry = BackupManager.INSTANCE.calculateBestWalletBackups(walletFile, walletInfo); Iterator<String> iterator = backupWalletsToTry.iterator(); while (!walletWasLoadedSuccessfully && iterator.hasNext()) { String walletToTry = iterator.next(); FileInputStream fileInputStream = new FileInputStream(new File(walletToTry)); InputStream stream = null; try { stream = new BufferedInputStream(fileInputStream); wallet = Wallet.loadFromFileStream(stream); walletWasLoadedSuccessfully = true; // Mention to user that backup is being used. // Report failure to user. MessageManager.INSTANCE.addMessage(new Message(bitcoinController.getLocaliser().getString("fileHandler.walletCannotLoadUsingBackup", new String[]{walletFilenameToUseInModel, walletToTry}))); } catch (Exception e) { e.printStackTrace(); String description = e.getClass().getCanonicalName() + " " + e.getMessage(); log.error(description); errorMessages.add(description); } finally { if (stream != null) { stream.close(); } fileInputStream.close(); } } } WalletData perWalletModelData = null; if (walletWasLoadedSuccessfully) { if (walletInfo != null) { // If wallet description is only in the wallet, copy it to // the wallet info // (perhaps the user deleted/ did not copy the info file). String walletDescriptionInInfo = walletInfo.getProperty(WalletInfoData.DESCRIPTION_PROPERTY); if ((walletDescriptionInInfo == null || walletDescriptionInInfo.length() == 0) && wallet.getDescription() != null) { walletInfo.put(WalletInfoData.DESCRIPTION_PROPERTY, wallet.getDescription()); } // Check that only receiving addresses that appear in a key // appear in the wallet info. walletInfo.checkAllReceivingAddressesAppearInWallet(wallet); // Make sure the version type in the info file matches what was actually loaded. // (A backup with a different encryption type might have been used). walletInfo.setWalletVersion(wallet.getVersion()); } // Ensure that the directories for the backups of the private // keys, rolling backups and regular backups exist. BackupManager.INSTANCE.createBackupDirectories(walletFile); // Add the new wallet into the model. wallet.setNetworkParameters(bitcoinController.getModel().getNetworkParameters()); perWalletModelData = bitcoinController.getModel().addWallet(this.bitcoinController, wallet, walletFilenameToUseInModel); perWalletModelData.setWalletInfo(walletInfo); // If the backup files were used save them immediately and don't // delete any rolling backups. if (useBackupWallets) { // Wipe the wallet backup property so that the rolling // backup file will not be overwritten walletInfo.put(BitcoinModel.WALLET_BACKUP_FILE, ""); // Save the wallet immediately just to be on the safe side. savePerWalletModelData(perWalletModelData, true); } synchronized (walletInfo) { rememberFileSizesAndLastModified(new File(walletFilenameToUseInModel), walletInfo); perWalletModelData.setDirty(false); } } else { // No wallet was loaded successfully. // Wipe the rolling backup property to ensure that file wont be deleted. if (walletInfo != null) { walletInfo.put(BitcoinModel.WALLET_BACKUP_FILE, ""); } // Report failure to user. String messageText = bitcoinController.getLocaliser().getString("fileHandler.unableToLoadWalletOrBackups", new String[] {walletFilenameToUseInModel}); if (!errorMessages.isEmpty()) { StringBuilder errorMessagesAsString = new StringBuilder(); for (String errorText : errorMessages) { if (errorMessagesAsString.length()>0) { errorMessagesAsString.append("\n"); } errorMessagesAsString.append(errorText); } messageText = messageText + "\n" + bitcoinController.getLocaliser().getString("deleteWalletConfirmDialog.walletDeleteError2", new String[]{errorMessagesAsString.toString()}); } MessageManager.INSTANCE.addMessage(new Message(messageText)); } return perWalletModelData; } catch (WalletVersionException wve) { // We want this to propagate out. throw wve; } catch (Exception e) { e.printStackTrace(); log.error(e.getClass().getCanonicalName() + " " + e.getMessage()); throw new WalletLoadException(e.getClass().getCanonicalName() + " " + e.getMessage(), e); } } private boolean isWalletSerialised(File walletFile) { boolean isWalletSerialised = false; InputStream stream = null; try { // Determine what kind of wallet stream this is: Java Serialization // or protobuf format. stream = new BufferedInputStream(new FileInputStream(walletFile)); isWalletSerialised = stream.read() == 0xac && stream.read() == 0xed; } catch (FileNotFoundException e) { log.error(e.getClass().getCanonicalName() + " " + e.getMessage()); } catch (IOException e) { log.error(e.getClass().getCanonicalName() + " " + e.getMessage()); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { log.error(e.getClass().getCanonicalName() + " " + e.getMessage()); } } } return isWalletSerialised; } /** * Save the perWalletModelData to file. * * @param perWalletModelData * @param forceWrite * force the write of the perWalletModelData */ public void savePerWalletModelData(WalletData perWalletModelData, boolean forceWrite) { if (perWalletModelData == null || perWalletModelData.getWalletFilename() == null) { return; } File walletFile = new File(perWalletModelData.getWalletFilename()); WalletInfoData walletInfo = perWalletModelData.getWalletInfo(); if (walletInfo != null) { synchronized (walletInfo) { // Save the perWalletModelData if it is dirty or if forceWrite is true. if (perWalletModelData.isDirty() || forceWrite) { // Check dates and sizes of files. boolean filesHaveChanged = haveFilesChanged(perWalletModelData); if (!filesHaveChanged || forceWrite) { // Normal write of data. String walletInfoFilename = WalletInfoData.createWalletInfoFilename(perWalletModelData.getWalletFilename()); saveWalletAndWalletInfo(perWalletModelData, perWalletModelData.getWalletFilename(), walletInfoFilename); rememberFileSizesAndLastModified(walletFile, walletInfo); // The perWalletModelData is no longer dirty. perWalletModelData.setDirty(false); } else { // Write to backup files. BackupManager.INSTANCE.backupPerWalletModelData(this, perWalletModelData); } } } } return; } /** * Simply save the wallet and wallet info files. * Used for backup writes. * * @param perWalletModelData * @param walletFilename * @param walletInfoFilename */ public void saveWalletAndWalletInfoSimple(WalletData perWalletModelData, String walletFilename, String walletInfoFilename) { File walletFile = new File(walletFilename); WalletInfoData walletInfo = perWalletModelData.getWalletInfo(); FileOutputStream fileOutputStream = null; // Save the wallet file try { if (perWalletModelData.getWallet() != null) { // Wallet description is currently stored in the wallet info // file but is now available on the wallet itself. // Store the description from the wallet info in the wallet - in // the future the wallet value will be primary // and wallet infos can be deprecated. // TODO - migrate completely to use wallet description and then // deprecate value in info file. if (walletInfo != null) { String walletDescriptionInInfoFile = walletInfo.getProperty(WalletInfoData.DESCRIPTION_PROPERTY); if (walletDescriptionInInfoFile != null) { perWalletModelData.getWallet().setDescription(walletDescriptionInInfoFile); } } log.debug("Saving wallet file '" + walletFile.getAbsolutePath() + "' ..."); if (MultiBitWalletVersion.SERIALIZED == walletInfo.getWalletVersion()) { throw new WalletSaveException("Cannot save wallet '" + walletFile.getAbsolutePath() + "'. Serialized wallets are no longer supported."); } else { // See if there are any encrypted private keys - if there // are the wallet will be saved // as encrypted and the version set to PROTOBUF_ENCRYPTED. boolean walletIsActuallyEncrypted = false; Wallet wallet = perWalletModelData.getWallet(); // Check all the keys individually. for (ECKey key : wallet.getKeychain()) { if (key.isEncrypted()) { walletIsActuallyEncrypted = true; break; } } if (walletIsActuallyEncrypted) { walletInfo.setWalletVersion(MultiBitWalletVersion.PROTOBUF_ENCRYPTED); } if (MultiBitWalletVersion.PROTOBUF == walletInfo.getWalletVersion()) { // Save as a Wallet message. perWalletModelData.getWallet().saveToFile(walletFile); } else if (MultiBitWalletVersion.PROTOBUF_ENCRYPTED == walletInfo.getWalletVersion()) { fileOutputStream = new FileOutputStream(walletFile); // Save as a Wallet message with a mandatory extension // to prevent loading by older versions of multibit. walletProtobufSerializer.writeWallet(perWalletModelData.getWallet(), fileOutputStream); } else { throw new WalletVersionException("Cannot save wallet '" + perWalletModelData.getWalletFilename() + "'. Its wallet version is '" + walletInfo.getWalletVersion().toString() + "' but this version of MultiBit does not understand that format."); } } log.debug("... done saving wallet file."); } } catch (IOException ioe) { throw new WalletSaveException("Cannot save wallet '" + perWalletModelData.getWalletFilename(), ioe); } finally { if (fileOutputStream != null) { try { fileOutputStream.flush(); fileOutputStream.close(); } catch (IOException e) { throw new WalletSaveException("Cannot save wallet '" + perWalletModelData.getWalletFilename(), e); } } } // Write wallet info. walletInfo.writeToFile(walletInfoFilename, walletInfo.getWalletVersion()); } /** * To protect the wallet data, the write is in steps: 1) Create a backup * file called <wallet file name>-<yyyymmddhhmmss>.wallet and copy the * original wallet to that 2) Write the new wallet to the walletFilename 3) * Delete the old backup file 4) Make the backup file in step 1) the new * backup file * **/ private void saveWalletAndWalletInfo(WalletData perWalletModelData, String walletFilename, String walletInfoFilename) { File walletFile = new File(walletFilename); WalletInfoData walletInfo = perWalletModelData.getWalletInfo(); FileOutputStream fileOutputStream = null; // Save the wallet file try { if (perWalletModelData.getWallet() != null) { // Wallet description is currently stored in the wallet info // file but is now available on the wallet itself. // Store the description from the wallet info in the wallet - in // the future the wallet value will be primary // and wallet infos can be deprecated. // TODO - migrate completely to use wallet description and then // deprecate value in info file. if (walletInfo != null) { String walletDescriptionInInfoFile = walletInfo.getProperty(WalletInfoData.DESCRIPTION_PROPERTY); if (walletDescriptionInInfoFile != null) { perWalletModelData.getWallet().setDescription(walletDescriptionInInfoFile); } } String oldBackupFilename = perWalletModelData.getWalletInfo().getProperty(BitcoinModel.WALLET_BACKUP_FILE); File oldBackupFile = null; String newBackupFilename = null; if (null != oldBackupFilename && !"".equals(oldBackupFilename)) { oldBackupFile = new File(oldBackupFilename); } if (MultiBitWalletVersion.PROTOBUF == walletInfo.getWalletVersion() || MultiBitWalletVersion.PROTOBUF_ENCRYPTED == walletInfo.getWalletVersion()) { newBackupFilename = copyExistingWalletToBackupAndDeleteOriginal(walletFile); } log.debug("Saving wallet file '" + walletFile.getAbsolutePath() + "' ..."); if (MultiBitWalletVersion.SERIALIZED == walletInfo.getWalletVersion()) { throw new WalletSaveException("Cannot save wallet '" + walletFile.getAbsolutePath() + "'. Serialized wallets are no longer supported."); } else { // See if there are any encrypted private keys - if there // are the wallet will be saved // as encrypted and the version set to PROTOBUF_ENCRYPTED. boolean walletIsActuallyEncrypted = false; Wallet wallet = perWalletModelData.getWallet(); // Check all the keys individually. for (ECKey key : wallet.getKeychain()) { if (key.isEncrypted()) { walletIsActuallyEncrypted = true; break; } } if (walletIsActuallyEncrypted) { walletInfo.setWalletVersion(MultiBitWalletVersion.PROTOBUF_ENCRYPTED); } if (MultiBitWalletVersion.PROTOBUF == walletInfo.getWalletVersion()) { // Save as a Wallet message. perWalletModelData.getWallet().saveToFile(walletFile); } else if (MultiBitWalletVersion.PROTOBUF_ENCRYPTED == walletInfo.getWalletVersion()) { fileOutputStream = new FileOutputStream(walletFile); // Save as a Wallet message with a mandatory extension // to prevent loading by older versions of multibit. walletProtobufSerializer.writeWallet(perWalletModelData.getWallet(), fileOutputStream); } else { throw new WalletVersionException("Cannot save wallet '" + perWalletModelData.getWalletFilename() + "'. Its wallet version is '" + walletInfo.getWalletVersion().toString() + "' but this version of MultiBit does not understand that format."); } } log.debug("... done saving wallet file."); if (MultiBitWalletVersion.PROTOBUF == walletInfo.getWalletVersion() || MultiBitWalletVersion.PROTOBUF_ENCRYPTED == walletInfo.getWalletVersion()) { perWalletModelData.getWalletInfo().put(BitcoinModel.WALLET_BACKUP_FILE, newBackupFilename); // Delete the oldBackupFile unless the user has manually // opened it. boolean userHasOpenedBackupFile = false; List<WalletData> perWalletModelDataList = this.bitcoinController.getModel().getPerWalletModelDataList(); if (perWalletModelDataList != null) { for (WalletData perWalletModelDataLoop : perWalletModelDataList) { if ((oldBackupFilename != null && oldBackupFilename.equals(perWalletModelDataLoop.getWalletFilename())) || (newBackupFilename != null && newBackupFilename.equals(perWalletModelDataLoop .getWalletFilename()))) { userHasOpenedBackupFile = true; break; } } } if (!userHasOpenedBackupFile) { secureDelete(oldBackupFile); } } } } catch (IOException ioe) { throw new WalletSaveException("Cannot save wallet '" + perWalletModelData.getWalletFilename(), ioe); } finally { if (fileOutputStream != null) { try { fileOutputStream.flush(); fileOutputStream.close(); } catch (IOException e) { throw new WalletSaveException("Cannot save wallet '" + perWalletModelData.getWalletFilename(), e); } } } // Write wallet info. walletInfo.writeToFile(walletInfoFilename, walletInfo.getWalletVersion()); } /** * Backup the private keys of the active wallet to a file with name <wallet-name>-data/key-backup/<wallet * name>-yyyymmddhhmmss.key * * TODO This might be better on the BackupManager * * @param passwordToUse * @return File to which keys were backed up, or null if they were not. * @throws KeyCrypterException */ public File backupPrivateKeys(CharSequence passwordToUse) throws IOException, KeyCrypterException { File privateKeysBackupFile = null; // Only encrypted files are backed up, and they must have a non blank password. if (passwordToUse != null && passwordToUse.length() > 0) { if (controller.getModel() != null && this.bitcoinController.getModel().getActiveWalletWalletInfo() != null && this.bitcoinController.getModel().getActiveWalletWalletInfo().getWalletVersion() == MultiBitWalletVersion.PROTOBUF_ENCRYPTED) { // Save a backup copy of the private keys, encrypted with the passwordToUse. PrivateKeysHandler privateKeysHandler = new PrivateKeysHandler(this.bitcoinController.getModel() .getNetworkParameters()); String privateKeysBackupFilename = BackupManager.INSTANCE.createBackupFilename(new File(this.bitcoinController.getModel() .getActiveWalletFilename()), BackupManager.PRIVATE_KEY_BACKUP_DIRECTORY_NAME, false, false, BitcoinModel.PRIVATE_KEY_FILE_EXTENSION); privateKeysBackupFile = new File(privateKeysBackupFilename); BlockChain blockChain = null; if (this.bitcoinController.getMultiBitService() != null) { blockChain = this.bitcoinController.getMultiBitService().getChain(); } privateKeysHandler.exportPrivateKeys(privateKeysBackupFile, this.bitcoinController.getModel().getActiveWallet(), blockChain, true, passwordToUse, passwordToUse); } else { log.debug("Wallet '" + this.bitcoinController.getModel().getActiveWalletFilename() + "' private keys not backed up as not PROTOBUF_ENCRYPTED"); } } else { log.debug("Wallet '" + this.bitcoinController.getModel().getActiveWalletFilename() + "' private keys not backed up password was blank or of zero length"); } return privateKeysBackupFile; } /** * Copy an existing wallet to a backup file and delete the original. * Used in rolling backups * * @param walletFile * @return * @throws IOException */ private String copyExistingWalletToBackupAndDeleteOriginal(File walletFile) throws IOException { String newWalletBackupFilename = BackupManager.INSTANCE.createBackupFilename(walletFile, BackupManager.ROLLING_WALLET_BACKUP_DIRECTORY_NAME, false, false, BitcoinModel.WALLET_FILE_EXTENSION); File newWalletBackupFile = new File(newWalletBackupFilename); if (walletFile != null && walletFile.exists()) { FileHandler.copyFile(walletFile, newWalletBackupFile); if (walletFile.length() != newWalletBackupFile.length()) { throw new IOException("Failed to copy the existing wallet from '" + walletFile.getAbsolutePath() + "' to '" + newWalletBackupFilename + "'"); } if (!walletFile.getAbsolutePath().equals(newWalletBackupFile.getAbsolutePath())) { secureDelete(walletFile); } } return newWalletBackupFilename; } /** * Secure delete the wallet and the wallet info file. * * @param perWalletModelData */ public void deleteWalletAndWalletInfo(WalletData perWalletModelData) { if (perWalletModelData == null) { return; } File walletFile = new File(perWalletModelData.getWalletFilename()); WalletInfoData walletInfo = perWalletModelData.getWalletInfo(); String walletInfoFilenameAsString = WalletInfoData.createWalletInfoFilename(perWalletModelData.getWalletFilename()); File walletInfoFile = new File(walletInfoFilenameAsString); synchronized (walletInfo) { // See if either of the files are readonly - abort. if (!walletFile.canWrite() || !walletInfoFile.canWrite()) { throw new DeleteWalletException(controller.getLocaliser().getString("deleteWalletException.walletWasReadonly")); } // Delete the wallet info file first, then the wallet. try { FileHandler.secureDelete(walletInfoFile); FileHandler.secureDelete(walletFile); walletInfo.setDeleted(true); } catch (IOException ioe) { log.error(ioe.getClass().getCanonicalName() + " " + ioe.getMessage()); throw new DeleteWalletException(controller.getLocaliser().getString("deleteWalletException.genericCouldNotDelete", new String[] { perWalletModelData.getWalletFilename() })); } } // If the wallet was deleted, delete the model data. if (walletInfo.isDeleted()) { this.bitcoinController.getModel().remove(perWalletModelData); } return; } public boolean haveFilesChanged(WalletData perWalletModelData) { if (perWalletModelData == null || perWalletModelData.getWalletFilename() == null) { return false; } boolean haveFilesChanged = false; String walletInfoFilename = WalletInfoData.createWalletInfoFilename(perWalletModelData.getWalletFilename()); File walletInfoFile = new File(walletInfoFilename); File walletFile = new File(perWalletModelData.getWalletFilename()); WalletInfoData walletInfo = perWalletModelData.getWalletInfo(); if (walletInfo != null) { synchronized (walletInfo) { String walletFileSize = "" + walletFile.length(); String walletFileLastModified = "" + walletFile.lastModified(); String walletInfoFileSize = "" + walletInfoFile.length(); String walletInfoFileLastModified = "" + walletInfoFile.lastModified(); if (!walletFileSize.equals(walletInfo.getProperty(BitcoinModel.WALLET_FILE_SIZE))) { haveFilesChanged = true; } if (!walletFileLastModified.equals(walletInfo.getProperty(BitcoinModel.WALLET_FILE_LAST_MODIFIED))) { haveFilesChanged = true; } if (!walletInfoFileSize.equals(walletInfo.getProperty(BitcoinModel.WALLET_INFO_FILE_SIZE))) { haveFilesChanged = true; } if (haveFilesChanged) { log.debug("Result of check of whether files have changed for wallet filename " + perWalletModelData.getWalletFilename() + " was " + haveFilesChanged + "."); log.debug(BitcoinModel.WALLET_FILE_SIZE + " " + walletFileSize + " ," + BitcoinModel.WALLET_FILE_LAST_MODIFIED + " " + walletFileLastModified + " ," + BitcoinModel.WALLET_INFO_FILE_SIZE + " " + walletInfoFileSize + " ," + BitcoinModel.WALLET_INFO_FILE_LAST_MODIFIED + " " + walletInfoFileLastModified); } } } return haveFilesChanged; } /** * Keep a record of the wallet and wallet info files sizes and date last * modified. * * @param walletFile * The wallet file * @param walletInfo * The wallet info */ private void rememberFileSizesAndLastModified(File walletFile, WalletInfoData walletInfo) { // Get the files' last modified data and sizes and store them in the // wallet properties. if (walletFile == null || walletInfo == null) { return; } long walletFileSize = walletFile.length(); long walletFileLastModified = walletFile.lastModified(); String walletFilename = walletFile.getAbsolutePath(); String walletInfoFilename = WalletInfoData.createWalletInfoFilename(walletFilename); File walletInfoFile = new File(walletInfoFilename); long walletInfoFileSize = walletInfoFile.length(); long walletInfoFileLastModified = walletInfoFile.lastModified(); walletInfo.put(BitcoinModel.WALLET_FILE_SIZE, "" + walletFileSize); walletInfo.put(BitcoinModel.WALLET_FILE_LAST_MODIFIED, "" + walletFileLastModified); walletInfo.put(BitcoinModel.WALLET_INFO_FILE_SIZE, "" + walletInfoFileSize); walletInfo.put(BitcoinModel.WALLET_INFO_FILE_LAST_MODIFIED, "" + walletInfoFileLastModified); log.debug("rememberFileSizesAndLastModified: Wallet filename " + walletFilename + " , " + BitcoinModel.WALLET_FILE_SIZE + " " + walletFileSize + " ," + BitcoinModel.WALLET_FILE_LAST_MODIFIED + " " + walletFileLastModified + " ," + BitcoinModel.WALLET_INFO_FILE_SIZE + " " + walletInfoFileSize + " ," + BitcoinModel.WALLET_INFO_FILE_LAST_MODIFIED + " " + walletInfoFileLastModified); } public static void writeUserPreferences(BitcoinController bitcoinController) { final Controller controller = bitcoinController; // Save all the wallets' filenames in the user preferences. if (bitcoinController.getModel().getPerWalletModelDataList() != null) { List<WalletData> perWalletModelDataList = bitcoinController.getModel().getPerWalletModelDataList(); List<String> orderList = new ArrayList<String>(); List<String> earlyList = new ArrayList<String>(); List<String> protobuf3List = new ArrayList<String>(); for (WalletData perWalletModelData : perWalletModelDataList) { // Check if this is the initial empty WalletData if ("".equals(perWalletModelData.getWalletFilename()) || perWalletModelData.getWalletFilename() == null || perWalletModelData.getWalletInfo() == null) { continue; } // Do not save deleted wallets if (perWalletModelData.getWalletInfo().isDeleted()) { log.debug("Not writing out info about wallet '" + perWalletModelData.getWalletFilename() + "' as it has been deleted"); continue; } if (!orderList.contains(perWalletModelData.getWalletFilename())) { orderList.add(perWalletModelData.getWalletFilename()); } if (perWalletModelData.getWalletInfo().getWalletVersion() == MultiBitWalletVersion.PROTOBUF_ENCRYPTED) { if (!protobuf3List.contains(perWalletModelData.getWalletFilename())) { protobuf3List.add(perWalletModelData.getWalletFilename()); } } else if (perWalletModelData.getWalletInfo().getWalletVersion() == null || perWalletModelData.getWalletInfo().getWalletVersion() == MultiBitWalletVersion.SERIALIZED || perWalletModelData.getWalletInfo().getWalletVersion() == MultiBitWalletVersion.PROTOBUF) { if (!earlyList.contains(perWalletModelData.getWalletFilename())) { earlyList.add(perWalletModelData.getWalletFilename()); } } } int orderCount = 1; for (String walletFilename : orderList) { controller.getModel().setUserPreference(BitcoinModel.WALLET_ORDER_PREFIX + orderCount, walletFilename); orderCount++; } controller.getModel().setUserPreference(BitcoinModel.WALLET_ORDER_TOTAL, "" + orderList.size()); int earlyCount = 1; for (String walletFilename : earlyList) { controller.getModel().setUserPreference(BitcoinModel.EARLY_WALLET_FILENAME_PREFIX + earlyCount, walletFilename); earlyCount++; } controller.getModel().setUserPreference(BitcoinModel.NUMBER_OF_EARLY_WALLETS, "" + earlyList.size()); int protobuf3Count = 1; for (String walletFilename : protobuf3List) { controller.getModel().setUserPreference(BitcoinModel.PROTOBUF3_WALLET_FILENAME_PREFIX + protobuf3Count, walletFilename); protobuf3Count++; } controller.getModel().setUserPreference(BitcoinModel.NUMBER_OF_PROTOBUF3_WALLETS, "" + protobuf3List.size()); controller.getModel().setUserPreference(BitcoinModel.ACTIVE_WALLET_FILENAME, bitcoinController.getModel().getActiveWalletFilename()); } Properties userPreferences = controller.getModel().getAllUserPreferences(); // If the view is marked as also requiring a backwards compatible // numeric field write that. @SuppressWarnings("deprecation") int currentViewNumericFormat = View.toOldViewNumeric(controller.getCurrentView()); if (currentViewNumericFormat != 0) { userPreferences.put(CoreModel.SELECTED_VIEW, "" + currentViewNumericFormat); } else { // Make sure the old numeric value for a view is not in the user // properties. userPreferences.remove(CoreModel.SELECTED_VIEW); } // Write the user preference properties. OutputStream outputStream = null; try { String userPropertiesFilename; if ("".equals(controller.getApplicationDataDirectoryLocator().getApplicationDataDirectory())) { userPropertiesFilename = USER_PROPERTIES_FILE_NAME; } else { userPropertiesFilename = controller.getApplicationDataDirectoryLocator().getApplicationDataDirectory() + File.separator + USER_PROPERTIES_FILE_NAME; } outputStream = new FileOutputStream(userPropertiesFilename); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(bufferedOutputStream, "UTF8"); userPreferences.store(outputStreamWriter, USER_PROPERTIES_HEADER_TEXT); } catch (FileNotFoundException e) { log.error(e.getMessage(), e); } catch (IOException e) { log.error(e.getMessage(), e); } finally { if (outputStream != null) { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { log.error(e.getClass().getCanonicalName() + " " + e.getMessage()); } finally { outputStream = null; } } } } public static Properties loadUserPreferences(ApplicationDataDirectoryLocator applicationDataDirectoryLocator) { Properties userPreferences = new Properties(); try { String userPropertiesFilename; if ("".equals(applicationDataDirectoryLocator.getApplicationDataDirectory())) { userPropertiesFilename = USER_PROPERTIES_FILE_NAME; } else { userPropertiesFilename = applicationDataDirectoryLocator.getApplicationDataDirectory() + File.separator + USER_PROPERTIES_FILE_NAME; } InputStream inputStream = new FileInputStream(userPropertiesFilename); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF8"); userPreferences.load(inputStreamReader); } catch (FileNotFoundException e) { // Ok - may not have been created yet. } catch (IOException e) { // Ok may not be written yet. } return userPreferences; } /** * To support multiple users on the same machine, the checkpoints file is * installed into the program installation directory and is then copied to * the user's application data directory when MultiBit is first used. * * Thus each user has their own copy of the blockchain. */ public void copyCheckpointsFromInstallationDirectory(String destinationCheckpointsFilename) throws IOException { if (destinationCheckpointsFilename == null) { return; } // See if the block chain in the user's application data directory // exists. File destinationCheckpoints = new File(destinationCheckpointsFilename); if (!destinationCheckpoints.exists()) { // Work out the source checkpoints (put into the program // installation directory by the installer). File directory = new File("."); String currentWorkingDirectory = directory.getCanonicalPath(); String filePrefix = MultiBitService.getFilePrefix(); String checkpointsFilename = filePrefix + MultiBitService.CHECKPOINTS_SUFFIX; String sourceCheckpointsFilename = currentWorkingDirectory + File.separator + checkpointsFilename; File sourceBlockcheckpoints = new File(sourceCheckpointsFilename); if (sourceBlockcheckpoints.exists() && !destinationCheckpointsFilename.equals(sourceCheckpointsFilename)) { // It should exist since installer puts them in. log.info("Copying checkpoints from '" + sourceCheckpointsFilename + "' to '" + destinationCheckpointsFilename + "'"); copyFile(sourceBlockcheckpoints, destinationCheckpoints); // Check all the data was copied. long sourceLength = sourceBlockcheckpoints.length(); long destinationLength = destinationCheckpoints.length(); if (sourceLength != destinationLength) { String errorText = "Checkpoints were not copied to user's application data directory correctly.\nThe source checkpoints '" + sourceCheckpointsFilename + "' is of length " + sourceLength + "\nbut the destination checkpoints '" + destinationCheckpointsFilename + "' is of length " + destinationLength; log.error(errorText); throw new FileHandlerException(errorText); } } } } /** * To support multiple users on the same machine, the block chain is * installed into the program installation directory and is then copied to * the user's application data directory when MultiBit is first used. * * Thus each user has their own copy of the blockchain. */ public void copyBlockChainFromInstallationDirectory(String destinationBlockChainFilename, boolean alwaysOverWrite) throws IOException { if (destinationBlockChainFilename == null) { return; } // See if the block chain in the user's application data directory // exists. File destinationBlockchain = new File(destinationBlockChainFilename); if (!destinationBlockchain.exists() || alwaysOverWrite) { // Work out the source blockchain (put into the program installation // directory by the installer). File directory = new File("."); String currentWorkingDirectory = directory.getCanonicalPath(); String filePrefix = MultiBitService.getFilePrefix(); String blockchainFilename = filePrefix + MultiBitService.BLOCKCHAIN_SUFFIX; String sourceBlockchainFilename = currentWorkingDirectory + File.separator + blockchainFilename; File sourceBlockchain = new File(sourceBlockchainFilename); if (sourceBlockchain.exists() && !destinationBlockChainFilename.equals(sourceBlockchainFilename)) { // It should exist since installer puts them in. log.info("Copying blockchain from '" + sourceBlockchainFilename + "' to '" + destinationBlockChainFilename + "'"); if (alwaysOverWrite) { // Delete the existing destinationBlockchain if it exists. if (destinationBlockchain.exists()) { destinationBlockchain.delete(); } } long startTime = (DateUtils.nowUtc()).getMillis(); copyFile(sourceBlockchain, destinationBlockchain); long stopTime = (DateUtils.nowUtc()).getMillis(); log.info("Time taken to copy blockchain was " + (stopTime - startTime) + " ms."); // Check all the data was copied. long sourceLength = sourceBlockchain.length(); long destinationLength = destinationBlockchain.length(); if (sourceLength != destinationLength) { String errorText = "Blockchain was not copied to user's application data directory correctly.\nThe source blockchain '" + sourceBlockchainFilename + "' is of length " + sourceLength + "\nbut the destination blockchain '" + destinationBlockChainFilename + "' is of length " + destinationLength; log.error(errorText); throw new FileHandlerException(errorText); } } } } public static void copyFile(File sourceFile, File destinationFile) throws IOException { if (!destinationFile.exists()) { destinationFile.createNewFile(); } FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; FileChannel source = null; FileChannel destination = null; try { fileInputStream = new FileInputStream(sourceFile); source = fileInputStream.getChannel(); fileOutputStream = new FileOutputStream(destinationFile); destination = fileOutputStream.getChannel(); long transfered = 0; long bytes = source.size(); while (transfered < bytes) { transfered += destination.transferFrom(source, 0, source.size()); destination.position(transfered); } } finally { if (source != null) { source.close(); source = null; } else if (fileInputStream != null) { fileInputStream.close(); fileInputStream = null; } if (destination != null) { destination.close(); destination = null; } else if (fileOutputStream != null) { fileOutputStream.flush(); fileOutputStream.close(); } } } public static void writeFile(byte[] sourceBytes, File destinationFile) throws IOException { if (!destinationFile.exists()) { destinationFile.createNewFile(); } FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(destinationFile); fileOutputStream.write(sourceBytes); } finally { if (fileOutputStream != null) { fileOutputStream.flush(); fileOutputStream.close(); } } } public static File createTempDirectory(String filePrefix) throws IOException { final File temp; temp = File.createTempFile(filePrefix, Long.toString(System.currentTimeMillis())); if (!(temp.delete())) { throw new IOException("Could not delete temp file: " + temp.getAbsolutePath()); } if (!(temp.mkdir())) { throw new IOException("Could not create temp directory: " + temp.getAbsolutePath()); } temp.deleteOnExit(); return temp; } /** * Delete a file with an overwrite of all of the data. * * Set bit patterns are used rather than random numbers to avoid a * futex_wait_queue_me error on Linux systems (related to /dev/random usage) * * @param file * @throws IOException */ public static void secureDelete(File file) throws IOException { log.debug("Start of secureDelete"); RandomAccessFile raf = null; if (file != null && file.exists()) { try { // Prep for file delete as this can be fiddly on windows. // Make sure it is writable and any references to it are garbage // collected and finalized. file.setWritable(true); System.gc(); long length = file.length(); raf = new RandomAccessFile(file, "rws"); raf.seek(0); raf.getFilePointer(); int pos = 0; while (pos < length) { raf.write(SECURE_DELETE_FILL_BYTES); pos += SECURE_DELETE_FILL_BYTES.length; } } finally { if (raf != null) { raf.close(); raf = null; } } boolean deleteSuccess = file.delete(); log.debug("Result of delete of file '" + file.getAbsolutePath() + "' was " + deleteSuccess); } log.debug("End of secureDelete"); } public static byte[] read(File file) throws IOException { if (file == null) { throw new IllegalArgumentException("File must be provided"); } if ( file.length() > MAX_FILE_SIZE ) { throw new IOException("File '" + file.getAbsolutePath() + "' is too large to input"); } byte []buffer = new byte[(int) file.length()]; InputStream ios = null; try { ios = new FileInputStream(file); if ( ios.read(buffer) == -1 ) { throw new IOException("EOF reached while trying to read the whole file"); } } finally { try { if ( ios != null ) { ios.close(); } } catch ( IOException e) { log.error(e.getClass().getName() + " " + e.getMessage()); } } return buffer; } }
/* * Copyright 2014-2016 See AUTHORS file. * * 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.kotcrab.vis.ui.widget; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.scenes.scene2d.*; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.Window; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.utils.Align; import com.kotcrab.vis.ui.FocusManager; import com.kotcrab.vis.ui.VisUI; /** * Extends functionality of standard scene2d.ui {@link Window}. * @author Kotcrab * @see Window */ public class VisWindow extends Window { public static float FADE_TIME = 0.3f; private boolean centerOnAdd; private boolean keepWithinParent = false; private boolean fadeOutActionRunning; public VisWindow (String title) { this(title, true); getTitleLabel().setAlignment(VisUI.getDefaultTitleAlign()); } public VisWindow (String title, boolean showWindowBorder) { super(title, VisUI.getSkin(), showWindowBorder ? "default" : "noborder"); getTitleLabel().setAlignment(VisUI.getDefaultTitleAlign()); } public VisWindow (String title, String styleName) { super(title, VisUI.getSkin(), styleName); getTitleLabel().setAlignment(VisUI.getDefaultTitleAlign()); } public VisWindow (String title, WindowStyle style) { super(title, style); getTitleLabel().setAlignment(VisUI.getDefaultTitleAlign()); } @Override public void setPosition (float x, float y) { super.setPosition((int) x, (int) y); } /** * Centers this window, if it has parent it will be done instantly, if it does not have parent it will be centered when it will * be added to stage * @return true when window was centered, false when window will be centered when added to stage */ public boolean centerWindow () { Group parent = getParent(); if (parent == null) { centerOnAdd = true; return false; } else { moveToCenter(); return true; } } /** * @param centerOnAdd if true window position will be centered on screen after adding to stage * @see #centerWindow() */ public void setCenterOnAdd (boolean centerOnAdd) { this.centerOnAdd = centerOnAdd; } @Override protected void setStage (Stage stage) { super.setStage(stage); if (stage != null) { stage.setKeyboardFocus(this); //issue #10, newly created window does not acquire keyboard focus if (centerOnAdd) { centerOnAdd = false; moveToCenter(); } } } private void moveToCenter () { Stage parent = getStage(); if (parent != null) setPosition((parent.getWidth() - getWidth()) / 2, (parent.getHeight() - getHeight()) / 2); } /** * Fade outs this window, when fade out animation is completed, window is removed from Stage. Calling this for the * second time won't have any effect if previous animation is still running. */ public void fadeOut (float time) { if (fadeOutActionRunning) return; fadeOutActionRunning = true; final Touchable previousTouchable = getTouchable(); setTouchable(Touchable.disabled); Stage stage = getStage(); if (stage != null && stage.getKeyboardFocus() != null && stage.getKeyboardFocus().isDescendantOf(this)) { FocusManager.resetFocus(stage); } addAction(Actions.sequence(Actions.fadeOut(time, Interpolation.fade), new Action() { @Override public boolean act (float delta) { setTouchable(previousTouchable); remove(); getColor().a = 1f; fadeOutActionRunning = false; return true; } })); } /** @return this window for the purpose of chaining methods eg. stage.addActor(new MyWindow(stage).fadeIn(0.3f)); */ public VisWindow fadeIn (float time) { setColor(1, 1, 1, 0); addAction(Actions.fadeIn(time, Interpolation.fade)); return this; } /** Fade outs this window, when fade out animation is completed, window is removed from Stage */ public void fadeOut () { fadeOut(FADE_TIME); } /** @return this window for the purpose of chaining methods eg. stage.addActor(new MyWindow(stage).fadeIn()); */ public VisWindow fadeIn () { return fadeIn(FADE_TIME); } /** * Called by window when close button was pressed (added using {@link #addCloseButton()}) * or escape key was pressed (for close on escape {@link #closeOnEscape()} have to be called). * Default close behaviour is to fade out window, this can be changed by overriding this function. */ protected void close () { fadeOut(); } /** * Adds close button to window, next to window title. After pressing that button, {@link #close()} is called. If nothing * else was added to title table, and current title alignment is center then the title will be automatically centered. */ public void addCloseButton () { Label titleLabel = getTitleLabel(); Table titleTable = getTitleTable(); VisImageButton closeButton = new VisImageButton("close-window"); titleTable.add(closeButton).padRight(-getPadRight() + 0.7f); closeButton.addListener(new ChangeListener() { @Override public void changed (ChangeEvent event, Actor actor) { close(); } }); closeButton.addListener(new ClickListener() { @Override public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) { event.cancel(); return true; } }); if (titleLabel.getLabelAlign() == Align.center && titleTable.getChildren().size == 2) titleTable.getCell(titleLabel).padLeft(closeButton.getWidth() * 2); } /** * Will make this window close when escape key or back key was pressed. After pressing escape or back, {@link #close()} is called. * Back key is Android and iOS only */ public void closeOnEscape () { addListener(new InputListener() { @Override public boolean keyDown (InputEvent event, int keycode) { if (keycode == Keys.ESCAPE) { close(); return true; } return false; } @Override public boolean keyUp (InputEvent event, int keycode) { if (keycode == Keys.BACK) { close(); return true; } return false; } }); } public boolean isKeepWithinParent () { return keepWithinParent; } public void setKeepWithinParent (boolean keepWithinParent) { this.keepWithinParent = keepWithinParent; } @Override public void draw (Batch batch, float parentAlpha) { if (keepWithinParent && getParent() != null) { float parentWidth = getParent().getWidth(); float parentHeight = getParent().getHeight(); if (getX() < 0) setX(0); if (getRight() > parentWidth) setX(parentWidth - getWidth()); if (getY() < 0) setY(0); if (getTop() > parentHeight) setY(parentHeight - getHeight()); } super.draw(batch, parentAlpha); } }
/**************************************************************************** Copyright 2008, Colorado School of Mines and others. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ package edu.mines.jtk.util; import org.testng.annotations.Test; import static java.lang.Math.*; import static org.testng.Assert.assertEquals; import static org.testng.AssertJUnit.assertTrue; /** * Tests {@link edu.mines.jtk.util.UnitSphereSampling}. * @author Dave Hale, Colorado School of Mines * @version 2008.08.27 */ public class UnitSphereSamplingTest { @Test public void testSymmetry() { testSymmetry(8); testSymmetry(16); } @Test public void testInterpolation() { testInterpolation(16,0.0001f); } @Test public void testTriangle() { testTriangle(8); testTriangle(16); } @Test public void testTriangle1() { // This used to fail due to rounding errors when computing r and s. float[] p = {-0.82179755f,0.56977963f,0.0f}; UnitSphereSampling uss = new UnitSphereSampling(16); int i = uss.getIndex(p); int[] abc = uss.getTriangle(p); int ia = abc[0], ib = abc[1], ic = abc[2]; assertTrue(i==ia || i==ib || i==ic); } public void testWeights() { testWeights(8); testWeights(16); } public void testMaxError() { testMaxError(16,1.0f); } private static void testSymmetry(int nbits) { UnitSphereSampling uss = new UnitSphereSampling(nbits); int mi = uss.getMaxIndex(); for (int i=1,j=-i; i<=mi; ++i,j=-i) { float[] p = uss.getPoint(i); float[] q = uss.getPoint(j); assertEquals(p[0],-q[0],0.0); assertEquals(p[1],-q[1],0.0); assertEquals(p[2],-q[2],0.0); } int npoint = 10000; for (int ipoint=0; ipoint<npoint; ++ipoint) { float[] p = randomPoint(); float[] q = {-p[0],-p[1],-p[2]}; int i = uss.getIndex(p); int j = uss.getIndex(q); if (p[2]==0.0f) { assertEquals(i+j,mi+1); } else { assertEquals(-i,j); } } } private static void testInterpolation(int nbits, float error) { UnitSphereSampling uss = new UnitSphereSampling(nbits); int mi = uss.getMaxIndex(); // Tabulate function values for sampled points. int nf = 1+2*mi; float[] fi = new float[nf]; for (int i=1; i<=mi; ++i) { float[] p = uss.getPoint( i); float[] q = uss.getPoint(-i); fi[i ] = func(p[0],p[1],p[2]); fi[nf-i] = func(q[0],q[1],q[2]); } // Interpolate and track errors. float emax = 0.0f; int npoint = 10000; for (int ipoint=0; ipoint<npoint; ++ipoint) { float[] p = randomPoint(); int[] iabc = uss.getTriangle(p); float[] wabc = uss.getWeights(p,iabc); int ia = iabc[0], ib = iabc[1], ic = iabc[2]; float wa = wabc[0], wb = wabc[1], wc = wabc[2]; if (ia<0) { ia = nf+ia; ib = nf+ib; ic = nf+ic; } float fa = fi[ia], fb = fi[ib], fc = fi[ic]; float f = func(p[0],p[1],p[2]); float g = wa*fa+wb*fb+wc*fc; float e = abs(g-f); if (e>emax) { emax = e; } } assertTrue(emax<error); } private static float func(float x, float y, float z) { return 0.1f*(9.0f*x*x*x-2.0f*x*x*y+3.0f*x*y*y-4.0f*y*y*y+2.0f*z*z*z-x*y*z); } private static void testTriangle(int nbits) { UnitSphereSampling uss = new UnitSphereSampling(nbits); int npoint = 100000; for (int ipoint=0; ipoint<npoint; ++ipoint) { float[] p = randomPoint(); int i = uss.getIndex(p); int[] abc = uss.getTriangle(p); int ia = abc[0], ib = abc[1], ic = abc[2]; /* float[] q = uss.getPoint(i); float[] qa = uss.getPoint(ia); float[] qb = uss.getPoint(ib); float[] qc = uss.getPoint(ic); float d = distanceOnSphere(p,q); float da = distanceOnSphere(p,qa); float db = distanceOnSphere(p,qb); float dc = distanceOnSphere(p,qc); */ assertTrue(i==ia || i==ib || i==ic); } } private static void testWeights(int nbits) { UnitSphereSampling uss = new UnitSphereSampling(nbits); int npoint = 10; for (int ipoint=0; ipoint<npoint; ++ipoint) { float[] p = randomPoint(); int[] iabc = uss.getTriangle(p); /* int ia = iabc[0], ib = iabc[1], ic = iabc[2]; int i = uss.getIndex(p); float[] q = uss.getPoint(i); float[] qa = uss.getPoint(ia); float[] qb = uss.getPoint(ib); float[] qc = uss.getPoint(ic); */ float[] wabc = uss.getWeights(p,iabc); float wa = wabc[0], wb = wabc[1], wc = wabc[2]; assertEquals(1.0,wa+wb+wc,0.00001); // TODO: more assertions? /* trace("wa="+wa+" wb="+wb+" wc="+wc); ArrayMath.dump(p); ArrayMath.dump(qa); ArrayMath.dump(qb); ArrayMath.dump(qc); */ } } private static void testMaxError(int nbits, float error) { UnitSphereSampling uss = new UnitSphereSampling(nbits); int npoint = 100000; float dmax = 0.0f; //float[] pmax = null; //float[] qmax = null; for (int ipoint=0; ipoint<npoint; ++ipoint) { float[] p = randomPoint(); int i = uss.getIndex(p); float[] q = uss.getPoint(i); float d = distanceOnSphere(p,q); if (d>dmax) { dmax = d; //pmax = p; //qmax = q; } } /* float dmaxDegrees = (float)(dmax*180.0/PI); trace("npoint="+npoint+" dmax="+dmax+" degrees="+dmaxDegrees); trace("pmax="); ArrayMath.dump(pmax); trace("qmax="); ArrayMath.dump(qmax); */ assertTrue(dmax<error); } private static java.util.Random _random = new java.util.Random(); private static float[] randomPoint() { float x = -1.0f+2.0f*_random.nextFloat(); float y = -1.0f+2.0f*_random.nextFloat(); float z = -1.0f+2.0f*_random.nextFloat(); float f = _random.nextFloat(); if (f<0.1f) x = 0.0f; if (0.1f<=f && f<0.2f) y = 0.0f; if (0.2f<=f && f<0.3f) z = 0.0f; float s = 1.0f/(float)sqrt(x*x+y*y+z*z); return new float[]{x*s,y*s,z*s}; } private static float distanceOnSphere(float[] p, float[] q) { double x = p[0]+q[0]; double y = p[1]+q[1]; double z = p[2]+q[2]; double d = x*x+y*y+z*z; if (d==0.0) { d = PI; } else if (d==4.0) { d = 0.0; } else { d = 2.0*atan(sqrt((4.0-d)/d)); } return (float)d; //return (float)acos(p[0]*q[0]+p[1]*q[1]+p[2]*q[2]); } /* private static final boolean TRACE = true; private static void trace(String s) { if (TRACE) System.out.println(s); } */ }
/** * Copyright 2014 Atos * Contact: Atos <roman.sosa@atos.net> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package eu.atos.sla.service.rest; import java.util.Collections; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import javax.xml.bind.JAXBException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestBody; import com.sun.jersey.core.spi.factory.ResponseBuilderImpl; import com.sun.jersey.multipart.FormDataBodyPart; import com.sun.jersey.multipart.FormDataMultiPart; import eu.atos.sla.dao.IAgreementDAO; import eu.atos.sla.dao.IProviderDAO; import eu.atos.sla.dao.ITemplateDAO; import eu.atos.sla.datamodel.IAgreement; import eu.atos.sla.datamodel.IProvider; import eu.atos.sla.datamodel.ITemplate; import eu.atos.sla.datamodel.bean.Provider; import eu.atos.sla.enforcement.IEnforcementService; import eu.atos.sla.modaclouds.ViolationSubscriber; import eu.atos.sla.parser.IParser; import eu.atos.sla.parser.ParserException; import eu.atos.sla.parser.data.wsag.Agreement; import eu.atos.sla.parser.data.wsag.Template; import eu.atos.sla.service.rest.exception.InternalException; import eu.atos.sla.service.rest.helpers.AgreementHelperE; import eu.atos.sla.service.rest.helpers.TemplateHelperE; import eu.atos.sla.service.rest.helpers.exception.DBExistsHelperException; import eu.atos.sla.service.rest.helpers.exception.DBMissingHelperException; import eu.atos.sla.service.rest.helpers.exception.InternalHelperException; import eu.atos.sla.service.rest.helpers.exception.ParserHelperException; import eu.seaclouds.platform.sla.generator.AgreementGenerator; import eu.seaclouds.platform.sla.generator.JaxbUtils; import eu.seaclouds.platform.sla.generator.RulesExtractor; import eu.seaclouds.platform.sla.generator.SlaGeneratorException; import eu.seaclouds.platform.sla.generator.SlaInfo; import eu.seaclouds.platform.sla.generator.TemplateGenerator; import eu.seaclouds.platform.sla.generator.SlaInfo.SlaInfoBuilder; @Path("seaclouds") @Component @Transactional public class SeacloudsRest extends AbstractSLARest { private static Logger logger = LoggerFactory.getLogger(SeacloudsRest.class); private SlaInfoBuilder slaInfoBuilder = new SlaInfoBuilder(new RulesExtractor()); /* * Base of monitoring manager /metrics endpoint. Something like http://localhost:8170/v1/metrics */ @Value("${MONITOR_METRICS_URL}") private String metricsUrl; /* * Base of SLA Core component. Something like http://localhost:8080/sla-service */ @Value("${SLA_URL}") private String slaUrl; @Autowired private AgreementHelperE agreementHelper; @Autowired private TemplateHelperE templateHelper; @Autowired private IProviderDAO providerDAO; @Autowired private IAgreementDAO agreementDAO; @Autowired private ITemplateDAO templateDAO; @Resource(name="agreementXmlParser") IParser<Agreement> agreementParser; @Resource(name="templateXmlParser") IParser<Template> templateParser; @Autowired private IEnforcementService enforcementService; @GET public String getRoot() { return "root"; } @GET @Path("config") @Produces(MediaType.TEXT_PLAIN) public String getConfig(@Context UriInfo uriInfo) { StringBuilder s = new StringBuilder(); String slaUrl = getSlaUrl(this.slaUrl, uriInfo); String metricsUrl = getMetricsBaseUrl("", this.metricsUrl); s.append("SLA_URL="); s.append(slaUrl); s.append("\n"); s.append("METRICS_URL="); s.append(metricsUrl); s.append("\n"); return s.toString(); } @POST @Path("templates") @Produces(MediaType.APPLICATION_JSON) public Response createTemplate(@Context UriInfo uriInfo, @RequestBody String dam) throws InternalException { try { logger.info("\nPOST /seaclouds/templates\n{}", dam); SlaInfo slaInfo = slaInfoBuilder.build(dam); String id = createTemplate(slaInfo, true); String location = buildResourceLocation(uriInfo.getAbsolutePath().toString(), id); Map<String, String> map = Collections.singletonMap("id", id); ResponseBuilderImpl builder = new ResponseBuilderImpl(); builder.header("location", location); builder.status(HttpStatus.CREATED.value()); builder.entity(map); return builder.build(); } catch (DBMissingHelperException e) { throw new InternalException(e.getMessage(), e); } catch (DBExistsHelperException e) { throw new InternalException(e.getMessage(), e); } catch (InternalHelperException e) { throw new InternalException(e.getMessage(), e); } catch (ParserHelperException e) { throw new InternalException(e.getMessage(), e); } catch (JAXBException e) { throw new InternalException(e.getMessage(), e); } } public String createTemplate(SlaInfo slaInfo, boolean persist) throws JAXBException, DBMissingHelperException, DBExistsHelperException, InternalHelperException, ParserHelperException { TemplateGenerator g = new TemplateGenerator(slaInfo); Template wsagTemplate = g.generate(); String providerUuid = wsagTemplate.getContext().getAgreementResponder(); String wsagSerialized = JaxbUtils.toString(wsagTemplate); String id = "<random-uuid>"; if (persist) { getOrCreateProvider(providerUuid); id = templateHelper.createTemplate(wsagTemplate, wsagSerialized); } return id; } @POST @Path("agreements") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response createAgreement(@Context UriInfo uriInfo, FormDataMultiPart form, @QueryParam("agreementId") String agreementId) throws ParserException, InternalException { FormDataBodyPart slaPart = form.getField("sla"); String slaPayload = slaPart.getValueAs(String.class); String id; String location = null; Agreement a = agreementParser.getWsagObject(slaPayload); try { String providerUuid = a.getContext().getAgreementResponder(); IProvider provider = providerDAO.getByUUID(providerUuid); if (provider == null) { provider = new Provider(); provider.setUuid(providerUuid); provider.setName(providerUuid); provider = providerDAO.save(provider); } id = agreementHelper.createAgreement(a, slaPayload, agreementId != null? agreementId : ""); location = buildResourceLocation(uriInfo.getAbsolutePath().toString() ,id); } catch (DBMissingHelperException e) { throw new InternalException(e.getMessage()); } catch (DBExistsHelperException e) { throw new InternalException(e.getMessage()); } catch (InternalHelperException e) { throw new InternalException(e.getMessage()); } catch (ParserHelperException e) { throw new InternalException(e.getMessage()); } logger.debug("EndOf createAgreement"); return buildResponsePOST( HttpStatus.CREATED, createMessage(HttpStatus.CREATED, id, "The agreement has been stored successfully in the SLA Repository Database. " + "It has location " + location), location); } @POST @Path("commands/rulesready") public String rulesReady(@Context UriInfo uriInfo, @QueryParam("agreementId") String agreementId) { String slaUrl = getSlaUrl(this.slaUrl, uriInfo); String metricsUrl = getMetricsBaseUrl("", this.metricsUrl); /* * Endpoint of the metrics receiver. Something like http://localhost:8080/metrics */ String slaMetricsUrl = getSlaMetricsUrl(slaUrl); if (agreementId == null) { agreementId = ""; } List<IAgreement> agreements = "".equals(agreementId)? agreementDAO.getAll() : Collections.singletonList(agreementDAO.getByAgreementId(agreementId)); ViolationSubscriber subscriber = new ViolationSubscriber(metricsUrl, slaMetricsUrl); for (IAgreement agreement : agreements) { subscriber.subscribeObserver(agreement); enforcementService.startEnforcement(agreement.getAgreementId()); } return ""; } @GET @Path("commands/fromtemplate") @Produces(MediaType.APPLICATION_XML) public Response generateAgreementFromTemplate(@QueryParam("templateId") String templateId) throws JAXBException { ITemplate template = templateDAO.getByUuid(templateId); Template wsagTemplate; try { wsagTemplate = templateParser.getWsagObject(template.getText()); } catch (ParserException e) { throw new SlaGeneratorException(e.getMessage(), e); } Agreement wsagAgreement = new AgreementGenerator(wsagTemplate).generate(); logger.debug(JaxbUtils.toString(wsagAgreement)); /* * TODO: Finish */ return null; } /** * Returns base url of the sla core. * * If the SLA_URL env var is set, returns that value. Else, get the base url from the * context of the current REST call. This second value may be wrong because this base url must * be the value that the MonitoringPlatform needs to use to connect to the SLA Core. */ private String getSlaUrl(String envSlaUrl, UriInfo uriInfo) { String baseUrl = uriInfo.getBaseUri().toString(); if (envSlaUrl == null) { envSlaUrl = ""; } String result = ("".equals(envSlaUrl))? baseUrl : envSlaUrl; logger.debug("getSlaUrl(env={}, supplied={}) = {}", envSlaUrl, baseUrl, result); return result; } /** * Return base url of the metrics endpoint of the Monitoring Platform. * * If an url is supplied in the request, use that value. Else, use MODACLOUDS_METRICS_URL env var is set. */ private String getMetricsBaseUrl(String suppliedBaseUrl, String envBaseUrl) { String result = ("".equals(suppliedBaseUrl))? envBaseUrl : suppliedBaseUrl; logger.debug("getMetricsBaseUrl(env={}, supplied={}) = {}", envBaseUrl, suppliedBaseUrl, result); return result; } private String getSlaMetricsUrl(String slaUrl) { return slaUrl + "/metrics"; } private IProvider getOrCreateProvider(String providerUuid) { IProvider provider = providerDAO.getByUUID(providerUuid); if (provider == null) { provider = new Provider(); provider.setUuid(providerUuid); provider.setName(providerUuid); provider = providerDAO.save(provider); } return provider; } }
/* Copyright 2016 Google Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.api.codegen.transformer.java; import com.google.api.codegen.config.FlatteningConfig; import com.google.api.codegen.config.GapicProductConfig; import com.google.api.codegen.config.GrpcStreamingConfig.GrpcStreamingType; import com.google.api.codegen.config.InterfaceModel; import com.google.api.codegen.config.MethodConfig; import com.google.api.codegen.config.MethodModel; import com.google.api.codegen.config.ProtoApiModel; import com.google.api.codegen.config.ProtoInterfaceModel; import com.google.api.codegen.config.ProtoMethodModel; import com.google.api.codegen.gapic.GapicCodePathMapper; import com.google.api.codegen.metacode.InitCodeContext; import com.google.api.codegen.metacode.InitCodeContext.InitCodeOutputType; import com.google.api.codegen.transformer.FileHeaderTransformer; import com.google.api.codegen.transformer.GapicInterfaceContext; import com.google.api.codegen.transformer.GapicMethodContext; import com.google.api.codegen.transformer.ImportTypeTable; import com.google.api.codegen.transformer.InitCodeTransformer; import com.google.api.codegen.transformer.InterfaceContext; import com.google.api.codegen.transformer.MockServiceTransformer; import com.google.api.codegen.transformer.ModelToViewTransformer; import com.google.api.codegen.transformer.ModelTypeTable; import com.google.api.codegen.transformer.StandardImportSectionTransformer; import com.google.api.codegen.transformer.StaticLangApiMethodTransformer; import com.google.api.codegen.transformer.SurfaceNamer; import com.google.api.codegen.transformer.TestCaseTransformer; import com.google.api.codegen.util.SymbolTable; import com.google.api.codegen.util.java.JavaTypeTable; import com.google.api.codegen.util.testing.StandardValueProducer; import com.google.api.codegen.util.testing.TestValueGenerator; import com.google.api.codegen.util.testing.ValueProducer; import com.google.api.codegen.viewmodel.ClientMethodType; import com.google.api.codegen.viewmodel.FileHeaderView; import com.google.api.codegen.viewmodel.ViewModel; import com.google.api.codegen.viewmodel.testing.ClientTestClassView; import com.google.api.codegen.viewmodel.testing.ClientTestFileView; import com.google.api.codegen.viewmodel.testing.MockServiceImplFileView; import com.google.api.codegen.viewmodel.testing.MockServiceImplView; import com.google.api.codegen.viewmodel.testing.MockServiceView; import com.google.api.codegen.viewmodel.testing.SmokeTestClassView; import com.google.api.codegen.viewmodel.testing.TestCaseView; import com.google.api.tools.framework.model.Model; import java.util.ArrayList; import java.util.List; /** A subclass of ModelToViewTransformer which translates model into API tests in Java. */ public class JavaGapicSurfaceTestTransformer implements ModelToViewTransformer { private static String UNIT_TEST_TEMPLATE_FILE = "java/test.snip"; private static String SMOKE_TEST_TEMPLATE_FILE = "java/smoke_test.snip"; private static String MOCK_SERVICE_FILE = "java/mock_service.snip"; private static String MOCK_SERVICE_IMPL_FILE = "java/mock_service_impl.snip"; private final GapicCodePathMapper pathMapper; private final InitCodeTransformer initCodeTransformer = new InitCodeTransformer(); private final FileHeaderTransformer fileHeaderTransformer = new FileHeaderTransformer(new StandardImportSectionTransformer()); private final ValueProducer valueProducer = new StandardValueProducer(); private final TestValueGenerator valueGenerator = new TestValueGenerator(valueProducer); private final MockServiceTransformer mockServiceTransformer = new MockServiceTransformer(); private final TestCaseTransformer testCaseTransformer = new TestCaseTransformer(valueProducer); public JavaGapicSurfaceTestTransformer(GapicCodePathMapper javaPathMapper) { this.pathMapper = javaPathMapper; } @Override public List<String> getTemplateFileNames() { List<String> fileNames = new ArrayList<>(); fileNames.add(UNIT_TEST_TEMPLATE_FILE); fileNames.add(SMOKE_TEST_TEMPLATE_FILE); fileNames.add(MOCK_SERVICE_IMPL_FILE); fileNames.add(MOCK_SERVICE_FILE); return fileNames; } @Override public List<ViewModel> transform(Model model, GapicProductConfig productConfig) { List<ViewModel> views = new ArrayList<>(); ProtoApiModel apiModel = new ProtoApiModel(model); for (ProtoInterfaceModel apiInterface : apiModel.getInterfaces(productConfig)) { GapicInterfaceContext context = createContext(apiInterface, productConfig); views.add(createUnitTestFileView(context)); if (context.getInterfaceConfig().getSmokeTestConfig() != null) { context = createContext(apiInterface, productConfig); views.add(createSmokeTestClassView(context)); } } for (InterfaceModel apiInterface : mockServiceTransformer.getGrpcInterfacesToMock(apiModel, productConfig)) { GapicInterfaceContext context = createContext(apiInterface, productConfig); views.add(createMockServiceImplFileView(context)); context = createContext(apiInterface, productConfig); views.add(createMockServiceView(context)); } return views; } ///////////////////////////////////// Smoke Test /////////////////////////////////////// private SmokeTestClassView createSmokeTestClassView(GapicInterfaceContext context) { String outputPath = pathMapper.getOutputPath( context.getInterfaceModel().getFullName(), context.getProductConfig()); SurfaceNamer namer = context.getNamer(); String name = namer.getSmokeTestClassName(context.getInterfaceConfig()); SmokeTestClassView.Builder testClass = createSmokeTestClassViewBuilder(context); testClass.name(name); testClass.outputPath(namer.getSourceFilePath(outputPath, name)); return testClass.build(); } /** * Package-private * * <p>A helper method that creates a partially initialized builder that can be customized and * build the smoke test class view later. */ SmokeTestClassView.Builder createSmokeTestClassViewBuilder(GapicInterfaceContext context) { addSmokeTestImports(context); // TODO(andrealin): The SmokeTestConfig should return a MethodModel, instead of creating one here. MethodModel method = new ProtoMethodModel(context.getInterfaceConfig().getSmokeTestConfig().getMethod()); SurfaceNamer namer = context.getNamer(); FlatteningConfig flatteningGroup = testCaseTransformer.getSmokeTestFlatteningGroup( context.getMethodConfig(method), context.getInterfaceConfig().getSmokeTestConfig()); GapicMethodContext methodContext = context.asFlattenedMethodContext(method, flatteningGroup); SmokeTestClassView.Builder testClass = SmokeTestClassView.newBuilder(); // TODO: we need to remove testCaseView after we switch to use apiMethodView for smoke test TestCaseView testCaseView = testCaseTransformer.createSmokeTestCaseView(methodContext); testClass.apiSettingsClassName(namer.getApiSettingsClassName(context.getInterfaceConfig())); testClass.apiClassName(namer.getApiWrapperClassName(context.getInterfaceConfig())); testClass.templateFileName(SMOKE_TEST_TEMPLATE_FILE); // TODO: Java needs to be refactored to use ApiMethodView instead testClass.apiMethod( new StaticLangApiMethodTransformer().generateFlattenedMethod(methodContext)); testClass.method(testCaseView); testClass.requireProjectId( testCaseTransformer.requireProjectIdInSmokeTest( testCaseView.initCode(), context.getNamer())); // Imports must be done as the last step to catch all imports. FileHeaderView fileHeader = fileHeaderTransformer.generateFileHeader(context); testClass.fileHeader(fileHeader); return testClass; } ///////////////////////////////////// Unit Test ///////////////////////////////////////// private ClientTestFileView createUnitTestFileView(GapicInterfaceContext context) { addUnitTestImports(context); String outputPath = pathMapper.getOutputPath(context.getInterface().getFullName(), context.getProductConfig()); SurfaceNamer namer = context.getNamer(); String name = namer.getUnitTestClassName(context.getInterfaceConfig()); ClientTestClassView.Builder testClass = ClientTestClassView.newBuilder(); testClass.apiSettingsClassName(namer.getApiSettingsClassName(context.getInterfaceConfig())); testClass.apiClassName(namer.getApiWrapperClassName(context.getInterfaceConfig())); testClass.name(name); testClass.testCases(createTestCaseViews(context)); testClass.apiHasLongRunningMethods(context.getInterfaceConfig().hasLongRunningOperations()); testClass.mockServices( mockServiceTransformer.createMockServices( context.getNamer(), context.getApiModel(), context.getProductConfig())); testClass.missingDefaultServiceAddress( !context.getInterfaceConfig().hasDefaultServiceAddress()); testClass.missingDefaultServiceScopes(!context.getInterfaceConfig().hasDefaultServiceScopes()); ClientTestFileView.Builder testFile = ClientTestFileView.newBuilder(); testFile.testClass(testClass.build()); testFile.outputPath(namer.getSourceFilePath(outputPath, name)); testFile.templateFileName(UNIT_TEST_TEMPLATE_FILE); // Imports must be done as the last step to catch all imports. FileHeaderView fileHeader = fileHeaderTransformer.generateFileHeader(context); testFile.fileHeader(fileHeader); return testFile.build(); } private List<TestCaseView> createTestCaseViews(GapicInterfaceContext context) { ArrayList<TestCaseView> testCaseViews = new ArrayList<>(); SymbolTable testNameTable = new SymbolTable(); for (MethodModel method : context.getSupportedMethods()) { MethodConfig methodConfig = context.getMethodConfig(method); if (methodConfig.isGrpcStreaming()) { if (methodConfig.getGrpcStreamingType() == GrpcStreamingType.ClientStreaming) { //TODO: Add unit test generation for ClientStreaming methods // Issue: https://github.com/googleapis/toolkit/issues/946 continue; } addGrpcStreamingTestImports(context, methodConfig.getGrpcStreamingType()); GapicMethodContext methodContext = context.asRequestMethodContext(method); InitCodeContext initCodeContext = initCodeTransformer.createRequestInitCodeContext( methodContext, new SymbolTable(), methodConfig.getRequiredFieldConfigs(), InitCodeOutputType.SingleObject, valueGenerator); testCaseViews.add( testCaseTransformer.createTestCaseView( methodContext, testNameTable, initCodeContext, ClientMethodType.CallableMethod)); } else if (methodConfig.isFlattening()) { ClientMethodType clientMethodType; if (methodConfig.isPageStreaming()) { clientMethodType = ClientMethodType.PagedFlattenedMethod; } else if (methodConfig.isLongRunningOperation()) { clientMethodType = ClientMethodType.AsyncOperationFlattenedMethod; } else { clientMethodType = ClientMethodType.FlattenedMethod; } for (FlatteningConfig flatteningGroup : methodConfig.getFlatteningConfigs()) { GapicMethodContext methodContext = context.asFlattenedMethodContext(method, flatteningGroup); InitCodeContext initCodeContext = initCodeTransformer.createRequestInitCodeContext( methodContext, new SymbolTable(), flatteningGroup.getFlattenedFieldConfigs().values(), InitCodeOutputType.FieldList, valueGenerator); testCaseViews.add( testCaseTransformer.createTestCaseView( methodContext, testNameTable, initCodeContext, clientMethodType)); } } else { // TODO: Add support of non-flattening method // Github issue: https://github.com/googleapis/toolkit/issues/393 System.err.println( "Non-flattening method test is not supported yet for " + method.getSimpleName()); } } return testCaseViews; } ///////////////////////////////////// Mock Service ///////////////////////////////////////// private MockServiceView createMockServiceView(InterfaceContext context) { addMockServiceImports(context); SurfaceNamer namer = context.getNamer(); String outputPath = pathMapper.getOutputPath( context.getInterfaceModel().getFullName(), context.getProductConfig()); String name = namer.getMockServiceClassName(context.getInterfaceModel()); MockServiceView.Builder mockService = MockServiceView.newBuilder(); mockService.name(name); mockService.serviceImplClassName(namer.getMockGrpcServiceImplName(context.getInterfaceModel())); mockService.outputPath(namer.getSourceFilePath(outputPath, name)); mockService.templateFileName(MOCK_SERVICE_FILE); // Imports must be done as the last step to catch all imports. FileHeaderView fileHeader = fileHeaderTransformer.generateFileHeader(context); mockService.fileHeader(fileHeader); return mockService.build(); } private MockServiceImplFileView createMockServiceImplFileView(InterfaceContext context) { addMockServiceImplImports(context); SurfaceNamer namer = context.getNamer(); String outputPath = pathMapper.getOutputPath( context.getInterfaceModel().getFullName(), context.getProductConfig()); String name = namer.getMockGrpcServiceImplName(context.getInterfaceModel()); String grpcClassName = context .getImportTypeTable() .getAndSaveNicknameFor(namer.getGrpcServiceClassName(context.getInterfaceModel())); MockServiceImplFileView.Builder mockServiceImplFile = MockServiceImplFileView.newBuilder(); mockServiceImplFile.serviceImpl( MockServiceImplView.newBuilder() .name(name) .grpcClassName(grpcClassName) .grpcMethods(mockServiceTransformer.createMockGrpcMethodViews(context)) .build()); mockServiceImplFile.outputPath(namer.getSourceFilePath(outputPath, name)); mockServiceImplFile.templateFileName(MOCK_SERVICE_IMPL_FILE); // Imports must be done as the last step to catch all imports. FileHeaderView fileHeader = fileHeaderTransformer.generateFileHeader(context); mockServiceImplFile.fileHeader(fileHeader); return mockServiceImplFile.build(); } /////////////////////////////////// General Helpers ////////////////////////////////////// /** Package-private */ GapicInterfaceContext createContext( InterfaceModel apiInterface, GapicProductConfig productConfig) { ModelTypeTable typeTable = new ModelTypeTable( new JavaTypeTable(productConfig.getPackageName()), new JavaModelTypeNameConverter(productConfig.getPackageName())); return GapicInterfaceContext.create( apiInterface, productConfig, typeTable, new JavaSurfaceNamer(productConfig.getPackageName(), productConfig.getPackageName()), JavaFeatureConfig.newBuilder() .enableStringFormatFunctions(productConfig.getResourceNameMessageConfigs().isEmpty()) .build()); } /////////////////////////////////// Imports ////////////////////////////////////// private void addUnitTestImports(InterfaceContext context) { ImportTypeTable typeTable = context.getImportTypeTable(); typeTable.saveNicknameFor("com.google.api.gax.core.NoCredentialsProvider"); typeTable.saveNicknameFor("com.google.api.gax.rpc.InvalidArgumentException"); typeTable.saveNicknameFor("com.google.api.gax.grpc.GrpcTransportProvider"); typeTable.saveNicknameFor("com.google.api.gax.grpc.GrpcStatusCode"); typeTable.saveNicknameFor("com.google.api.gax.grpc.testing.MockGrpcService"); typeTable.saveNicknameFor("com.google.api.gax.grpc.testing.MockServiceHelper"); typeTable.saveNicknameFor("com.google.common.collect.Lists"); typeTable.saveNicknameFor("com.google.protobuf.GeneratedMessageV3"); typeTable.saveNicknameFor("io.grpc.Status"); typeTable.saveNicknameFor("io.grpc.StatusRuntimeException"); typeTable.saveNicknameFor("java.io.IOException"); typeTable.saveNicknameFor("java.util.ArrayList"); typeTable.saveNicknameFor("java.util.Arrays"); typeTable.saveNicknameFor("java.util.concurrent.ExecutionException"); typeTable.saveNicknameFor("java.util.List"); typeTable.saveNicknameFor("java.util.Objects"); typeTable.saveNicknameFor("org.junit.After"); typeTable.saveNicknameFor("org.junit.AfterClass"); typeTable.saveNicknameFor("org.junit.Assert"); typeTable.saveNicknameFor("org.junit.Before"); typeTable.saveNicknameFor("org.junit.BeforeClass"); typeTable.saveNicknameFor("org.junit.Test"); if (context.getInterfaceConfig().hasPageStreamingMethods()) { typeTable.saveNicknameFor("com.google.api.gax.core.PagedListResponse"); } if (context.getInterfaceConfig().hasLongRunningOperations()) { typeTable.saveNicknameFor("com.google.protobuf.Any"); } } /** package-private */ void addSmokeTestImports(InterfaceContext context) { ImportTypeTable typeTable = context.getImportTypeTable(); typeTable.saveNicknameFor("java.util.logging.Level"); typeTable.saveNicknameFor("java.util.logging.Logger"); typeTable.saveNicknameFor("java.util.List"); typeTable.saveNicknameFor("java.util.Arrays"); typeTable.saveNicknameFor("com.google.common.collect.Lists"); typeTable.saveNicknameFor("com.google.api.gax.core.PagedListResponse"); typeTable.saveNicknameFor("org.apache.commons.lang.builder.ReflectionToStringBuilder"); typeTable.saveNicknameFor("org.apache.commons.lang.builder.ToStringStyle"); typeTable.saveNicknameFor("org.apache.commons.cli.CommandLine"); typeTable.saveNicknameFor("org.apache.commons.cli.DefaultParser"); typeTable.saveNicknameFor("org.apache.commons.cli.HelpFormatter"); typeTable.saveNicknameFor("org.apache.commons.cli.Option"); typeTable.saveNicknameFor("org.apache.commons.cli.Options"); } private void addMockServiceImplImports(InterfaceContext context) { ImportTypeTable typeTable = context.getImportTypeTable(); typeTable.saveNicknameFor("java.util.ArrayList"); typeTable.saveNicknameFor("java.util.List"); typeTable.saveNicknameFor("java.util.LinkedList"); typeTable.saveNicknameFor("java.util.Queue"); typeTable.saveNicknameFor("com.google.common.collect.Lists"); typeTable.saveNicknameFor("com.google.protobuf.GeneratedMessageV3"); typeTable.saveNicknameFor("io.grpc.stub.StreamObserver"); } private void addMockServiceImports(InterfaceContext context) { ImportTypeTable typeTable = context.getImportTypeTable(); typeTable.saveNicknameFor("java.util.List"); typeTable.saveNicknameFor("com.google.api.gax.grpc.testing.MockGrpcService"); typeTable.saveNicknameFor("com.google.protobuf.GeneratedMessageV3"); typeTable.saveNicknameFor("io.grpc.ServerServiceDefinition"); } private void addGrpcStreamingTestImports( GapicInterfaceContext context, GrpcStreamingType streamingType) { ModelTypeTable typeTable = context.getImportTypeTable(); typeTable.saveNicknameFor("com.google.api.gax.grpc.testing.MockStreamObserver"); typeTable.saveNicknameFor("com.google.api.gax.rpc.ApiStreamObserver"); switch (streamingType) { case BidiStreaming: typeTable.saveNicknameFor("com.google.api.gax.rpc.BidiStreamingCallable"); break; case ClientStreaming: typeTable.saveNicknameFor("com.google.api.gax.rpc.ClientStreamingCallable"); break; case ServerStreaming: typeTable.saveNicknameFor("com.google.api.gax.rpc.ServerStreamingCallable"); break; default: throw new IllegalArgumentException("Invalid streaming type: " + streamingType); } } }
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.cherrypick; import com.intellij.dvcs.DvcsUtil; import com.intellij.dvcs.cherrypick.VcsCherryPicker; import com.intellij.notification.Notification; import com.intellij.notification.NotificationListener; import com.intellij.openapi.application.AccessToken; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.AbstractVcsHelper; import com.intellij.openapi.vcs.FilePath; import com.intellij.openapi.vcs.VcsKey; import com.intellij.openapi.vcs.VcsNotifier; import com.intellij.openapi.vcs.changes.*; import com.intellij.openapi.vcs.history.VcsRevisionNumber; import com.intellij.openapi.vcs.merge.MergeDialogCustomizer; import com.intellij.openapi.vcs.update.RefreshVFsSynchronously; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Consumer; import com.intellij.util.Function; import com.intellij.util.containers.ContainerUtil; import com.intellij.vcs.log.Hash; import com.intellij.vcs.log.VcsFullCommitDetails; import com.intellij.vcs.log.VcsLog; import com.intellij.vcs.log.util.VcsUserUtil; import git4idea.GitLocalBranch; import git4idea.GitUtil; import git4idea.GitVcs; import git4idea.commands.Git; import git4idea.commands.GitCommandResult; import git4idea.commands.GitSimpleEventDetector; import git4idea.commands.GitUntrackedFilesOverwrittenByOperationDetector; import git4idea.config.GitVcsSettings; import git4idea.merge.GitConflictResolver; import git4idea.repo.GitRepository; import git4idea.repo.GitRepositoryManager; import git4idea.util.GitUntrackedFilesHelper; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.event.HyperlinkEvent; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import static com.intellij.dvcs.DvcsUtil.getShortRepositoryName; import static com.intellij.openapi.util.text.StringUtil.pluralize; import static git4idea.commands.GitSimpleEventDetector.Event.CHERRY_PICK_CONFLICT; import static git4idea.commands.GitSimpleEventDetector.Event.LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK; public class GitCherryPicker extends VcsCherryPicker { private static final Logger LOG = Logger.getInstance(GitCherryPicker.class); @NotNull private final Project myProject; @NotNull private final Git myGit; @NotNull private final ChangeListManager myChangeListManager; @NotNull private final GitRepositoryManager myRepositoryManager; public GitCherryPicker(@NotNull Project project, @NotNull Git git) { myProject = project; myGit = git; myChangeListManager = ChangeListManager.getInstance(myProject); myRepositoryManager = GitUtil.getRepositoryManager(myProject); } public void cherryPick(@NotNull List<VcsFullCommitDetails> commits) { Map<GitRepository, List<VcsFullCommitDetails>> commitsInRoots = DvcsUtil.groupCommitsByRoots(myRepositoryManager, commits); LOG.info("Cherry-picking commits: " + toString(commitsInRoots)); List<GitCommitWrapper> successfulCommits = ContainerUtil.newArrayList(); List<GitCommitWrapper> alreadyPicked = ContainerUtil.newArrayList(); AccessToken token = DvcsUtil.workingTreeChangeStarted(myProject); try { for (Map.Entry<GitRepository, List<VcsFullCommitDetails>> entry : commitsInRoots.entrySet()) { GitRepository repository = entry.getKey(); boolean result = cherryPick(repository, entry.getValue(), successfulCommits, alreadyPicked); repository.update(); if (!result) { return; } } notifyResult(successfulCommits, alreadyPicked); } finally { DvcsUtil.workingTreeChangeFinished(myProject, token); } } @NotNull private static String toString(@NotNull final Map<GitRepository, List<VcsFullCommitDetails>> commitsInRoots) { return StringUtil.join(commitsInRoots.keySet(), new Function<GitRepository, String>() { @Override public String fun(@NotNull GitRepository repository) { String commits = StringUtil.join(commitsInRoots.get(repository), new Function<VcsFullCommitDetails, String>() { @Override public String fun(VcsFullCommitDetails details) { return details.getId().asString(); } }, ", "); return getShortRepositoryName(repository) + ": [" + commits + "]"; } }, "; "); } // return true to continue with other roots, false to break execution private boolean cherryPick(@NotNull GitRepository repository, @NotNull List<VcsFullCommitDetails> commits, @NotNull List<GitCommitWrapper> successfulCommits, @NotNull List<GitCommitWrapper> alreadyPicked) { for (VcsFullCommitDetails commit : commits) { GitSimpleEventDetector conflictDetector = new GitSimpleEventDetector(CHERRY_PICK_CONFLICT); GitSimpleEventDetector localChangesOverwrittenDetector = new GitSimpleEventDetector(LOCAL_CHANGES_OVERWRITTEN_BY_CHERRY_PICK); GitUntrackedFilesOverwrittenByOperationDetector untrackedFilesDetector = new GitUntrackedFilesOverwrittenByOperationDetector(repository.getRoot()); boolean autoCommit = isAutoCommit(); GitCommandResult result = myGit.cherryPick(repository, commit.getId().asString(), autoCommit, conflictDetector, localChangesOverwrittenDetector, untrackedFilesDetector); GitCommitWrapper commitWrapper = new GitCommitWrapper(commit); if (result.success()) { if (autoCommit) { successfulCommits.add(commitWrapper); } else { boolean committed = updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(repository, commitWrapper, successfulCommits, alreadyPicked); if (!committed) { notifyCommitCancelled(commitWrapper, successfulCommits); return false; } } } else if (conflictDetector.hasHappened()) { boolean mergeCompleted = new CherryPickConflictResolver(myProject, myGit, repository.getRoot(), commit.getId().asString(), VcsUserUtil.getShortPresentation(commit.getAuthor()), commit.getSubject()).merge(); if (mergeCompleted) { boolean committed = updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(repository, commitWrapper, successfulCommits, alreadyPicked); if (!committed) { notifyCommitCancelled(commitWrapper, successfulCommits); return false; } } else { updateChangeListManager(commit); notifyConflictWarning(repository, commitWrapper, successfulCommits); return false; } } else if (untrackedFilesDetector.wasMessageDetected()) { String description = commitDetails(commitWrapper) + "<br/>Some untracked working tree files would be overwritten by cherry-pick.<br/>" + "Please move, remove or add them before you can cherry-pick. <a href='view'>View them</a>"; description += getSuccessfulCommitDetailsIfAny(successfulCommits); GitUntrackedFilesHelper.notifyUntrackedFilesOverwrittenBy(myProject, repository.getRoot(), untrackedFilesDetector.getRelativeFilePaths(), "cherry-pick", description); return false; } else if (localChangesOverwrittenDetector.hasHappened()) { notifyError("Your local changes would be overwritten by cherry-pick.<br/>Commit your changes or stash them to proceed.", commitWrapper, successfulCommits); return false; } else if (isNothingToCommitMessage(result)) { alreadyPicked.add(commitWrapper); return true; } else { notifyError(result.getErrorOutputAsHtmlString(), commitWrapper, successfulCommits); return false; } } return true; } private static boolean isNothingToCommitMessage(@NotNull GitCommandResult result) { if (!result.getErrorOutputAsJoinedString().isEmpty()) { return false; } String stdout = result.getOutputAsJoinedString(); return stdout.contains("nothing to commit") || stdout.contains("previous cherry-pick is now empty"); } private boolean updateChangeListManagerShowCommitDialogAndRemoveChangeListOnSuccess(@NotNull GitRepository repository, @NotNull GitCommitWrapper commit, @NotNull List<GitCommitWrapper> successfulCommits, @NotNull List<GitCommitWrapper> alreadyPicked) { CherryPickData data = updateChangeListManager(commit.getCommit()); if (data == null) { alreadyPicked.add(commit); return true; } boolean committed = showCommitDialogAndWaitForCommit(repository, commit, data.myChangeList, data.myCommitMessage); if (committed) { myChangeListManager.removeChangeList(data.myChangeList); successfulCommits.add(commit); return true; } return false; } private void notifyConflictWarning(@NotNull GitRepository repository, @NotNull GitCommitWrapper commit, @NotNull List<GitCommitWrapper> successfulCommits) { NotificationListener resolveLinkListener = new ResolveLinkListener(myProject, myGit, repository.getRoot(), commit.getCommit().getId().toShortString(), VcsUserUtil.getShortPresentation(commit.getCommit().getAuthor()), commit.getSubject()); String description = commitDetails(commit) + "<br/>Unresolved conflicts remain in the working tree. <a href='resolve'>Resolve them.<a/>"; description += getSuccessfulCommitDetailsIfAny(successfulCommits); VcsNotifier.getInstance(myProject).notifyImportantWarning("Cherry-picked with conflicts", description, resolveLinkListener); } private void notifyCommitCancelled(@NotNull GitCommitWrapper commit, @NotNull List<GitCommitWrapper> successfulCommits) { if (successfulCommits.isEmpty()) { // don't notify about cancelled commit. Notify just in the case when there were already successful commits in the queue. return; } String description = commitDetails(commit); description += getSuccessfulCommitDetailsIfAny(successfulCommits); VcsNotifier.getInstance(myProject).notifyMinorWarning("Cherry-pick cancelled", description, null); } @Nullable private CherryPickData updateChangeListManager(@NotNull final VcsFullCommitDetails commit) { Collection<Change> changes = commit.getChanges(); RefreshVFsSynchronously.updateChanges(changes); final String commitMessage = createCommitMessage(commit); final Collection<FilePath> paths = ChangesUtil.getPaths(changes); LocalChangeList changeList = createChangeListAfterUpdate(commit, paths, commitMessage); return changeList == null ? null : new CherryPickData(changeList, commitMessage); } @Nullable private LocalChangeList createChangeListAfterUpdate(@NotNull final VcsFullCommitDetails commit, @NotNull final Collection<FilePath> paths, @NotNull final String commitMessage) { final CountDownLatch waiter = new CountDownLatch(1); final AtomicReference<LocalChangeList> changeList = new AtomicReference<LocalChangeList>(); ApplicationManager.getApplication().invokeAndWait(new Runnable() { @Override public void run() { myChangeListManager.invokeAfterUpdate(new Runnable() { public void run() { changeList.set(createChangeListIfThereAreChanges(commit, commitMessage)); waiter.countDown(); } }, InvokeAfterUpdateMode.SILENT_CALLBACK_POOLED, "Cherry-pick", new Consumer<VcsDirtyScopeManager>() { public void consume(VcsDirtyScopeManager vcsDirtyScopeManager) { vcsDirtyScopeManager.filePathsDirty(paths, null); } }, ModalityState.NON_MODAL); } }, ModalityState.NON_MODAL); try { boolean success = waiter.await(100, TimeUnit.SECONDS); if (!success) { LOG.error("Couldn't await for changelist manager refresh"); } } catch (InterruptedException e) { LOG.error(e); return null; } return changeList.get(); } @NotNull private static String createCommitMessage(@NotNull VcsFullCommitDetails commit) { return commit.getFullMessage() + "\n(cherry picked from commit " + commit.getId().toShortString() + ")"; } private boolean showCommitDialogAndWaitForCommit(@NotNull final GitRepository repository, @NotNull final GitCommitWrapper commit, @NotNull final LocalChangeList changeList, @NotNull final String commitMessage) { final AtomicBoolean commitSucceeded = new AtomicBoolean(); final Semaphore sem = new Semaphore(0); ApplicationManager.getApplication().invokeAndWait(new Runnable() { @Override public void run() { try { cancelCherryPick(repository); Collection<Change> changes = commit.getCommit().getChanges(); boolean commitNotCancelled = AbstractVcsHelper.getInstance(myProject).commitChanges(changes, changeList, commitMessage, new CommitResultHandler() { @Override public void onSuccess(@NotNull String commitMessage) { commit.setActualSubject(commitMessage); commitSucceeded.set(true); sem.release(); } @Override public void onFailure() { commitSucceeded.set(false); sem.release(); } }); if (!commitNotCancelled) { commitSucceeded.set(false); sem.release(); } } catch (Throwable t) { LOG.error(t); commitSucceeded.set(false); sem.release(); } } }, ModalityState.NON_MODAL); // need additional waiting, because commitChanges is asynchronous try { sem.acquire(); } catch (InterruptedException e) { LOG.error(e); return false; } return commitSucceeded.get(); } /** * We control the cherry-pick workflow ourselves + we want to use partial commits ('git commit --only'), which is prohibited during * cherry-pick, i.e. until the CHERRY_PICK_HEAD exists. */ private void cancelCherryPick(@NotNull GitRepository repository) { if (isAutoCommit()) { removeCherryPickHead(repository); } } private void removeCherryPickHead(@NotNull GitRepository repository) { File cherryPickHeadFile = repository.getRepositoryFiles().getCherryPickHead(); final VirtualFile cherryPickHead = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(cherryPickHeadFile); if (cherryPickHead != null && cherryPickHead.exists()) { ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { try { cherryPickHead.delete(this); } catch (IOException e) { // if CHERRY_PICK_HEAD is not deleted, the partial commit will fail, and the user will be notified anyway. // So here we just log the fact. It is happens relatively often, maybe some additional solution will follow. LOG.error(e); } } }); } else { LOG.info("Cancel cherry-pick in " + repository.getPresentableUrl() + ": no CHERRY_PICK_HEAD found"); } } private void notifyError(@NotNull String content, @NotNull GitCommitWrapper failedCommit, @NotNull List<GitCommitWrapper> successfulCommits) { String description = commitDetails(failedCommit) + "<br/>" + content; description += getSuccessfulCommitDetailsIfAny(successfulCommits); VcsNotifier.getInstance(myProject).notifyError("Cherry-pick failed", description); } @NotNull private static String getSuccessfulCommitDetailsIfAny(@NotNull List<GitCommitWrapper> successfulCommits) { String description = ""; if (!successfulCommits.isEmpty()) { description += "<hr/>However cherry-pick succeeded for the following " + pluralize("commit", successfulCommits.size()) + ":<br/>"; description += getCommitsDetails(successfulCommits); } return description; } private void notifyResult(@NotNull List<GitCommitWrapper> successfulCommits, @NotNull List<GitCommitWrapper> alreadyPicked) { if (alreadyPicked.isEmpty()) { VcsNotifier.getInstance(myProject).notifySuccess("Cherry-pick successful", getCommitsDetails(successfulCommits)); } else if (!successfulCommits.isEmpty()) { String title = String.format("Cherry-picked %d commits from %d", successfulCommits.size(), successfulCommits.size() + alreadyPicked.size()); String description = getCommitsDetails(successfulCommits) + "<hr/>" + formAlreadyPickedDescription(alreadyPicked, true); VcsNotifier.getInstance(myProject).notifySuccess(title, description); } else { VcsNotifier.getInstance(myProject).notifyImportantWarning("Nothing to cherry-pick", formAlreadyPickedDescription(alreadyPicked, false)); } } @NotNull private static String formAlreadyPickedDescription(@NotNull List<GitCommitWrapper> alreadyPicked, boolean but) { String hashes = StringUtil.join(alreadyPicked, new Function<GitCommitWrapper, String>() { @Override public String fun(GitCommitWrapper commit) { return commit.getCommit().getId().toShortString(); } }, ", "); if (but) { String wasnt = alreadyPicked.size() == 1 ? "wasn't" : "weren't"; String it = alreadyPicked.size() == 1 ? "it" : "them"; return String.format("%s %s picked, because all changes from %s have already been applied.", hashes, wasnt, it); } return String.format("All changes from %s have already been applied", hashes); } @NotNull private static String getCommitsDetails(@NotNull List<GitCommitWrapper> successfulCommits) { String description = ""; for (GitCommitWrapper commit : successfulCommits) { description += commitDetails(commit) + "<br/>"; } return description.substring(0, description.length() - "<br/>".length()); } @NotNull private static String commitDetails(@NotNull GitCommitWrapper commit) { return commit.getCommit().getId().toShortString() + " " + commit.getOriginalSubject(); } @Nullable private LocalChangeList createChangeListIfThereAreChanges(@NotNull VcsFullCommitDetails commit, @NotNull String commitMessage) { Collection<Change> originalChanges = commit.getChanges(); if (originalChanges.isEmpty()) { LOG.info("Empty commit " + commit.getId()); return null; } if (noChangesAfterCherryPick(originalChanges)) { LOG.info("No changes after cherry-picking " + commit.getId()); return null; } String changeListName = createNameForChangeList(commitMessage, 0).replace('\n', ' '); LocalChangeList createdChangeList = ((ChangeListManagerEx)myChangeListManager).addChangeList(changeListName, commitMessage, commit); LocalChangeList actualChangeList = moveChanges(originalChanges, createdChangeList); if (actualChangeList != null && !actualChangeList.getChanges().isEmpty()) { return createdChangeList; } LOG.warn("No changes were moved to the changelist. Changes from commit: " + originalChanges + "\nAll changes: " + myChangeListManager.getAllChanges()); myChangeListManager.removeChangeList(createdChangeList); return null; } private boolean noChangesAfterCherryPick(@NotNull Collection<Change> originalChanges) { final Collection<Change> allChanges = myChangeListManager.getAllChanges(); return !ContainerUtil.exists(originalChanges, new Condition<Change>() { @Override public boolean value(Change change) { return allChanges.contains(change); } }); } @Nullable private LocalChangeList moveChanges(@NotNull Collection<Change> originalChanges, @NotNull final LocalChangeList targetChangeList) { // 1. We have to listen to CLM changes, because moveChangesTo is asynchronous // 2. We have to collect the real target change list, because the original target list (passed to moveChangesTo) is not updated in time. final CountDownLatch moveChangesWaiter = new CountDownLatch(1); final AtomicReference<LocalChangeList> resultingChangeList = new AtomicReference<LocalChangeList>(); ChangeListAdapter listener = new ChangeListAdapter() { @Override public void changesMoved(Collection<Change> changes, ChangeList fromList, ChangeList toList) { if (toList instanceof LocalChangeList && targetChangeList.getId().equals(((LocalChangeList)toList).getId())) { resultingChangeList.set((LocalChangeList)toList); moveChangesWaiter.countDown(); } } }; try { myChangeListManager.addChangeListListener(listener); myChangeListManager.moveChangesTo(targetChangeList, originalChanges.toArray(new Change[originalChanges.size()])); boolean success = moveChangesWaiter.await(100, TimeUnit.SECONDS); if (!success) { LOG.error("Couldn't await for changes move."); } return resultingChangeList.get(); } catch (InterruptedException e) { LOG.error(e); return null; } finally { myChangeListManager.removeChangeListListener(listener); } } @NotNull private String createNameForChangeList(@NotNull String proposedName, int step) { for (LocalChangeList list : myChangeListManager.getChangeLists()) { if (list.getName().equals(nameWithStep(proposedName, step))) { return createNameForChangeList(proposedName, step + 1); } } return nameWithStep(proposedName, step); } private static String nameWithStep(String name, int step) { return step == 0 ? name : name + "-" + step; } @NotNull @Override public VcsKey getSupportedVcs() { return GitVcs.getKey(); } @NotNull @Override public String getActionTitle() { return "Cherry-Pick"; } private boolean isAutoCommit() { return GitVcsSettings.getInstance(myProject).isAutoCommitOnCherryPick(); } @Override public boolean isEnabled(@NotNull VcsLog log, @NotNull Map<VirtualFile, List<Hash>> commits) { if (commits.isEmpty()) { return false; } for (VirtualFile root : commits.keySet()) { GitRepository repository = myRepositoryManager.getRepositoryForRoot(root); if (repository == null) { return false; } for (Hash commit : commits.get(root)) { GitLocalBranch currentBranch = repository.getCurrentBranch(); Collection<String> containingBranches = log.getContainingBranches(commit, root); if (currentBranch != null && containingBranches != null && containingBranches.contains(currentBranch.getName())) { // already is contained in the current branch return false; } } } return true; } private static class CherryPickData { @NotNull private final LocalChangeList myChangeList; @NotNull private final String myCommitMessage; private CherryPickData(@NotNull LocalChangeList list, @NotNull String message) { myChangeList = list; myCommitMessage = message; } } private static class CherryPickConflictResolver extends GitConflictResolver { public CherryPickConflictResolver(@NotNull Project project, @NotNull Git git, @NotNull VirtualFile root, @NotNull String commitHash, @NotNull String commitAuthor, @NotNull String commitMessage) { super(project, git, Collections.singleton(root), makeParams(commitHash, commitAuthor, commitMessage)); } private static Params makeParams(String commitHash, String commitAuthor, String commitMessage) { Params params = new Params(); params.setErrorNotificationTitle("Cherry-picked with conflicts"); params.setMergeDialogCustomizer(new CherryPickMergeDialogCustomizer(commitHash, commitAuthor, commitMessage)); return params; } @Override protected void notifyUnresolvedRemain() { // we show a [possibly] compound notification after cherry-picking all commits. } } private static class ResolveLinkListener implements NotificationListener { @NotNull private final Project myProject; @NotNull private final Git myGit; @NotNull private final VirtualFile myRoot; @NotNull private final String myHash; @NotNull private final String myAuthor; @NotNull private final String myMessage; public ResolveLinkListener(@NotNull Project project, @NotNull Git git, @NotNull VirtualFile root, @NotNull String commitHash, @NotNull String commitAuthor, @NotNull String commitMessage) { myProject = project; myGit = git; myRoot = root; myHash = commitHash; myAuthor = commitAuthor; myMessage = commitMessage; } @Override public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) { if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { if (event.getDescription().equals("resolve")) { new CherryPickConflictResolver(myProject, myGit, myRoot, myHash, myAuthor, myMessage).mergeNoProceed(); } } } } private static class CherryPickMergeDialogCustomizer extends MergeDialogCustomizer { private String myCommitHash; private String myCommitAuthor; private String myCommitMessage; public CherryPickMergeDialogCustomizer(String commitHash, String commitAuthor, String commitMessage) { myCommitHash = commitHash; myCommitAuthor = commitAuthor; myCommitMessage = commitMessage; } @Override public String getMultipleFileMergeDescription(@NotNull Collection<VirtualFile> files) { return "<html>Conflicts during cherry-picking commit <code>" + myCommitHash + "</code> made by " + myCommitAuthor + "<br/>" + "<code>\"" + myCommitMessage + "\"</code></html>"; } @Override public String getLeftPanelTitle(@NotNull VirtualFile file) { return "Local changes"; } @Override public String getRightPanelTitle(@NotNull VirtualFile file, VcsRevisionNumber revisionNumber) { return "<html>Changes from cherry-pick <code>" + myCommitHash + "</code>"; } } /** * This class is needed to hold both the original GitCommit, and the commit message which could be changed by the user. * Only the subject of the commit message is needed. */ private static class GitCommitWrapper { @NotNull private final VcsFullCommitDetails myOriginalCommit; @NotNull private String myActualSubject; private GitCommitWrapper(@NotNull VcsFullCommitDetails commit) { myOriginalCommit = commit; myActualSubject = commit.getSubject(); } @NotNull public String getSubject() { return myActualSubject; } public void setActualSubject(@NotNull String actualSubject) { myActualSubject = actualSubject; } @NotNull public VcsFullCommitDetails getCommit() { return myOriginalCommit; } public String getOriginalSubject() { return myOriginalCommit.getSubject(); } } }
/* * Copyright (C) 2011, 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.android.bandwidthtest; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo.State; import android.net.NetworkStats; import android.net.NetworkStats.Entry; import android.net.TrafficStats; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Environment; import android.os.Process; import android.os.SystemClock; import android.telephony.TelephonyManager; import android.test.InstrumentationTestCase; import android.test.suitebuilder.annotation.LargeTest; import android.util.Log; import com.android.bandwidthtest.util.BandwidthTestUtil; import com.android.bandwidthtest.util.ConnectionUtil; import java.io.File; /** * Test that downloads files from a test server and reports the bandwidth metrics collected. */ public class BandwidthTest extends InstrumentationTestCase { private static final String LOG_TAG = "BandwidthTest"; private final static String PROF_LABEL = "PROF_"; private final static String PROC_LABEL = "PROC_"; private final static int INSTRUMENTATION_IN_PROGRESS = 2; private final static String BASE_DIR = Environment.getExternalStorageDirectory().getAbsolutePath(); private final static String TMP_FILENAME = "tmp.dat"; // Download 10.486 * 106 bytes (+ headers) from app engine test server. private final int FILE_SIZE = 10485613; private Context mContext; private ConnectionUtil mConnectionUtil; private TelephonyManager mTManager; private int mUid; private String mSsid; private String mTestServer; private String mDeviceId; private BandwidthTestRunner mRunner; @Override protected void setUp() throws Exception { super.setUp(); mRunner = (BandwidthTestRunner) getInstrumentation(); mSsid = mRunner.mSsid; mTestServer = mRunner.mTestServer; mContext = mRunner.getTargetContext(); mConnectionUtil = new ConnectionUtil(mContext); mConnectionUtil.initialize(); Log.v(LOG_TAG, "Initialized mConnectionUtil"); mUid = Process.myUid(); mTManager = (TelephonyManager)mContext.getSystemService(Context.TELEPHONY_SERVICE); mDeviceId = mTManager.getDeviceId(); } @Override protected void tearDown() throws Exception { mConnectionUtil.cleanUp(); super.tearDown(); } /** * Ensure that downloading on wifi reports reasonable stats. */ @LargeTest public void testWifiDownload() throws Exception { mConnectionUtil.wifiTestInit(); assertTrue("Could not connect to wifi!", setDeviceWifiAndAirplaneMode(mSsid)); downloadFile(); } /** * Ensure that downloading on mobile reports reasonable stats. */ @LargeTest public void testMobileDownload() throws Exception { // As part of the setup we disconnected from wifi; make sure we are connected to mobile and // that we have data. assertTrue("Do not have mobile data!", hasMobileData()); downloadFile(); } /** * Helper method that downloads a file using http connection from a test server and reports the * data usage stats to instrumentation out. */ protected void downloadFile() throws Exception { NetworkStats pre_test_stats = fetchDataFromProc(mUid); String ts = Long.toString(System.currentTimeMillis()); String targetUrl = BandwidthTestUtil.buildDownloadUrl( mTestServer, FILE_SIZE, mDeviceId, ts); TrafficStats.startDataProfiling(mContext); File tmpSaveFile = new File(BASE_DIR + File.separator + TMP_FILENAME); assertTrue(BandwidthTestUtil.DownloadFromUrl(targetUrl, tmpSaveFile)); NetworkStats prof_stats = TrafficStats.stopDataProfiling(mContext); Log.d(LOG_TAG, prof_stats.toString()); NetworkStats post_test_stats = fetchDataFromProc(mUid); NetworkStats proc_stats = post_test_stats.subtract(pre_test_stats); // Output measurements to instrumentation out, so that it can be compared to that of // the server. Bundle results = new Bundle(); results.putString("device_id", mDeviceId); results.putString("timestamp", ts); results.putInt("size", FILE_SIZE); addStatsToResults(PROF_LABEL, prof_stats, results, mUid); addStatsToResults(PROC_LABEL, proc_stats, results, mUid); getInstrumentation().sendStatus(INSTRUMENTATION_IN_PROGRESS, results); // Clean up. assertTrue(cleanUpFile(tmpSaveFile)); } /** * Ensure that uploading on wifi reports reasonable stats. */ @LargeTest public void testWifiUpload() throws Exception { mConnectionUtil.wifiTestInit(); assertTrue(setDeviceWifiAndAirplaneMode(mSsid)); uploadFile(); } /** * Ensure that uploading on wifi reports reasonable stats. */ @LargeTest public void testMobileUpload() throws Exception { assertTrue(hasMobileData()); uploadFile(); } /** * Helper method that downloads a test file to upload. The stats reported to instrumentation out * only include upload stats. */ protected void uploadFile() throws Exception { // Download a file from the server. String ts = Long.toString(System.currentTimeMillis()); String targetUrl = BandwidthTestUtil.buildDownloadUrl( mTestServer, FILE_SIZE, mDeviceId, ts); File tmpSaveFile = new File(BASE_DIR + File.separator + TMP_FILENAME); assertTrue(BandwidthTestUtil.DownloadFromUrl(targetUrl, tmpSaveFile)); ts = Long.toString(System.currentTimeMillis()); NetworkStats pre_test_stats = fetchDataFromProc(mUid); TrafficStats.startDataProfiling(mContext); assertTrue(BandwidthTestUtil.postFileToServer(mTestServer, mDeviceId, ts, tmpSaveFile)); NetworkStats prof_stats = TrafficStats.stopDataProfiling(mContext); Log.d(LOG_TAG, prof_stats.toString()); NetworkStats post_test_stats = fetchDataFromProc(mUid); NetworkStats proc_stats = post_test_stats.subtract(pre_test_stats); // Output measurements to instrumentation out, so that it can be compared to that of // the server. Bundle results = new Bundle(); results.putString("device_id", mDeviceId); results.putString("timestamp", ts); results.putInt("size", FILE_SIZE); addStatsToResults(PROF_LABEL, prof_stats, results, mUid); addStatsToResults(PROC_LABEL, proc_stats, results, mUid); getInstrumentation().sendStatus(INSTRUMENTATION_IN_PROGRESS, results); // Clean up. assertTrue(cleanUpFile(tmpSaveFile)); } /** * We want to make sure that if we use wifi and the Download Manager to download stuff, * accounting still goes to the app making the call and that the numbers still make sense. */ @LargeTest public void testWifiDownloadWithDownloadManager() throws Exception { mConnectionUtil.wifiTestInit(); assertTrue(setDeviceWifiAndAirplaneMode(mSsid)); downloadFileUsingDownloadManager(); } /** * We want to make sure that if we use mobile data and the Download Manager to download stuff, * accounting still goes to the app making the call and that the numbers still make sense. */ @LargeTest public void testMobileDownloadWithDownloadManager() throws Exception { assertTrue(hasMobileData()); downloadFileUsingDownloadManager(); } /** * Helper method that downloads a file from a test server using the download manager and reports * the stats to instrumentation out. */ protected void downloadFileUsingDownloadManager() throws Exception { // If we are using the download manager, then the data that is written to /proc/uid_stat/ // is accounted against download manager's uid, since it uses pre-ICS API. int downloadManagerUid = mConnectionUtil.downloadManagerUid(); assertTrue(downloadManagerUid >= 0); NetworkStats pre_test_stats = fetchDataFromProc(downloadManagerUid); // start profiling TrafficStats.startDataProfiling(mContext); String ts = Long.toString(System.currentTimeMillis()); String targetUrl = BandwidthTestUtil.buildDownloadUrl( mTestServer, FILE_SIZE, mDeviceId, ts); Log.v(LOG_TAG, "Download url: " + targetUrl); File tmpSaveFile = new File(BASE_DIR + File.separator + TMP_FILENAME); assertTrue(mConnectionUtil.startDownloadAndWait(targetUrl, 500000)); NetworkStats prof_stats = TrafficStats.stopDataProfiling(mContext); NetworkStats post_test_stats = fetchDataFromProc(downloadManagerUid); NetworkStats proc_stats = post_test_stats.subtract(pre_test_stats); Log.d(LOG_TAG, prof_stats.toString()); // Output measurements to instrumentation out, so that it can be compared to that of // the server. Bundle results = new Bundle(); results.putString("device_id", mDeviceId); results.putString("timestamp", ts); results.putInt("size", FILE_SIZE); addStatsToResults(PROF_LABEL, prof_stats, results, mUid); // remember to use download manager uid for proc stats addStatsToResults(PROC_LABEL, proc_stats, results, downloadManagerUid); getInstrumentation().sendStatus(INSTRUMENTATION_IN_PROGRESS, results); // Clean up. assertTrue(cleanUpFile(tmpSaveFile)); } /** * Fetch network data from /proc/uid_stat/uid * * @return populated {@link NetworkStats} */ public NetworkStats fetchDataFromProc(int uid) { String root_filepath = "/proc/uid_stat/" + uid + "/"; File rcv_stat = new File (root_filepath + "tcp_rcv"); int rx = BandwidthTestUtil.parseIntValueFromFile(rcv_stat); File snd_stat = new File (root_filepath + "tcp_snd"); int tx = BandwidthTestUtil.parseIntValueFromFile(snd_stat); NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1); stats.addValues(NetworkStats.IFACE_ALL, uid, NetworkStats.SET_DEFAULT, NetworkStats.TAG_NONE, rx, 0, tx, 0, 0); return stats; } /** * Turn on Airplane mode and connect to the wifi. * * @param ssid of the wifi to connect to * @return true if we successfully connected to a given network. */ public boolean setDeviceWifiAndAirplaneMode(String ssid) { mConnectionUtil.setAirplaneMode(mContext, true); assertTrue(mConnectionUtil.connectToWifi(ssid)); assertTrue(mConnectionUtil.waitForWifiState(WifiManager.WIFI_STATE_ENABLED, ConnectionUtil.LONG_TIMEOUT)); assertTrue(mConnectionUtil.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED, ConnectionUtil.LONG_TIMEOUT)); return mConnectionUtil.hasData(); } /** * Helper method to make sure we are connected to mobile data. * * @return true if we successfully connect to mobile data. */ public boolean hasMobileData() { assertTrue(mConnectionUtil.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.CONNECTED, ConnectionUtil.LONG_TIMEOUT)); assertTrue("Not connected to mobile", mConnectionUtil.isConnectedToMobile()); assertFalse("Still connected to wifi.", mConnectionUtil.isConnectedToWifi()); return mConnectionUtil.hasData(); } /** * Output the {@link NetworkStats} to Instrumentation out. * * @param label to attach to this given stats. * @param stats {@link NetworkStats} to add. * @param results {@link Bundle} to be added to. * @param uid for which to report the results. */ public void addStatsToResults(String label, NetworkStats stats, Bundle results, int uid){ if (results == null || results.isEmpty()) { Log.e(LOG_TAG, "Empty bundle provided."); return; } Entry totalStats = null; for (int i = 0; i < stats.size(); ++i) { Entry statsEntry = stats.getValues(i, null); // We are only interested in the all inclusive stats. if (statsEntry.tag != 0) { continue; } // skip stats for other uids if (statsEntry.uid != uid) { continue; } if (totalStats == null || statsEntry.set == NetworkStats.SET_ALL) { totalStats = statsEntry; } else { totalStats.rxBytes += statsEntry.rxBytes; totalStats.txBytes += statsEntry.txBytes; } } // Output merged stats to bundle. results.putInt(label + "uid", totalStats.uid); results.putLong(label + "tx", totalStats.txBytes); results.putLong(label + "rx", totalStats.rxBytes); } /** * Remove file if it exists. * @param file {@link File} to delete. * @return true if successfully deleted the file. */ private boolean cleanUpFile(File file) { if (file.exists()) { return file.delete(); } return true; } }
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.find.impl; import com.intellij.BundleBase; import com.intellij.find.*; import com.intellij.find.findInProject.FindInProjectManager; import com.intellij.icons.AllIcons; import com.intellij.ide.DataManager; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.util.ProgressWrapper; import com.intellij.openapi.progress.util.TooManyUsagesStatus; import com.intellij.openapi.project.DumbServiceImpl; import com.intellij.openapi.project.IndexNotReadyException; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.LibraryOrderEntry; import com.intellij.openapi.roots.OrderEntry; import com.intellij.openapi.roots.OrderRootType; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.libraries.Library; import com.intellij.openapi.util.Condition; import com.intellij.openapi.util.Conditions; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.*; import com.intellij.psi.*; import com.intellij.psi.search.*; import com.intellij.ui.content.Content; import com.intellij.usageView.UsageInfo; import com.intellij.usageView.UsageViewManager; import com.intellij.usages.ConfigurableUsageTarget; import com.intellij.usages.FindUsagesProcessPresentation; import com.intellij.usages.UsageView; import com.intellij.usages.UsageViewPresentation; import com.intellij.util.Function; import com.intellij.util.PatternUtil; import com.intellij.util.Processor; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.*; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class FindInProjectUtil { private static final int USAGES_PER_READ_ACTION = 100; private FindInProjectUtil() {} public static void setDirectoryName(@NotNull FindModel model, @NotNull DataContext dataContext) { PsiElement psiElement = null; Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project != null && !DumbServiceImpl.getInstance(project).isDumb()) { try { psiElement = CommonDataKeys.PSI_ELEMENT.getData(dataContext); } catch (IndexNotReadyException ignore) {} } String directoryName = null; if (psiElement instanceof PsiDirectory) { directoryName = ((PsiDirectory)psiElement).getVirtualFile().getPresentableUrl(); } if (directoryName == null && psiElement instanceof PsiDirectoryContainer) { final PsiDirectory[] directories = ((PsiDirectoryContainer)psiElement).getDirectories(); directoryName = directories.length == 1 ? directories[0].getVirtualFile().getPresentableUrl():null; } if (directoryName == null) { VirtualFile virtualFile = CommonDataKeys.VIRTUAL_FILE.getData(dataContext); if (virtualFile != null && virtualFile.isDirectory()) directoryName = virtualFile.getPresentableUrl(); } Module module = LangDataKeys.MODULE_CONTEXT.getData(dataContext); if (module != null) { model.setModuleName(module.getName()); } // model contains previous find in path settings // apply explicit settings from context if (module != null) { model.setModuleName(module.getName()); } Editor editor = CommonDataKeys.EDITOR.getData(dataContext); if (model.getModuleName() == null || editor == null) { if (directoryName != null) { model.setDirectoryName(directoryName); model.setCustomScope(false); // to select "Directory: " radio button } } // set project scope if we have no other settings model.setProjectScope(model.getDirectoryName() == null && model.getModuleName() == null && !model.isCustomScope()); } /** @deprecated to remove in IDEA 2018 */ @Nullable public static PsiDirectory getPsiDirectory(@NotNull FindModel findModel, @NotNull Project project) { VirtualFile directory = getDirectory(findModel); return directory == null ? null : PsiManager.getInstance(project).findDirectory(directory); } @Nullable public static VirtualFile getDirectory(@NotNull FindModel findModel) { String directoryName = findModel.getDirectoryName(); if (findModel.isProjectScope() || StringUtil.isEmptyOrSpaces(directoryName)) { return null; } String path = FileUtil.toSystemIndependentName(directoryName); VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(path); if (virtualFile == null || !virtualFile.isDirectory()) { virtualFile = null; @SuppressWarnings("deprecation") VirtualFileSystem[] fileSystems = ApplicationManager.getApplication().getComponents(VirtualFileSystem.class); for (VirtualFileSystem fs : fileSystems) { if (fs instanceof LocalFileProvider) { @SuppressWarnings("deprecation") VirtualFile file = ((LocalFileProvider)fs).findLocalVirtualFileByPath(path); if (file != null && file.isDirectory()) { if (file.getChildren().length > 0) { virtualFile = file; break; } if (virtualFile == null) { virtualFile = file; } } } } } return virtualFile; } /* filter can have form "*.js, !*_min.js", latter means except matched by *_min.js */ @NotNull public static Condition<CharSequence> createFileMaskCondition(@Nullable String filter) throws PatternSyntaxException { if (filter == null) { return Conditions.alwaysTrue(); } String pattern = ""; String negativePattern = ""; final List<String> masks = StringUtil.split(filter, ","); for(String mask:masks) { mask = mask.trim(); if (StringUtil.startsWith(mask, "!")) { negativePattern += (negativePattern.isEmpty() ? "" : "|") + "(" + PatternUtil.convertToRegex(mask.substring(1)) + ")"; } else { pattern += (pattern.isEmpty() ? "" : "|") + "(" + PatternUtil.convertToRegex(mask) + ")"; } } if (pattern.isEmpty()) pattern = PatternUtil.convertToRegex("*"); final String finalPattern = pattern; final String finalNegativePattern = negativePattern; return new Condition<CharSequence>() { final Pattern regExp = Pattern.compile(finalPattern, Pattern.CASE_INSENSITIVE); final Pattern negativeRegExp = StringUtil.isEmpty(finalNegativePattern) ? null : Pattern.compile(finalNegativePattern, Pattern.CASE_INSENSITIVE); @Override public boolean value(CharSequence input) { return regExp.matcher(input).matches() && (negativeRegExp == null || !negativeRegExp.matcher(input).matches()); } }; } /** * @deprecated to be removed in IDEA 16 */ @Nullable public static Pattern createFileMaskRegExp(@Nullable String filter) { if (filter == null) { return null; } String pattern; final List<String> strings = StringUtil.split(filter, ","); if (strings.size() == 1) { pattern = PatternUtil.convertToRegex(filter.trim()); } else { pattern = StringUtil.join(strings, s -> "(" + PatternUtil.convertToRegex(s.trim()) + ")", "|"); } return Pattern.compile(pattern, Pattern.CASE_INSENSITIVE); } /** * @deprecated to remove in IDEA 16 */ public static void findUsages(@NotNull FindModel findModel, @Nullable final PsiDirectory psiDirectory, @NotNull final Project project, @NotNull final Processor<UsageInfo> consumer, @NotNull FindUsagesProcessPresentation processPresentation) { findUsages(findModel, project, consumer, processPresentation); } public static void findUsages(@NotNull FindModel findModel, @NotNull final Project project, @NotNull final Processor<UsageInfo> consumer, @NotNull FindUsagesProcessPresentation processPresentation) { findUsages(findModel, project, consumer, processPresentation, Collections.emptySet()); } public static void findUsages(@NotNull FindModel findModel, @NotNull final Project project, @NotNull final Processor<UsageInfo> consumer, @NotNull FindUsagesProcessPresentation processPresentation, @NotNull Set<VirtualFile> filesToStart) { new FindInProjectTask(findModel, project, filesToStart).findUsages(consumer, processPresentation); } // returns number of hits static int processUsagesInFile(@NotNull final PsiFile psiFile, @NotNull final VirtualFile virtualFile, @NotNull final FindModel findModel, @NotNull final Processor<UsageInfo> consumer) { if (findModel.getStringToFind().isEmpty()) { if (!ReadAction.compute(() -> consumer.process(new UsageInfo(psiFile)))) { throw new ProcessCanceledException(); } return 1; } if (virtualFile.getFileType().isBinary()) return 0; // do not decompile .class files final Document document = ReadAction.compute(() -> virtualFile.isValid() ? FileDocumentManager.getInstance().getDocument(virtualFile) : null); if (document == null) return 0; final int[] offset = {0}; int count = 0; int found; ProgressIndicator indicator = ProgressWrapper.unwrap(ProgressManager.getInstance().getProgressIndicator()); TooManyUsagesStatus tooManyUsagesStatus = TooManyUsagesStatus.getFrom(indicator); do { tooManyUsagesStatus.pauseProcessingIfTooManyUsages(); // wait for user out of read action found = ReadAction.compute(() -> { if (!psiFile.isValid()) return 0; return addToUsages(document, consumer, findModel, psiFile, offset, USAGES_PER_READ_ACTION); }); count += found; } while (found != 0); return count; } private static int addToUsages(@NotNull Document document, @NotNull Processor<UsageInfo> consumer, @NotNull FindModel findModel, @NotNull final PsiFile psiFile, @NotNull int[] offsetRef, int maxUsages) { int count = 0; CharSequence text = document.getCharsSequence(); int textLength = document.getTextLength(); int offset = offsetRef[0]; Project project = psiFile.getProject(); FindManager findManager = FindManager.getInstance(project); while (offset < textLength) { FindResult result = findManager.findString(text, offset, findModel, psiFile.getVirtualFile()); if (!result.isStringFound()) break; final int prevOffset = offset; offset = result.getEndOffset(); if (prevOffset == offset) { // for regular expr the size of the match could be zero -> could be infinite loop in finding usages! ++offset; } final SearchScope customScope = findModel.getCustomScope(); if (customScope instanceof LocalSearchScope) { final TextRange range = new TextRange(result.getStartOffset(), result.getEndOffset()); if (!((LocalSearchScope)customScope).containsRange(psiFile, range)) continue; } UsageInfo info = new FindResultUsageInfo(findManager, psiFile, prevOffset, findModel, result); if (!consumer.process(info)){ throw new ProcessCanceledException(); } count++; if (maxUsages > 0 && count >= maxUsages) { break; } } offsetRef[0] = offset; return count; } @NotNull private static String getTitleForScope(@NotNull final FindModel findModel) { String scopeName; if (findModel.isProjectScope()) { scopeName = FindBundle.message("find.scope.project.title"); } else if (findModel.getModuleName() != null) { scopeName = FindBundle.message("find.scope.module.title", findModel.getModuleName()); } else if(findModel.getCustomScopeName() != null) { scopeName = findModel.getCustomScopeName(); } else { scopeName = FindBundle.message("find.scope.directory.title", findModel.getDirectoryName()); } String result = scopeName; if (findModel.getFileFilter() != null) { result += " "+FindBundle.message("find.scope.files.with.mask", findModel.getFileFilter()); } return result; } @NotNull public static UsageViewPresentation setupViewPresentation(final boolean toOpenInNewTab, @NotNull FindModel findModel) { final UsageViewPresentation presentation = new UsageViewPresentation(); setupViewPresentation(presentation, toOpenInNewTab, findModel); return presentation; } public static void setupViewPresentation(UsageViewPresentation presentation, boolean toOpenInNewTab, @NotNull FindModel findModel) { final String scope = getTitleForScope(findModel); final String stringToFind = findModel.getStringToFind(); presentation.setScopeText(scope); if (stringToFind.isEmpty()) { presentation.setTabText("Files"); presentation.setToolwindowTitle(BundleBase.format("Files in {0}", scope)); presentation.setUsagesString("files"); } else { FindModel.SearchContext searchContext = findModel.getSearchContext(); String contextText = ""; if (searchContext != FindModel.SearchContext.ANY) { contextText = FindBundle.message("find.context.presentation.scope.label", FindDialog.getPresentableName(searchContext)); } presentation.setTabText(FindBundle.message("find.usage.view.tab.text", stringToFind, contextText)); presentation.setToolwindowTitle(FindBundle.message("find.usage.view.toolwindow.title", stringToFind, scope, contextText)); presentation.setUsagesString(FindBundle.message("find.usage.view.usages.text", stringToFind)); presentation.setUsagesWord(FindBundle.message("occurrence")); presentation.setCodeUsagesString(FindBundle.message("found.occurrences")); presentation.setContextText(contextText); } presentation.setOpenInNewTab(toOpenInNewTab); presentation.setCodeUsages(false); presentation.setUsageTypeFilteringAvailable(true); if (findModel.isReplaceState() && findModel.isRegularExpressions()) { presentation.setSearchPattern(findModel.compileRegExp()); presentation.setReplacePattern(Pattern.compile(findModel.getStringToReplace())); } else { presentation.setSearchPattern(null); presentation.setReplacePattern(null); } } @NotNull public static FindUsagesProcessPresentation setupProcessPresentation(@NotNull final Project project, final boolean showPanelIfOnlyOneUsage, @NotNull final UsageViewPresentation presentation) { FindUsagesProcessPresentation processPresentation = new FindUsagesProcessPresentation(presentation); processPresentation.setShowNotFoundMessage(true); processPresentation.setShowPanelIfOnlyOneUsage(showPanelIfOnlyOneUsage); processPresentation.setProgressIndicatorFactory( () -> new FindProgressIndicator(project, presentation.getScopeText()) ); return processPresentation; } private static List<PsiElement> getTopLevelRegExpChars(String regExpText, Project project) { @SuppressWarnings("deprecation") PsiFile file = PsiFileFactory.getInstance(project).createFileFromText("A.regexp", regExpText); List<PsiElement> result = null; final PsiElement[] children = file.getChildren(); for (PsiElement child:children) { PsiElement[] grandChildren = child.getChildren(); if (grandChildren.length != 1) return Collections.emptyList(); // a | b, more than one branch, can not predict in current way for(PsiElement grandGrandChild:grandChildren[0].getChildren()) { if (result == null) result = new ArrayList<>(); result.add(grandGrandChild); } } return result != null ? result : Collections.emptyList(); } @NotNull public static String buildStringToFindForIndicesFromRegExp(@NotNull String stringToFind, @NotNull Project project) { if (!Registry.is("idea.regexp.search.uses.indices")) return ""; return ReadAction.compute(() -> { final List<PsiElement> topLevelRegExpChars = getTopLevelRegExpChars("a", project); if (topLevelRegExpChars.size() != 1) return ""; // leave only top level regExpChars return StringUtil.join(getTopLevelRegExpChars(stringToFind, project), new Function<PsiElement, String>() { final Class regExpCharPsiClass = topLevelRegExpChars.get(0).getClass(); @Override public String fun(PsiElement element) { if (regExpCharPsiClass.isInstance(element)) { String text = element.getText(); if (!text.startsWith("\\")) return text; } return " "; } }, ""); }); } public static void initStringToFindFromDataContext(FindModel findModel, @NotNull DataContext dataContext) { Editor editor = CommonDataKeys.EDITOR.getData(dataContext); FindUtil.initStringToFindWithSelection(findModel, editor); if (editor == null || !editor.getSelectionModel().hasSelection()) { FindUtil.useFindStringFromFindInFileModel(findModel, CommonDataKeys.EDITOR_EVEN_IF_INACTIVE.getData(dataContext)); } } public static class StringUsageTarget implements ConfigurableUsageTarget, ItemPresentation, TypeSafeDataProvider { @NotNull protected final Project myProject; @NotNull protected final FindModel myFindModel; public StringUsageTarget(@NotNull Project project, @NotNull FindModel findModel) { myProject = project; myFindModel = findModel.clone(); } @Override @NotNull public String getPresentableText() { UsageViewPresentation presentation = setupViewPresentation(false, myFindModel); return presentation.getToolwindowTitle(); } @NotNull @Override public String getLongDescriptiveName() { return getPresentableText(); } @Override public String getLocationString() { return myFindModel + "!!"; } @Override public Icon getIcon(boolean open) { return AllIcons.Actions.Menu_find; } @Override public void findUsages() { FindInProjectManager.getInstance(myProject).startFindInProject(myFindModel); } @Override public void findUsagesInEditor(@NotNull FileEditor editor) {} @Override public void highlightUsages(@NotNull PsiFile file, @NotNull Editor editor, boolean clearHighlights) {} @Override public boolean isValid() { return true; } @Override public boolean isReadOnly() { return true; } @Override @Nullable public VirtualFile[] getFiles() { return null; } @Override public void update() { } @Override public String getName() { return myFindModel.getStringToFind().isEmpty() ? myFindModel.getFileFilter() : myFindModel.getStringToFind(); } @Override public ItemPresentation getPresentation() { return this; } @Override public void navigate(boolean requestFocus) { throw new UnsupportedOperationException(); } @Override public boolean canNavigate() { return false; } @Override public boolean canNavigateToSource() { return false; } @Override public void showSettings() { Content selectedContent = UsageViewManager.getInstance(myProject).getSelectedContent(true); JComponent component = selectedContent == null ? null : selectedContent.getComponent(); FindInProjectManager findInProjectManager = FindInProjectManager.getInstance(myProject); findInProjectManager.findInProject(DataManager.getInstance().getDataContext(component), myFindModel); } @Override public KeyboardShortcut getShortcut() { return ActionManager.getInstance().getKeyboardShortcut("FindInPath"); } @Override public void calcData(DataKey key, DataSink sink) { if (UsageView.USAGE_SCOPE.equals(key)) { SearchScope scope = getScopeFromModel(myProject, myFindModel); sink.put(UsageView.USAGE_SCOPE, scope); } } } private static void addSourceDirectoriesFromLibraries(@NotNull Project project, @NotNull VirtualFile directory, @NotNull Collection<VirtualFile> outSourceRoots) { ProjectFileIndex index = ProjectFileIndex.SERVICE.getInstance(project); // if we already are in the sources, search just in this directory only if (!index.isInLibraryClasses(directory)) return; VirtualFile classRoot = index.getClassRootForFile(directory); if (classRoot == null) return; String relativePath = VfsUtilCore.getRelativePath(directory, classRoot); if (relativePath == null) return; Collection<VirtualFile> otherSourceRoots = new THashSet<>(); // if we are in the library sources, return (to search in this directory only) // otherwise, if we outside sources or in a jar directory, add directories from other source roots searchForOtherSourceDirs: for (OrderEntry entry : index.getOrderEntriesForFile(directory)) { if (entry instanceof LibraryOrderEntry) { Library library = ((LibraryOrderEntry)entry).getLibrary(); if (library == null) continue; // note: getUrls() returns jar directories too String[] sourceUrls = library.getUrls(OrderRootType.SOURCES); for (String sourceUrl : sourceUrls) { if (VfsUtilCore.isEqualOrAncestor(sourceUrl, directory.getUrl())) { // already in this library sources, no need to look for another source root otherSourceRoots.clear(); break searchForOtherSourceDirs; } // otherwise we may be inside the jar file in a library which is configured as a jar directory // in which case we have no way to know whether this is a source jar or classes jar - so try to locate the source jar } } for (VirtualFile sourceRoot : entry.getFiles(OrderRootType.SOURCES)) { VirtualFile sourceFile = sourceRoot.findFileByRelativePath(relativePath); if (sourceFile != null) { otherSourceRoots.add(sourceFile); } } } outSourceRoots.addAll(otherSourceRoots); } @NotNull static SearchScope getScopeFromModel(@NotNull Project project, @NotNull FindModel findModel) { SearchScope customScope = findModel.getCustomScope(); VirtualFile directory = getDirectory(findModel); Module module = findModel.getModuleName() == null ? null : ModuleManager.getInstance(project).findModuleByName(findModel.getModuleName()); return findModel.isCustomScope() && customScope != null ? customScope.intersectWith(GlobalSearchScope.allScope(project)) : // we don't have to check for myProjectFileIndex.isExcluded(file) here like FindInProjectTask.collectFilesInScope() does // because all found usages are guaranteed to be not in excluded dir directory != null ? forDirectory(project, findModel.isWithSubdirectories(), directory) : module != null ? module.getModuleContentScope() : findModel.isProjectScope() ? ProjectScope.getContentScope(project) : GlobalSearchScope.allScope(project); } @NotNull private static GlobalSearchScope forDirectory(@NotNull Project project, boolean withSubdirectories, @NotNull VirtualFile directory) { Set<VirtualFile> result = new LinkedHashSet<>(); result.add(directory); addSourceDirectoriesFromLibraries(project, directory, result); VirtualFile[] array = result.toArray(VirtualFile.EMPTY_ARRAY); return GlobalSearchScopesCore.directoriesScope(project, withSubdirectories, array); } }
/* * Copyright 2012-2013 inBloom, Inc. and 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.slc.sli.ingestion.tenant; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ResourceLoaderAware; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Component; import org.slc.sli.ingestion.util.LogUtil; /** * Populates the tenant database collection with default tenant collections. * * @author jtully */ @Component public class TenantPopulator implements ResourceLoaderAware { private static final Logger LOG = LoggerFactory.getLogger(TenantPopulator.class); @Autowired private TenantDA tenantDA; private ResourceLoader resourceLoader; private String parentLandingZoneDir; private List<String> tenantRecordResourcePaths; private static final String HOSTNAME_PLACEHOLDER = "<hostname>"; private static final String PARENT_LZ_PATH_PLACEHOLDER = "<lzpath>"; /** * Populate the tenant data store with a default set of tenants. * */ public void populateDefaultTenants() { try { String hostName = InetAddress.getLocalHost().getHostName(); createParentLzDirectory(); List<TenantRecord> tenants = constructDefaultTenantCollection(hostName); for (TenantRecord tenant : tenants) { tenantDA.insertTenant(tenant); } } catch (Exception e) { LOG.error("Exception encountered populating default tenants:", e); } } /** * Construct the default tenant collection based on the configured TenantRecord resources. * * @param hostName * @return a list of constructed TenantRecord objects */ private List<TenantRecord> constructDefaultTenantCollection(String hostname) { List<TenantRecord> tenants = new ArrayList<TenantRecord>(); for (String tenantResourcePath : tenantRecordResourcePaths) { TenantRecord tenant = loadTenant(tenantResourcePath); replaceTenantPlaceholderFields(tenant, hostname); createTenantLzDirectory(tenant); tenants.add(tenant); } return tenants; } /** * * Create the landing zone directory for the parent landing zone * */ private void createParentLzDirectory() { String lzPath = Matcher.quoteReplacement(parentLandingZoneDir); File lzDirectory = new File(lzPath); if (!lzDirectory.mkdir()) { LOG.debug("Failed to mkdir: {}", lzDirectory.getPath()); } if (!lzDirectory.setReadable(true, false)) { LOG.debug("Failed to setReadable: {}", lzDirectory.getPath()); } if (!lzDirectory.setWritable(true, false)) { LOG.debug("Failed to setWritable: {}", lzDirectory.getPath()); } } /** * * Create the landing zone directory for a tenant. * * @param tenant * , the tenant for which to create landing zone directories * */ private void createTenantLzDirectory(TenantRecord tenant) { List<LandingZoneRecord> landingZones = tenant.getLandingZone(); for (LandingZoneRecord lz : landingZones) { String lzPath = lz.getPath(); File lzDirectory = new File(lzPath); if (!lzDirectory.mkdir()) { LOG.debug("Failed to mkdir: {}", lzDirectory.getPath()); } if (!lzDirectory.setReadable(true, false)) { LOG.debug("Failed to setReadable: {}", lzDirectory.getPath()); } if (!lzDirectory.setWritable(true, false)) { LOG.debug("Failed to setWritable: {}", lzDirectory.getPath()); } } } /** * * Process TenantRecord, Replacing hostname and lzPath placeholder fields with * the actual values. * * @param tenant * record to be processed * @param hostname * the hostname to be used in placeholder replacement */ private void replaceTenantPlaceholderFields(TenantRecord tenant, String hostname) { List<LandingZoneRecord> landingZones = tenant.getLandingZone(); for (LandingZoneRecord lz : landingZones) { // replace hostname field String serverVal = lz.getIngestionServer(); serverVal = serverVal.replaceFirst(HOSTNAME_PLACEHOLDER, hostname); lz.setIngestionServer(serverVal); String pathVal = lz.getPath(); pathVal = pathVal.replaceFirst(PARENT_LZ_PATH_PLACEHOLDER, Matcher.quoteReplacement(parentLandingZoneDir)); lz.setPath(new File(pathVal).getAbsolutePath()); } } /** * Loads a TenantRecord from a tenant resource * * @param resourcePath * to load into a tenant record * @return the loaded tenant */ private TenantRecord loadTenant(String resourcePath) { TenantRecord tenant = null; InputStream tenantIs = null; try { Resource config = resourceLoader.getResource(resourcePath); if (config.exists()) { tenantIs = config.getInputStream(); tenant = TenantRecord.parse(tenantIs); } } catch (IOException e) { LogUtil.error(LOG, "Exception encountered loading tenant resource: ", e); } finally { IOUtils.closeQuietly(tenantIs); } return tenant; } /** * Obtain the hostname for the ingestion server running * * @throws UnknownHostException */ private String getHostname() throws UnknownHostException { return InetAddress.getLocalHost().getHostName(); } @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } /** * @return the parentLandingZoneDir */ public String getParentLandingZoneDir() { return parentLandingZoneDir; } /** * @param parentLandingZoneDir * the parentLandingZoneDir to set */ public void setParentLandingZoneDir(String singleLandingZoneDir) { File lzFile = new File(singleLandingZoneDir); this.parentLandingZoneDir = lzFile.getAbsolutePath(); } public List<String> getTenantRecordResourcePaths() { return tenantRecordResourcePaths; } public void setTenantRecordResourcePaths(List<String> tenantRecordResourcePaths) { this.tenantRecordResourcePaths = tenantRecordResourcePaths; } }
/** * 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.backup.example; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CountDownLatch; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.ChoreService; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.Stoppable; import org.apache.hadoop.hbase.client.ClusterConnection; import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor; import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.master.cleaner.BaseHFileCleanerDelegate; import org.apache.hadoop.hbase.master.cleaner.CleanerChore; import org.apache.hadoop.hbase.master.cleaner.HFileCleaner; import org.apache.hadoop.hbase.regionserver.CompactedHFilesDischarger; import org.apache.hadoop.hbase.regionserver.HRegion; import org.apache.hadoop.hbase.regionserver.HStore; import org.apache.hadoop.hbase.regionserver.RegionServerServices; import org.apache.hadoop.hbase.testclassification.MediumTests; import org.apache.hadoop.hbase.testclassification.MiscTests; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.FSUtils; import org.apache.hadoop.hbase.util.HFileArchiveUtil; import org.apache.hadoop.hbase.util.StoppableImplementation; import org.apache.hadoop.hbase.zookeeper.ZKUtil; import org.apache.hadoop.hbase.zookeeper.ZKWatcher; import org.apache.zookeeper.KeeperException; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Spin up a small cluster and check that the hfiles of region are properly long-term archived as * specified via the {@link ZKTableArchiveClient}. */ @Category({MiscTests.class, MediumTests.class}) public class TestZooKeeperTableArchiveClient { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestZooKeeperTableArchiveClient.class); private static final Logger LOG = LoggerFactory.getLogger(TestZooKeeperTableArchiveClient.class); private static final HBaseTestingUtility UTIL = HBaseTestingUtility.createLocalHTU(); private static final String STRING_TABLE_NAME = "test"; private static final byte[] TEST_FAM = Bytes.toBytes("fam"); private static final byte[] TABLE_NAME = Bytes.toBytes(STRING_TABLE_NAME); private static ZKTableArchiveClient archivingClient; private final List<Path> toCleanup = new ArrayList<>(); private static ClusterConnection CONNECTION; private static RegionServerServices rss; /** * Setup the config for the cluster */ @BeforeClass public static void setupCluster() throws Exception { setupConf(UTIL.getConfiguration()); UTIL.startMiniZKCluster(); CONNECTION = (ClusterConnection)ConnectionFactory.createConnection(UTIL.getConfiguration()); archivingClient = new ZKTableArchiveClient(UTIL.getConfiguration(), CONNECTION); // make hfile archiving node so we can archive files ZKWatcher watcher = UTIL.getZooKeeperWatcher(); String archivingZNode = ZKTableArchiveClient.getArchiveZNode(UTIL.getConfiguration(), watcher); ZKUtil.createWithParents(watcher, archivingZNode); rss = mock(RegionServerServices.class); } private static void setupConf(Configuration conf) { // only compact with 3 files conf.setInt("hbase.hstore.compaction.min", 3); } @After public void tearDown() throws Exception { try { FileSystem fs = UTIL.getTestFileSystem(); // cleanup each of the files/directories registered for (Path file : toCleanup) { // remove the table and archive directories FSUtils.delete(fs, file, true); } } catch (IOException e) { LOG.warn("Failure to delete archive directory", e); } finally { toCleanup.clear(); } // make sure that backups are off for all tables archivingClient.disableHFileBackup(); } @AfterClass public static void cleanupTest() throws Exception { try { CONNECTION.close(); UTIL.shutdownMiniZKCluster(); } catch (Exception e) { LOG.warn("problem shutting down cluster", e); } } /** * Test turning on/off archiving */ @Test public void testArchivingEnableDisable() throws Exception { // 1. turn on hfile backups LOG.debug("----Starting archiving"); archivingClient.enableHFileBackupAsync(TABLE_NAME); assertTrue("Archving didn't get turned on", archivingClient .getArchivingEnabled(TABLE_NAME)); // 2. Turn off archiving and make sure its off archivingClient.disableHFileBackup(); assertFalse("Archving didn't get turned off.", archivingClient.getArchivingEnabled(TABLE_NAME)); // 3. Check enable/disable on a single table archivingClient.enableHFileBackupAsync(TABLE_NAME); assertTrue("Archving didn't get turned on", archivingClient .getArchivingEnabled(TABLE_NAME)); // 4. Turn off archiving and make sure its off archivingClient.disableHFileBackup(TABLE_NAME); assertFalse("Archving didn't get turned off for " + STRING_TABLE_NAME, archivingClient.getArchivingEnabled(TABLE_NAME)); } @Test public void testArchivingOnSingleTable() throws Exception { createArchiveDirectory(); FileSystem fs = UTIL.getTestFileSystem(); Path archiveDir = getArchiveDir(); Path tableDir = getTableDir(STRING_TABLE_NAME); toCleanup.add(archiveDir); toCleanup.add(tableDir); Configuration conf = UTIL.getConfiguration(); // setup the delegate Stoppable stop = new StoppableImplementation(); CleanerChore.initChorePool(conf); HFileCleaner cleaner = setupAndCreateCleaner(conf, fs, archiveDir, stop); List<BaseHFileCleanerDelegate> cleaners = turnOnArchiving(STRING_TABLE_NAME, cleaner); final LongTermArchivingHFileCleaner delegate = (LongTermArchivingHFileCleaner) cleaners.get(0); // create the region ColumnFamilyDescriptor hcd = ColumnFamilyDescriptorBuilder.of(TEST_FAM); HRegion region = UTIL.createTestRegion(STRING_TABLE_NAME, hcd); List<HRegion> regions = new ArrayList<>(); regions.add(region); Mockito.doReturn(regions).when(rss).getRegions(); final CompactedHFilesDischarger compactionCleaner = new CompactedHFilesDischarger(100, stop, rss, false); loadFlushAndCompact(region, TEST_FAM); compactionCleaner.chore(); // get the current hfiles in the archive directory List<Path> files = getAllFiles(fs, archiveDir); if (files == null) { FSUtils.logFileSystemState(fs, UTIL.getDataTestDir(), LOG); throw new RuntimeException("Didn't archive any files!"); } CountDownLatch finished = setupCleanerWatching(delegate, cleaners, files.size()); runCleaner(cleaner, finished, stop); // know the cleaner ran, so now check all the files again to make sure they are still there List<Path> archivedFiles = getAllFiles(fs, archiveDir); assertEquals("Archived files changed after running archive cleaner.", files, archivedFiles); // but we still have the archive directory assertTrue(fs.exists(HFileArchiveUtil.getArchivePath(UTIL.getConfiguration()))); } /** * Test archiving/cleaning across multiple tables, where some are retained, and others aren't * @throws Exception on failure */ @Test public void testMultipleTables() throws Exception { createArchiveDirectory(); String otherTable = "otherTable"; FileSystem fs = UTIL.getTestFileSystem(); Path archiveDir = getArchiveDir(); Path tableDir = getTableDir(STRING_TABLE_NAME); Path otherTableDir = getTableDir(otherTable); // register cleanup for the created directories toCleanup.add(archiveDir); toCleanup.add(tableDir); toCleanup.add(otherTableDir); Configuration conf = UTIL.getConfiguration(); // setup the delegate Stoppable stop = new StoppableImplementation(); final ChoreService choreService = new ChoreService("TEST_SERVER_NAME"); CleanerChore.initChorePool(conf); HFileCleaner cleaner = setupAndCreateCleaner(conf, fs, archiveDir, stop); List<BaseHFileCleanerDelegate> cleaners = turnOnArchiving(STRING_TABLE_NAME, cleaner); final LongTermArchivingHFileCleaner delegate = (LongTermArchivingHFileCleaner) cleaners.get(0); // create the region ColumnFamilyDescriptor hcd = ColumnFamilyDescriptorBuilder.of(TEST_FAM); HRegion region = UTIL.createTestRegion(STRING_TABLE_NAME, hcd); List<HRegion> regions = new ArrayList<>(); regions.add(region); Mockito.doReturn(regions).when(rss).getRegions(); final CompactedHFilesDischarger compactionCleaner = new CompactedHFilesDischarger(100, stop, rss, false); loadFlushAndCompact(region, TEST_FAM); compactionCleaner.chore(); // create the another table that we don't archive hcd = ColumnFamilyDescriptorBuilder.of(TEST_FAM); HRegion otherRegion = UTIL.createTestRegion(otherTable, hcd); regions = new ArrayList<>(); regions.add(otherRegion); Mockito.doReturn(regions).when(rss).getRegions(); final CompactedHFilesDischarger compactionCleaner1 = new CompactedHFilesDischarger(100, stop, rss, false); loadFlushAndCompact(otherRegion, TEST_FAM); compactionCleaner1.chore(); // get the current hfiles in the archive directory // Should be archived List<Path> files = getAllFiles(fs, archiveDir); if (files == null) { FSUtils.logFileSystemState(fs, archiveDir, LOG); throw new RuntimeException("Didn't load archive any files!"); } // make sure we have files from both tables int initialCountForPrimary = 0; int initialCountForOtherTable = 0; for (Path file : files) { String tableName = file.getParent().getParent().getParent().getName(); // check to which table this file belongs if (tableName.equals(otherTable)) initialCountForOtherTable++; else if (tableName.equals(STRING_TABLE_NAME)) initialCountForPrimary++; } assertTrue("Didn't archive files for:" + STRING_TABLE_NAME, initialCountForPrimary > 0); assertTrue("Didn't archive files for:" + otherTable, initialCountForOtherTable > 0); // run the cleaners, checking for each of the directories + files (both should be deleted and // need to be checked) in 'otherTable' and the files (which should be retained) in the 'table' CountDownLatch finished = setupCleanerWatching(delegate, cleaners, files.size() + 3); // run the cleaner choreService.scheduleChore(cleaner); // wait for the cleaner to check all the files finished.await(); // stop the cleaner stop.stop(""); // know the cleaner ran, so now check all the files again to make sure they are still there List<Path> archivedFiles = getAllFiles(fs, archiveDir); int archivedForPrimary = 0; for(Path file: archivedFiles) { String tableName = file.getParent().getParent().getParent().getName(); // ensure we don't have files from the non-archived table assertFalse("Have a file from the non-archived table: " + file, tableName.equals(otherTable)); if (tableName.equals(STRING_TABLE_NAME)) archivedForPrimary++; } assertEquals("Not all archived files for the primary table were retained.", initialCountForPrimary, archivedForPrimary); // but we still have the archive directory assertTrue("Archive directory was deleted via archiver", fs.exists(archiveDir)); } private void createArchiveDirectory() throws IOException { //create the archive and test directory FileSystem fs = UTIL.getTestFileSystem(); Path archiveDir = getArchiveDir(); fs.mkdirs(archiveDir); } private Path getArchiveDir() throws IOException { return new Path(UTIL.getDataTestDir(), HConstants.HFILE_ARCHIVE_DIRECTORY); } private Path getTableDir(String tableName) throws IOException { Path testDataDir = UTIL.getDataTestDir(); FSUtils.setRootDir(UTIL.getConfiguration(), testDataDir); return new Path(testDataDir, tableName); } private HFileCleaner setupAndCreateCleaner(Configuration conf, FileSystem fs, Path archiveDir, Stoppable stop) { conf.setStrings(HFileCleaner.MASTER_HFILE_CLEANER_PLUGINS, LongTermArchivingHFileCleaner.class.getCanonicalName()); return new HFileCleaner(1000, stop, conf, fs, archiveDir); } /** * Start archiving table for given hfile cleaner * @param tableName table to archive * @param cleaner cleaner to check to make sure change propagated * @return underlying {@link LongTermArchivingHFileCleaner} that is managing archiving * @throws IOException on failure * @throws KeeperException on failure */ private List<BaseHFileCleanerDelegate> turnOnArchiving(String tableName, HFileCleaner cleaner) throws IOException, KeeperException { // turn on hfile retention LOG.debug("----Starting archiving for table:" + tableName); archivingClient.enableHFileBackupAsync(Bytes.toBytes(tableName)); assertTrue("Archving didn't get turned on", archivingClient.getArchivingEnabled(tableName)); // wait for the archiver to get the notification List<BaseHFileCleanerDelegate> cleaners = cleaner.getDelegatesForTesting(); LongTermArchivingHFileCleaner delegate = (LongTermArchivingHFileCleaner) cleaners.get(0); while (!delegate.archiveTracker.keepHFiles(STRING_TABLE_NAME)) { // spin until propagation - should be fast } return cleaners; } /** * Spy on the {@link LongTermArchivingHFileCleaner} to ensure we can catch when the cleaner has * seen all the files * @return a {@link CountDownLatch} to wait on that releases when the cleaner has been called at * least the expected number of times. */ private CountDownLatch setupCleanerWatching(LongTermArchivingHFileCleaner cleaner, List<BaseHFileCleanerDelegate> cleaners, final int expected) { // replace the cleaner with one that we can can check BaseHFileCleanerDelegate delegateSpy = Mockito.spy(cleaner); final int[] counter = new int[] { 0 }; final CountDownLatch finished = new CountDownLatch(1); Mockito.doAnswer(new Answer<Iterable<FileStatus>>() { @Override public Iterable<FileStatus> answer(InvocationOnMock invocation) throws Throwable { counter[0]++; LOG.debug(counter[0] + "/ " + expected + ") Wrapping call to getDeletableFiles for files: " + invocation.getArgument(0)); @SuppressWarnings("unchecked") Iterable<FileStatus> ret = (Iterable<FileStatus>) invocation.callRealMethod(); if (counter[0] >= expected) finished.countDown(); return ret; } }).when(delegateSpy).getDeletableFiles(Mockito.anyListOf(FileStatus.class)); cleaners.set(0, delegateSpy); return finished; } /** * Get all the files (non-directory entries) in the file system under the passed directory * @param dir directory to investigate * @return all files under the directory */ private List<Path> getAllFiles(FileSystem fs, Path dir) throws IOException { FileStatus[] files = FSUtils.listStatus(fs, dir, null); if (files == null) { LOG.warn("No files under:" + dir); return null; } List<Path> allFiles = new ArrayList<>(); for (FileStatus file : files) { if (file.isDirectory()) { List<Path> subFiles = getAllFiles(fs, file.getPath()); if (subFiles != null) allFiles.addAll(subFiles); continue; } allFiles.add(file.getPath()); } return allFiles; } private void loadFlushAndCompact(HRegion region, byte[] family) throws IOException { // create two hfiles in the region createHFileInRegion(region, family); createHFileInRegion(region, family); HStore s = region.getStore(family); int count = s.getStorefilesCount(); assertTrue("Don't have the expected store files, wanted >= 2 store files, but was:" + count, count >= 2); // compact the two files into one file to get files in the archive LOG.debug("Compacting stores"); region.compact(true); } /** * Create a new hfile in the passed region * @param region region to operate on * @param columnFamily family for which to add data * @throws IOException */ private void createHFileInRegion(HRegion region, byte[] columnFamily) throws IOException { // put one row in the region Put p = new Put(Bytes.toBytes("row")); p.addColumn(columnFamily, Bytes.toBytes("Qual"), Bytes.toBytes("v1")); region.put(p); // flush the region to make a store file region.flush(true); } /** * @param cleaner */ private void runCleaner(HFileCleaner cleaner, CountDownLatch finished, Stoppable stop) throws InterruptedException { final ChoreService choreService = new ChoreService("CLEANER_SERVER_NAME"); // run the cleaner choreService.scheduleChore(cleaner); // wait for the cleaner to check all the files finished.await(); // stop the cleaner stop.stop(""); } }
/* * Copyright 2012-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.jvm.java; import static org.hamcrest.Matchers.matchesPattern; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import com.facebook.buck.io.MorePathsForTests; import com.facebook.buck.io.ProjectFilesystem; import com.facebook.buck.step.ExecutionContext; import com.facebook.buck.step.StepExecutionResult; import com.facebook.buck.step.TestExecutionContext; import com.facebook.buck.test.CoverageReportFormat; import com.facebook.buck.testutil.MoreAsserts; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; import java.util.Properties; import java.util.Set; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class GenerateCodeCoverageReportStepTest { public static final String OUTPUT_DIRECTORY = Paths.get("buck-out/gen/output").toString(); public static final Set<String> SOURCE_DIRECTORIES = ImmutableSet.of( MorePathsForTests.rootRelativePath("/absolute/path/to/parentDirectory1/src").toString(), MorePathsForTests.rootRelativePath("/absolute/path/to/parentDirectory2/src").toString()); private GenerateCodeCoverageReportStep step; private ExecutionContext context; private ProjectFilesystem filesystem; private Set<Path> jarFiles; @Rule public TemporaryFolder tmp = new TemporaryFolder(); @Before public void setUp() throws Exception { filesystem = new ProjectFilesystem(Paths.get(".").toAbsolutePath()); jarFiles = new LinkedHashSet<>(); File jarFile = new File(tmp.getRoot(), "foo.jar"); File jar2File = new File(tmp.getRoot(), "foo2.jar"); try (InputStream jarIn = getClass().getResourceAsStream("testdata/code_coverage_test/foo.jar")) { Files.copy(jarIn, jarFile.toPath()); } try (InputStream jarIn = getClass().getResourceAsStream("testdata/code_coverage_test/foo.jar")) { Files.copy(jarIn, jar2File.toPath()); } jarFiles.add(jarFile.toPath()); jarFiles.add(jar2File.toPath()); assertTrue(jarFile.exists()); step = new GenerateCodeCoverageReportStep( new ExternalJavaRuntimeLauncher("/baz/qux/java"), filesystem, SOURCE_DIRECTORIES, jarFiles, Paths.get(OUTPUT_DIRECTORY), CoverageReportFormat.HTML, "TitleFoo", Optional.empty(), Optional.empty()); context = TestExecutionContext.newInstance(); } @Test public void testGetShellCommandInternal() { ImmutableList.Builder<String> shellCommandBuilder = ImmutableList.builder(); System.setProperty( "buck.report_generator_jar", MorePathsForTests.rootRelativePath("/absolute/path/to/report/generator/jar").toString()); shellCommandBuilder.add( "/baz/qux/java", "-jar", MorePathsForTests.rootRelativePath("/absolute/path/to/report/generator/jar").toString(), absolutifyPath(Paths.get(OUTPUT_DIRECTORY + "/parameters.properties"))); List<String> expectedShellCommand = shellCommandBuilder.build(); MoreAsserts.assertListEquals(expectedShellCommand, step.getShellCommand(context)); } @Test public void testJarFileIsExtracted() throws Throwable { final File[] extractedDir = new File[2]; step = new GenerateCodeCoverageReportStep( new ExternalJavaRuntimeLauncher("/baz/qux/java"), filesystem, SOURCE_DIRECTORIES, jarFiles, Paths.get(OUTPUT_DIRECTORY), CoverageReportFormat.HTML, "TitleFoo", Optional.empty(), Optional.empty()) { @Override StepExecutionResult executeInternal(ExecutionContext context, Set<Path> jarFiles) { for (int i = 0; i < 2; i++) { extractedDir[i] = new ArrayList<>(jarFiles).get(i).toFile(); assertTrue(extractedDir[i].isDirectory()); assertTrue( new File(extractedDir[i], "com/facebook/testing/coverage/Foo.class").exists()); } return null; } }; step.execute(TestExecutionContext.newInstance()); assertFalse(extractedDir[0].exists()); assertFalse(extractedDir[1].exists()); } @Test public void testClassesDirIsUntouched() throws Throwable { final File classesDir = tmp.newFolder("classesDir"); jarFiles.clear(); jarFiles.add(classesDir.toPath()); step = new GenerateCodeCoverageReportStep( new ExternalJavaRuntimeLauncher("/baz/qux/java"), filesystem, SOURCE_DIRECTORIES, jarFiles, Paths.get(OUTPUT_DIRECTORY), CoverageReportFormat.HTML, "TitleFoo", Optional.empty(), Optional.empty()) { @Override StepExecutionResult executeInternal(ExecutionContext context, Set<Path> jarFiles) { assertEquals(1, jarFiles.size()); assertEquals(classesDir.toPath(), jarFiles.iterator().next()); return null; } }; step.execute(TestExecutionContext.newInstance()); assertTrue(classesDir.exists()); } @Test public void testSaveParametersToPropertyFile() throws IOException { byte[] actualOutput; Set<Path> directories = ImmutableSet.of(Paths.get("foo/bar"), Paths.get("foo/bar2")); try (ByteArrayOutputStream actualOutputStream = new ByteArrayOutputStream()) { step.saveParametersToPropertyStream(filesystem, directories, actualOutputStream); actualOutput = actualOutputStream.toByteArray(); } Properties actual = new Properties(); try (ByteArrayInputStream actualInputStream = new ByteArrayInputStream(actualOutput)) { try (InputStreamReader reader = new InputStreamReader(actualInputStream)) { actual.load(reader); } } assertEquals( absolutifyPath(Paths.get(OUTPUT_DIRECTORY)), actual.getProperty("jacoco.output.dir")); assertEquals("jacoco.exec", actual.getProperty("jacoco.exec.data.file")); assertEquals("html", actual.getProperty("jacoco.format")); assertEquals("TitleFoo", actual.getProperty("jacoco.title")); assertEquals( String.format( "%s:%s", absolutifyPath(Paths.get("foo/bar")), absolutifyPath(Paths.get("foo/bar2"))), actual.getProperty("classes.dir")); assertEquals( String.format( "%s:%s", absolutifyPath(Paths.get("foo/bar")), absolutifyPath(Paths.get("foo/bar2"))), actual.getProperty("classes.dir")); assertThat(actual.getProperty("classes.jars"), matchesPattern("^.*foo.jar:.*foo2.jar$")); assertEquals( String.format( "%s:%s", MorePathsForTests.rootRelativePath("/absolute/path/to/parentDirectory1/src").toString(), MorePathsForTests.rootRelativePath("/absolute/path/to/parentDirectory2/src") .toString()), actual.getProperty("src.dir")); } private static String absolutifyPath(Path relativePath) { return String.format( "%s%c%s", new File(".").getAbsoluteFile().toPath().normalize(), File.separatorChar, relativePath); } }
package com.haxademic.core.media.audio.interphase; import java.util.ArrayList; import com.haxademic.core.app.P; import com.haxademic.core.data.ConvertUtil; import com.haxademic.core.data.constants.PEvents; import com.haxademic.core.data.store.IAppStoreListener; import com.haxademic.core.debug.DebugView; import com.haxademic.core.draw.context.PG; import com.haxademic.core.draw.shapes.Shapes; import com.haxademic.core.file.FileUtil; import com.haxademic.core.hardware.midi.devices.LaunchPad; import com.haxademic.core.hardware.midi.devices.LaunchPad.ILaunchpadCallback; //import com.haxademic.core.hardware.midi.devices.LaunchPad; import com.haxademic.core.hardware.midi.devices.LaunchPadMini; import com.haxademic.core.hardware.shared.InputTrigger; import com.haxademic.core.media.audio.AudioUtil; import com.haxademic.core.net.JsonUtil; import com.haxademic.core.system.SystemUtil; import com.haxademic.core.ui.IUIControl; import com.haxademic.core.ui.UI; import processing.core.PGraphics; import processing.core.PImage; import processing.data.JSONArray; import processing.data.JSONObject; import themidibus.MidiBus; public class Interphase implements IAppStoreListener, ILaunchpadCallback { //////////////////////////////////////// // sizes public static int NUM_CHANNELS = 8; public static final int NUM_STEPS = 16; // events public static final String BEAT = "BEAT"; public static final String CUR_STEP = "CUR_STEP"; public static final String BPM = "BPM"; public static final String SEQUENCER_TRIGGER = "SEQUENCER_TRIGGER"; // state public static final String CUR_SCALE_INDEX = "CUR_SCALE_INDEX"; public static final String GLOBAL_PATTERNS_EVLOVE = "GLOBAL_PATTERNS_EVLOVE"; public static final String SYSTEM_MUTED = "SYSTEM_MUTED"; // input public static final float TEMPO_EASE_FACTOR = 1.5f; public static boolean TEMPO_MOUSE_CONTROL = false; public static boolean TEMPO_MIDI_CONTROL = true; public static final int TRIGGER_TIMEOUT = 45000; public static final String INTERACTION_SPEED_MULT = "INTERACTION_SPEED_MULT"; // ui public static final String UI_GLOBAL_BPM = "UI_GLOBAL_BPM"; public static final String UI_GLOBAL_EVOLVES = "UI_GLOBAL_EVOLVES"; public static final String UI_CUR_SCALE = "UI_CUR_SCALE"; public static final String UI_SAMPLE_ = "UI_SAMPLE_"; public static final String UI_VOLUME_ = "UI_VOLUME_"; ////////////////////////////////////////// protected Scales scales; public Sequencer sequencers[]; protected Metronome metronome; protected String SEQUENCES_PATH = "text/json/interphase/sequences/"; protected ArrayList<String> configFiles = new ArrayList<String>(); protected int curConfigIndex = 0; protected boolean hasUI = false; // protected InputTrigger trigger1 = new InputTrigger().addKeyCodes(new char[]{'1'}).addMidiNotes(new Integer[]{104, 41}); // protected InputTrigger trigger2 = new InputTrigger().addKeyCodes(new char[]{'2'}).addMidiNotes(new Integer[]{105, 42}); // protected InputTrigger trigger3 = new InputTrigger().addKeyCodes(new char[]{'3'}).addMidiNotes(new Integer[]{106, 43}); // protected InputTrigger trigger4 = new InputTrigger().addKeyCodes(new char[]{'4'}).addMidiNotes(new Integer[]{107, 44}); // protected InputTrigger trigger5 = new InputTrigger().addKeyCodes(new char[]{'5'}).addMidiNotes(new Integer[]{108, 45}); // protected InputTrigger trigger6 = new InputTrigger().addKeyCodes(new char[]{'6'}).addMidiNotes(new Integer[]{109, 46}); // protected InputTrigger trigger7 = new InputTrigger().addKeyCodes(new char[]{'7'}).addMidiNotes(new Integer[]{110, 47}); // protected InputTrigger trigger8 = new InputTrigger().addKeyCodes(new char[]{'8'}).addMidiNotes(new Integer[]{111, 48}); protected InputTrigger triggerDown = new InputTrigger().addKeyCodes(new char[]{'-'}); protected InputTrigger triggerUp = new InputTrigger().addKeyCodes(new char[]{'='}); // protected InputTrigger trigger9 = new InputTrigger().addKeyCodes(new char[]{'9'}); protected LaunchPadMini launchpad1; protected LaunchPadMini launchpad2; public Interphase(SequencerConfig[] interphaseChannels) { this(interphaseChannels, AudioUtil.getAudioMixerIndex("Primary")); } public Interphase(SequencerConfig[] interphaseChannels, int audioOutDeviceIndex) { AudioUtil.DEFAULT_AUDIO_MIXER_INDEX = audioOutDeviceIndex; NUM_CHANNELS = interphaseChannels.length; // init state // override these after Interphase init P.store.setBoolean(SYSTEM_MUTED, false); P.store.setNumber(BEAT, 0); P.store.setNumber(CUR_STEP, 0); P.store.setNumber(BPM, 90); P.store.setNumber(INTERACTION_SPEED_MULT, 0); P.store.setNumber(CUR_SCALE_INDEX, 0); P.store.setNumber(SEQUENCER_TRIGGER, 0); P.store.setBoolean(GLOBAL_PATTERNS_EVLOVE, false); P.store.addListener(this); // build music machine scales = new Scales(); metronome = new Metronome(); buildSequencers(interphaseChannels); addDebugHelpLines(); loadConfigFiles(); } protected void buildSequencers(SequencerConfig[] interphaseChannels) { sequencers = new Sequencer[NUM_CHANNELS]; for (int i = 0; i < NUM_CHANNELS; i++) { sequencers[i] = new Sequencer(this, interphaseChannels[i]); } } protected void addDebugHelpLines() { DebugView.setHelpLine(DebugView.TITLE_PREFIX + "Interphase Key Commands", ""); DebugView.setHelpLine("[SPACE] |", "Play/Stop"); DebugView.setHelpLine("[1234] |", "Trigger"); DebugView.setHelpLine("[QWER] |", "Toggle mute"); DebugView.setHelpLine("[ASDF] |", "New sound"); DebugView.setHelpLine("[ZXCV] |", "Toggle Evloves"); DebugView.setHelpLine("[+] |", "BPM ++"); DebugView.setHelpLine("[-] |", "BPM --"); DebugView.setHelpLine("[9-0] |", "Load stored sequences"); DebugView.setHelpLine("[o] |", "Save stored sequences"); DebugView.setHelpLine("[O] |", "Overwrite cur sequence"); } // init config public Interphase initUI() { hasUI = true; // add UI buttons grid // make dyanmic number of columns per number of sequencers for (int i = 0; i < NUM_STEPS; i++) { int numChannels = sequencers.length; String[] buttonIds = new String[numChannels]; for(int j = 0; j < numChannels; j++) { int channel = j; int step = i; buttonIds[j] = "beatgrid-"+channel+"-"+step; } UI.addButtons(buttonIds, true); } UI.addWebInterface(false); return this; } public Interphase initGlobalControlsUI() { return initGlobalControlsUI(null, null); } public Interphase initGlobalControlsUI(int samplePickerMidiCC, int midiCCSequence) { // create sequential MIDI CC notes int[] samplePickerMidiCCArray = new int[sequencers.length]; for (int i = 0; i < samplePickerMidiCCArray.length; i++) samplePickerMidiCCArray[i] = samplePickerMidiCC + i; int[] midiCCSequenceArray = new int[sequencers.length]; for (int i = 0; i < midiCCSequenceArray.length; i++) midiCCSequenceArray[i] = midiCCSequence + i; // pass to constructor return initGlobalControlsUI(samplePickerMidiCCArray, midiCCSequenceArray); } public Interphase initGlobalControlsUI(int[] samplePickerMidiCC, int[] volumeMidiCC) { UI.addTitle("Interphase"); UI.addSlider(UI_GLOBAL_BPM, P.store.getInt(BPM), 60, 170, 1, false); UI.addToggle(UI_GLOBAL_EVOLVES, false, false); UI.addSlider(UI_CUR_SCALE, 0, 0, Scales.SCALES.length-1, 1, false); UI.addTitle("Interphase | Sequencers"); for (int i = 0; i < sequencers.length; i++) { // add optonal midi int midiCCSample = (samplePickerMidiCC != null) ? samplePickerMidiCC[i] : -1; int midiCCVolume = (volumeMidiCC != null) ? volumeMidiCC[i] : -1; // add sliders for each sequencer Sequencer seq = sequencerAt(i); UI.addSlider(UI_SAMPLE_+(i+1), 0, 0, seq.numSamples() - 1, 1, false, midiCCSample); UI.addSlider(UI_VOLUME_+(i+1), seq.volume(), 0, 3, 0.01f, false, midiCCVolume); } return this; } // init launchpad grids public Interphase initLaunchpads(int midiIn1, int midiOut1, int midiIn2, int midiOut2) { MidiBus.list(); launchpad1 = new LaunchPadMini(midiIn1, midiOut1); launchpad1.setDelegate(this); launchpad2 = new LaunchPadMini(midiIn2, midiOut2); launchpad2.setDelegate(this); return this; } public Interphase initLaunchpads(String deviceName1, String deviceName2) { MidiBus.list(); launchpad1 = new LaunchPadMini(deviceName1); launchpad1.setDelegate(this); launchpad2 = new LaunchPadMini(deviceName2); launchpad2.setDelegate(this); return this; } public Interphase initAudioAnalysisPerChannel() { for (int i = 0; i < sequencers.length; i++) { sequencers[i].addAudioAnalysis(); } return this; } public Interphase initAudioTexturesPerChannel() { for (int i = 0; i < sequencers.length; i++) { sequencers[i].addAudioTextures(); } return this; } public void autoPlay() { metronome.togglePlay(); } ///////////////////////////////// // GETTERS ///////////////////////////////// public Sequencer[] sequencers() { return sequencers; } public Sequencer sequencerAt(int index) { return sequencers[index]; } public int numChannels() { return sequencers.length; } ///////////////////////////////// // SHARED ///////////////////////////////// public void setSystemMute(boolean muted) { P.store.setBoolean(SYSTEM_MUTED, muted); } ///////////////////////////////// // INPUT ///////////////////////////////// protected void keyPressed() { // App controls --------------------------------------- P.out("Interphase keyPressed:", P.p.key); if (P.p.key == ' ') metronome.togglePlay(); if (P.p.key == 'g') TEMPO_MOUSE_CONTROL = !TEMPO_MOUSE_CONTROL; if (P.p.key == P.CODED && P.p.keyCode == P.DOWN) P.store.setBoolean(SYSTEM_MUTED, true); if (P.p.key == P.CODED && P.p.keyCode == P.UP) P.store.setBoolean(SYSTEM_MUTED, false); // Sequencer controls --------------------------------- if(P.p.key == 'Q') sequencers[0].toggleMute(); if(P.p.key == 'W') sequencers[1].toggleMute(); if(P.p.key == 'E') sequencers[2].toggleMute(); if(P.p.key == 'R') sequencers[3].toggleMute(); if(P.p.key == 'T') sequencers[4].toggleMute(); if(P.p.key == 'Y') sequencers[5].toggleMute(); if(P.p.key == 'U') sequencers[6].toggleMute(); if(P.p.key == 'I') sequencers[7].toggleMute(); if(P.p.key == 'A') sequencers[0].loadNextSound(); if(P.p.key == 'S') sequencers[1].loadNextSound(); if(P.p.key == 'D') sequencers[2].loadNextSound(); if(P.p.key == 'F') sequencers[3].loadNextSound(); if(P.p.key == 'G') sequencers[4].loadNextSound(); if(P.p.key == 'H') sequencers[5].loadNextSound(); if(P.p.key == 'J') sequencers[6].loadNextSound(); if(P.p.key == 'K') sequencers[7].loadNextSound(); if(P.p.key == 'Z') sequencers[0].toggleEvloves(); if(P.p.key == 'X') sequencers[1].toggleEvloves(); if(P.p.key == 'C') sequencers[2].toggleEvloves(); if(P.p.key == 'V') sequencers[3].toggleEvloves(); if(P.p.key == 'B') sequencers[4].toggleEvloves(); if(P.p.key == 'N') sequencers[5].toggleEvloves(); if(P.p.key == 'M') sequencers[6].toggleEvloves(); if(P.p.key == '<') sequencers[7].toggleEvloves(); // if(P.p.key == 'o') P.out(outputConfigSingleLine()); if(P.p.key == 'o') saveJsonConfigToFile(); if(P.p.key == 'O') rewriteCurJsonFile(); // if(P.p.key == 'p') loadConfig("{\"sequencers\": [ { \"volume\": 1, \"sampleIndex\": 19, \"noteOffset\": 3, \"notesByStep\": true, \"steps\": [ 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1 ] }, { \"volume\": 1, \"sampleIndex\": 22, \"noteOffset\": 6, \"notesByStep\": false, \"steps\": [ 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 ] }, { \"volume\": 1, \"sampleIndex\": 29, \"noteOffset\": 13, \"notesByStep\": true, \"steps\": [ 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0 ] }, { \"volume\": 1, \"sampleIndex\": 35, \"noteOffset\": 7, \"notesByStep\": true, \"steps\": [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] } ]}"); // if(P.p.key == 'p') loadConfigFromFile("2022-01-16-20-34-35.json"); if(configFiles.size() > 0) { if(P.p.key == '9') { curConfigIndex--; curConfigIndex = P.max(curConfigIndex, 0); loadConfigFromFile(configFiles.get(curConfigIndex)); } if(P.p.key == '0') { curConfigIndex++; curConfigIndex = P.min(curConfigIndex, configFiles.size() - 1); loadConfigFromFile(configFiles.get(curConfigIndex)); } } } // JSON CONFIGS protected void loadConfigFiles() { if(FileUtil.fileOrPathExists(FileUtil.getPath(SEQUENCES_PATH))) { configFiles = FileUtil.getFilesInDirOfType(FileUtil.getPath(SEQUENCES_PATH), "json"); } } public JSONObject outputConfig() { JSONObject interphaseConfig = new JSONObject(); // add global props interphaseConfig.setFloat(BPM, P.store.getInt(BPM)); // add sequencers' data JSONArray sequencersJSON = new JSONArray(); interphaseConfig.setJSONArray("sequencers", sequencersJSON); for (int i = 0; i < numChannels(); i++) { Sequencer seq = sequencerAt(i); sequencersJSON.setJSONObject(i, seq.json()); } return interphaseConfig; } public String outputConfigSingleLine() { return JsonUtil.jsonToSingleLine(outputConfig()); } public void saveJsonConfigToFile() { FileUtil.createDir(FileUtil.getPath(SEQUENCES_PATH)); String jsonFilename = SystemUtil.getTimestamp() + ".json"; String jsonSavePath = FileUtil.getPath(SEQUENCES_PATH + jsonFilename); JsonUtil.jsonToFile(outputConfig(), jsonSavePath); configFiles.add(jsonFilename); curConfigIndex = configFiles.size() - 1; } public void rewriteCurJsonFile() { // when we want to update an existing json :) FileUtil.createDir(FileUtil.getPath(SEQUENCES_PATH)); String jsonFilename = configFiles.get(curConfigIndex); String jsonSavePath = FileUtil.getPath(SEQUENCES_PATH + jsonFilename); JsonUtil.jsonToFile(outputConfig(), jsonSavePath); } protected void loadConfig(String jsonStr) { JSONObject jsonConfig = JsonUtil.jsonFromString(jsonStr); loadConfig(jsonConfig); } protected void loadConfigFromFile(String filename) { JSONObject interphaseConfig = JsonUtil.jsonFromFile(FileUtil.getPath(SEQUENCES_PATH + filename)); loadConfig(interphaseConfig); } protected void loadConfig(JSONObject interphaseConfig) { // load global props if(UI.has(UI_GLOBAL_BPM)) UI.setValue(UI_GLOBAL_BPM, interphaseConfig.getInt(BPM)); // just in case UI wasn't initialized P.store.setNumber(BPM, interphaseConfig.getInt(BPM)); // add sequencers' data JSONArray sequencersDataArray = interphaseConfig.getJSONArray("sequencers"); for (int i = 0; i < sequencersDataArray.size(); i++) { Sequencer seq = sequencerAt(i); JSONObject sequencerDataObj = sequencersDataArray.getJSONObject(i); seq.load(sequencerDataObj); // make sure to update UI to keep in sync String uiSampleKey = UI_SAMPLE_+(i+1); String uiVolumeKey = UI_VOLUME_+(i+1); if(UI.has(uiSampleKey)) UI.setValue(UI_SAMPLE_+(i+1), seq.sampleIndex()); if(UI.has(uiVolumeKey)) UI.setValue(UI_VOLUME_+(i+1), seq.volume()); } } // LAUNCHPAD INTEGRATION protected void updateLaunchpads() { if(launchpad1 == null) return; // split across launchpads for (int i = 0; i < sequencers.length; i++) { for (int step = 0; step < NUM_STEPS; step++) { float value = (sequencers[i].stepActive(step)) ? 1 : 0; float adjustedVal = value; if(value == 0 && step % 4 == 0) adjustedVal = 0.3f; // show divisor by 4 if(value == 0 && step == P.store.getInt(CUR_STEP)) adjustedVal = 0.65f; // show playhead in row if(step <= 7) { launchpad1.setButton(i, step, adjustedVal); } else { launchpad2.setButton(i, step - 8, adjustedVal); } } } // update playhead row in play button column on 1st-gen Launchpad /* if(launchpad1 instanceof LaunchPadMini == false) { int lastColIndex = 8; for (int step = 0; step < NUM_STEPS; step++) { float value = (step == P.store.getInt(CUR_STEP)) ? 0.68f : 0; if(step <= 7) { launchpad1.setButton(lastColIndex, step, value); } else { launchpad2.setButton(lastColIndex, step - 8, value); } } } */ } // Bridge to UIControls for mouse control protected void updateUIGridButtons() { if(!hasUI) return; // split across launchpads for (int i = 0; i < sequencers.length; i++) { int channel = i; for (int step = 0; step < NUM_STEPS; step++) { float value = (sequencers[i].stepActive(step)) ? 1 : 0; String buttonId = "beatgrid-"+channel+"-"+step; UI.get(buttonId).set(value); if(step % 4 == 0) { if(UI.active()) { P.p.fill(127); P.p.rect(0, 10 + IUIControl.controlSpacing * step, IUIControl.controlW + 20, IUIControl.controlH); } } } } // playhead if(UI.active()) { P.p.fill(255); P.p.rect(0, IUIControl.controlSpacing * P.store.getInt(CUR_STEP), IUIControl.controlW + 20, IUIControl.controlH); } } ///////////////////////////////// // DRAW ///////////////////////////////// protected void checkInputs() { // sample triggers & evolve // if(trigger1.triggered()) { sequencers[0].evolvePattern(); sequencers[0].triggerSample(); } // if(trigger2.triggered()) { sequencers[1].evolvePattern(); sequencers[1].triggerSample(); } // if(trigger3.triggered()) { sequencers[2].evolvePattern(); sequencers[2].triggerSample(); } // if(trigger4.triggered()) { sequencers[3].evolvePattern(); sequencers[3].triggerSample(); } // if(trigger5.triggered()) { sequencers[4].evolvePattern(); sequencers[4].triggerSample(); } // if(trigger6.triggered()) { sequencers[5].evolvePattern(); sequencers[5].triggerSample(); } // if(trigger7.triggered()) { sequencers[6].evolvePattern(); sequencers[6].triggerSample(); } // if(trigger8.triggered()) { sequencers[7].evolvePattern(); sequencers[7].triggerSample(); } // bpm int curBmpMIDI = P.store.getInt(Interphase.BPM); if(triggerDown.triggered()) P.store.setNumber(Interphase.BPM, curBmpMIDI - 1); if(triggerUp.triggered()) P.store.setNumber(Interphase.BPM, curBmpMIDI + 1); // global settings // if(trigger9.triggered()) P.store.setBoolean(GLOBAL_PATTERNS_EVLOVE, !P.store.getBoolean(GLOBAL_PATTERNS_EVLOVE)); } public void update() { update(null); } public void update(PGraphics pg) { // check inputs & advance sequencers checkInputs(); updateSequencers(); updateUIGridButtons(); updateDebugValues(); if(pg != null) drawSequencer(pg); } protected void updateSequencers() { // update sequencers & draw to wall PG. also set overall user activity for tempo change float numWallsInteracted = 0; for (int i = 0; i < sequencers.length; i++) { sequencers[i].update(); if(sequencers[i].userInteracted()) numWallsInteracted++; } P.store.setNumber(INTERACTION_SPEED_MULT, numWallsInteracted); } protected void updateDebugValues() { DebugView.setValue("INTERPHASE :: BPM", P.store.getFloat(BPM)); DebugView.setValue("INTERPHASE :: BEAT", P.store.getFloat(BEAT)); DebugView.setValue("INTERPHASE :: INTERACTION_SPEED_MULT", P.store.getFloat(INTERACTION_SPEED_MULT)); DebugView.setValue("INTERPHASE :: PATTERNS_AUTO_MORPH", P.store.getBoolean(GLOBAL_PATTERNS_EVLOVE)); DebugView.setValue("INTERPHASE :: SEQUENCER_TRIGGER", P.store.getInt(SEQUENCER_TRIGGER)); DebugView.setValue("INTERPHASE :: CUR_SCALE", Scales.SCALE_NAMES[P.store.getInt(CUR_SCALE_INDEX)]); } protected void drawSequencer(PGraphics pg) { float spacing = 40; float boxSize = 25; float startx = (spacing * sequencers.length) / -2f + boxSize/2; float startY = (spacing * NUM_STEPS) / -2f + boxSize/2; pg.beginDraw(); PG.setCenterScreen(pg); PG.basicCameraFromMouse(pg, 0.1f); PG.setBetterLights(pg); PG.setDrawCenter(pg); // draw cubes for (int x = 0; x < sequencers.length; x++) { for (int y = 0; y < NUM_STEPS; y++) { // float value = (sequencers[x].stepActive(y)) ? 1 : 0; boolean isOn = (sequencers[x].stepActive(y)); pg.fill(isOn ? P.p.color(255) : 30); pg.pushMatrix(); pg.translate(startx + x * spacing, startY + y * spacing); pg.box(20); pg.popMatrix(); } } // show beat/4 for (int y = 0; y < NUM_STEPS; y+=4) { // float value = (sequencers[x].stepActive(y)) ? 1 : 0; pg.stroke(255); pg.noFill(); pg.pushMatrix(); pg.translate(-boxSize/2, startY + y * spacing); Shapes.drawDashedBox(pg, spacing * (sequencers.length + 1), boxSize, boxSize, 10, true); pg.popMatrix(); } // track current beat int curBeat = P.store.getInt(BEAT) % NUM_STEPS; pg.stroke(255); pg.noFill(); pg.pushMatrix(); pg.translate(-boxSize/2, startY + curBeat * spacing); pg.box(spacing * (sequencers.length + 1), boxSize, boxSize); pg.popMatrix(); pg.endDraw(); } ///////////////////////////////// // LAUNCHPAD CALLBACK ///////////////////////////////// public void cellUpdated(LaunchPad launchpad, int x, int y, float value) { // apply toggle button press int launchpadNumber = (launchpad == launchpad1) ? 1 : 2; // P.out(launchpadNumber, x, y, value); int step = (launchpadNumber == 1) ? y : 8 + y; boolean isActive = (value == 1f); if(x < NUM_CHANNELS) sequencers[x].stepActive(step, isActive); } public void noteOn(LaunchPad launchpad, int note, float value) { int launchpadNumber = (launchpad == launchpad1) ? 1 : 2; // P.out("Interphase.noteOn", launchpadNumber, note, value); // special functions on original paunchpad. // launchpad mini doesn't send MIDI notes from 9th row/col of buttons if(launchpad1 instanceof LaunchPadMini == false) { if(launchpadNumber == 1) { for (int i = 0; i < NUM_CHANNELS; i++) { if(note == LaunchPad.headerColMidiNote(i)) sequencers[i].evolvePattern(); } } else { // change sample for (int i = 0; i < NUM_CHANNELS; i++) { if(note == LaunchPad.headerColMidiNote(i)) sequencers[i].loadNextSound(); } // bpm up/down int curBmpMIDI = P.store.getInt(Interphase.BPM); if(note == LaunchPad.groupRowMidiNote(1)) P.store.setNumber(Interphase.BPM, curBmpMIDI - 1); if(note == LaunchPad.groupRowMidiNote(0)) P.store.setNumber(Interphase.BPM, curBmpMIDI + 1); } } } ////////////////////////// // IAppStoreListener updates ////////////////////////// public void updatedNumber(String key, Number val) { // connect to sequencer UI if(key.indexOf("beatgrid-") == 0) { String[] components = key.split("-"); int gridX = ConvertUtil.stringToInt(components[1]); int gridY = ConvertUtil.stringToInt(components[2]); boolean isActive = (val.intValue() == 1); sequencers[gridX].stepActive(gridY, isActive); } // update launchpads with BEAT delay if(key.equals(BEAT)) updateLaunchpads(); // connect local UI events to global settings if(key.equals(UI_GLOBAL_BPM)) P.store.setNumber(Interphase.BPM, val.floatValue()); if(key.equals(UI_CUR_SCALE)) P.store.setNumber(Interphase.CUR_SCALE_INDEX, val.intValue()); if(key.equals(UI_GLOBAL_EVOLVES)) P.store.setBoolean(Interphase.GLOBAL_PATTERNS_EVLOVE, val.intValue() == 1); // toggle events are 0-1, not boolean !!! // set sample/volume props for specific channels if(key.indexOf(UI_SAMPLE_) == 0) { String sequencerNum = key.substring(UI_SAMPLE_.length(), key.length() - 0); // used to break after 9 channels, should work for higher numbers int sequencerIndex = ConvertUtil.stringToInt(sequencerNum) - 1; // use key to grab sample index sequencerAt(sequencerIndex).setSampleByIndex(val.intValue()); } if(key.indexOf(UI_VOLUME_) == 0) { String sequencerNum = key.substring(UI_SAMPLE_.length(), key.length() - 0); // TODO: this will break after 9 channels!!!! int sequencerIndex = ConvertUtil.stringToInt(sequencerNum) - 1; sequencerAt(sequencerIndex).volume(val.floatValue()); } } public void updatedString(String key, String val) { if(key.equals(PEvents.KEY_PRESSED)) keyPressed(); } public void updatedBoolean(String key, Boolean val) { } public void updatedImage(String key, PImage val) {} public void updatedBuffer(String key, PGraphics val) {} }
package com.miloshpetrov.sol2.game; import com.miloshpetrov.sol2.common.SolMath; import com.miloshpetrov.sol2.game.gun.GunConfig; import com.miloshpetrov.sol2.game.gun.GunItem; import com.miloshpetrov.sol2.game.item.*; import com.miloshpetrov.sol2.game.maze.MazeConfig; import com.miloshpetrov.sol2.game.planet.PlanetConfig; import com.miloshpetrov.sol2.game.planet.SysConfig; import com.miloshpetrov.sol2.game.projectile.ProjectileConfig; import com.miloshpetrov.sol2.game.ship.*; import com.miloshpetrov.sol2.game.ship.hulls.GunSlot; import com.miloshpetrov.sol2.game.ship.hulls.HullConfig; import com.miloshpetrov.sol2.game.ship.hulls.Hull; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class HardnessCalc { public static final float SHIELD_MUL = 1.2f; public static float getGunMeanDps(GunConfig gc) { ClipConfig cc = gc.clipConf; ProjectileConfig pc = cc.projConfig; float projDmg = pc.dmg; if (pc.emTime > 0) projDmg = 150; else if (pc.density > 0) projDmg += 10; float projHitChance; if (pc.guideRotSpd > 0) { projHitChance = .9f; } else if (pc.zeroAbsSpd) { projHitChance = 0.1f; } else { projHitChance = (pc.spdLen + pc.acc) / 6; if (pc.physSize > 0) projHitChance += pc.physSize; projHitChance = SolMath.clamp(projHitChance, .1f, 1); if (gc.fixed) { projHitChance *= .3f; } } float shotDmg = projDmg * projHitChance; return getShotDps(gc, shotDmg); } public static float getShotDps(GunConfig gc, float shotDmg) { ClipConfig cc = gc.clipConf; int projectilesPerShot = cc.projectilesPerShot; if (gc.timeBetweenShots == 0) projectilesPerShot = cc.size; if (projectilesPerShot > 1) shotDmg *= .6f * projectilesPerShot; float timeBetweenShots = gc.timeBetweenShots == 0 ? gc.reloadTime : gc.timeBetweenShots; return shotDmg / timeBetweenShots; } private static float getItemCfgDps(ItemConfig ic, boolean fixed) { float dps = 0; for (SolItem e : ic.examples) { if (!(e instanceof GunItem)) throw new AssertionError("all item options must be of the same type"); GunItem g = (GunItem) e; if (g.config.fixed != fixed) { String items = ""; for (SolItem ex : ic.examples) { items += ex.getDisplayName() + " "; } throw new AssertionError("all gun options must have equal fixed param: " + items); } dps += g.config.meanDps; } return dps / ic.examples.size() * ic.chance; } public static float getShipConfDps(ShipConfig sc, ItemManager itemManager) { final List<ItemConfig> parsedItems = itemManager.parseItems(sc.items); final List<GunSlot> unusedGunSlots = sc.hull.getGunSlotList(); float dps = 0; Iterator<ItemConfig> itemConfigIterator = parsedItems.iterator(); while(itemConfigIterator.hasNext() && !unusedGunSlots.isEmpty()) { ItemConfig itemConfig = itemConfigIterator.next(); final SolItem item = itemConfig.examples.get(0); if (item instanceof GunItem) { final GunItem gunItem = (GunItem) item; final Iterator<GunSlot> gunSlotIterator = unusedGunSlots.listIterator(); boolean matchingSlotFound = false; while (gunSlotIterator.hasNext() && !matchingSlotFound) { final GunSlot gunSlot = gunSlotIterator.next(); if (gunItem.config.fixed != gunSlot.allowsRotation()) { dps += getItemCfgDps(itemConfig, gunItem.config.fixed); gunSlotIterator.remove(); matchingSlotFound = true; } } } } return dps; } public static float getShipCfgDmgCap(ShipConfig sc, ItemManager itemManager) { List<ItemConfig> parsed = itemManager.parseItems(sc.items); float meanShieldLife = 0; float meanArmorPerc = 0; for (ItemConfig ic : parsed) { SolItem item = ic.examples.get(0); if (meanShieldLife == 0 && item instanceof Shield) { for (SolItem ex : ic.examples) { meanShieldLife += ((Shield) ex).getLife(); } meanShieldLife /= ic.examples.size(); meanShieldLife *= ic.chance; } if (meanArmorPerc == 0 && item instanceof Armor) { for (SolItem ex : ic.examples) { meanArmorPerc += ((Armor) ex).getPerc(); } meanArmorPerc /= ic.examples.size(); meanArmorPerc *= ic.chance; } } return sc.hull.getMaxLife() / (1 - meanArmorPerc) + meanShieldLife * SHIELD_MUL; } private static float getShipConfListDps(List<ShipConfig> ships) { float maxDps = 0; for (ShipConfig e : ships) { if (maxDps < e.dps) maxDps = e.dps; } return maxDps; } public static float getGroundDps(PlanetConfig pc, float grav) { float groundDps = getShipConfListDps(pc.groundEnemies); float bomberDps = getShipConfListDps(pc.lowOrbitEnemies); float res = bomberDps < groundDps ? groundDps : bomberDps; float gravFactor = 1 + grav * .5f; return res * gravFactor; } public static float getAtmDps(PlanetConfig pc) { return getShipConfListDps(pc.highOrbitEnemies); } public static float getMazeDps(MazeConfig c) { float outer = getShipConfListDps(c.outerEnemies); float inner = getShipConfListDps(c.innerEnemies); float res = inner < outer ? outer : inner; return res * 1.25f; } public static float getBeltDps(SysConfig c) { return 1.2f * getShipConfListDps(c.tempEnemies); } public static float getSysDps(SysConfig c, boolean inner) { return getShipConfListDps(inner ? c.innerTempEnemies : c.tempEnemies); } private static float getGunDps(GunItem g) { if (g == null) return 0; return g.config.meanDps; } public static float getShipDps(SolShip s) { Hull h = s.getHull(); return getGunDps(h.getGun(false)) + getGunDps(h.getGun(true)); } public static float getFarShipDps(FarShip s) { return getGunDps(s.getGun(false)) + getGunDps(s.getGun(true)); } public static float getShipDmgCap(SolShip s) { return getDmgCap(s.getHull().config, s.getArmor(), s.getShield()); } public static float getFarShipDmgCap(FarShip s) { return getDmgCap(s.getHullConfig(), s.getArmor(), s.getShield()); } private static float getDmgCap(HullConfig hull, Armor armor, Shield shield) { float r = hull.getMaxLife(); if (armor != null) r *= 1 / (1 - armor.getPerc()); if (shield != null) r += shield.getMaxLife() * SHIELD_MUL; return r; } public static boolean isDangerous(float destDmgCap, float dps) { float killTime = destDmgCap / dps; return killTime < 5; } public static boolean isDangerous(float destDmgCap, Object srcObj) { float dps = getShipObjDps(srcObj); return isDangerous(destDmgCap, dps); } public static float getShipObjDps(Object srcObj) { return srcObj instanceof SolShip ? getShipDps((SolShip) srcObj) : getFarShipDps((FarShip) srcObj); } }
/* * 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.dubbo.rpc.filter; import org.apache.dubbo.common.beanutil.JavaBeanAccessor; import org.apache.dubbo.common.beanutil.JavaBeanDescriptor; import org.apache.dubbo.common.beanutil.JavaBeanSerializeUtil; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.io.UnsafeByteArrayInputStream; import org.apache.dubbo.common.io.UnsafeByteArrayOutputStream; import org.apache.dubbo.common.serialize.Serialization; import org.apache.dubbo.common.utils.PojoUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcContext; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.RpcInvocation; import org.apache.dubbo.rpc.service.GenericException; import org.apache.dubbo.rpc.service.GenericService; import org.apache.dubbo.rpc.support.ProtocolUtils; import java.io.IOException; import java.lang.reflect.Method; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE; import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE_ASYNC; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_PROTOBUF; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; /** * GenericInvokerFilter. */ @Activate(group = CommonConstants.PROVIDER, order = -20000) public class GenericFilter implements Filter, Filter.Listener { @Override public Result invoke(Invoker<?> invoker, Invocation inv) throws RpcException { if ((inv.getMethodName().equals($INVOKE) || inv.getMethodName().equals($INVOKE_ASYNC)) && inv.getArguments() != null && inv.getArguments().length == 3 && !GenericService.class.isAssignableFrom(invoker.getInterface())) { String name = ((String) inv.getArguments()[0]).trim(); String[] types = (String[]) inv.getArguments()[1]; Object[] args = (Object[]) inv.getArguments()[2]; try { Method method = ReflectUtils.findMethodByMethodSignature(invoker.getInterface(), name, types); Class<?>[] params = method.getParameterTypes(); if (args == null) { args = new Object[params.length]; } String generic = (String) inv.getAttachment(GENERIC_KEY); if (StringUtils.isBlank(generic)) { generic = (String) RpcContext.getContext().getAttachment(GENERIC_KEY); } if (StringUtils.isEmpty(generic) || ProtocolUtils.isDefaultGenericSerialization(generic) || ProtocolUtils.isGenericReturnRawResult(generic)) { args = PojoUtils.realize(args, params, method.getGenericParameterTypes()); } else if (ProtocolUtils.isJavaGenericSerialization(generic)) { for (int i = 0; i < args.length; i++) { if (byte[].class == args[i].getClass()) { try (UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream((byte[]) args[i])) { args[i] = ExtensionLoader.getExtensionLoader(Serialization.class) .getExtension(GENERIC_SERIALIZATION_NATIVE_JAVA) .deserialize(null, is).readObject(); } catch (Exception e) { throw new RpcException("Deserialize argument [" + (i + 1) + "] failed.", e); } } else { throw new RpcException( "Generic serialization [" + GENERIC_SERIALIZATION_NATIVE_JAVA + "] only support message type " + byte[].class + " and your message type is " + args[i].getClass()); } } } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { for (int i = 0; i < args.length; i++) { if (args[i] instanceof JavaBeanDescriptor) { args[i] = JavaBeanSerializeUtil.deserialize((JavaBeanDescriptor) args[i]); } else { throw new RpcException( "Generic serialization [" + GENERIC_SERIALIZATION_BEAN + "] only support message type " + JavaBeanDescriptor.class.getName() + " and your message type is " + args[i].getClass().getName()); } } } else if (ProtocolUtils.isProtobufGenericSerialization(generic)) { // as proto3 only accept one protobuf parameter if (args.length == 1 && args[0] instanceof String) { try (UnsafeByteArrayInputStream is = new UnsafeByteArrayInputStream(((String) args[0]).getBytes())) { args[0] = ExtensionLoader.getExtensionLoader(Serialization.class) .getExtension("" + GENERIC_SERIALIZATION_PROTOBUF) .deserialize(null, is).readObject(method.getParameterTypes()[0]); } catch (Exception e) { throw new RpcException("Deserialize argument failed.", e); } } else { throw new RpcException( "Generic serialization [" + GENERIC_SERIALIZATION_PROTOBUF + "] only support one" + String.class.getName() + " argument and your message size is " + args.length + " and type is" + args[0].getClass().getName()); } } RpcInvocation rpcInvocation = new RpcInvocation(method, invoker.getInterface().getName(), args, inv.getAttachments(), inv.getAttributes()); rpcInvocation.setInvoker(inv.getInvoker()); rpcInvocation.setTargetServiceUniqueName(inv.getTargetServiceUniqueName()); return invoker.invoke(rpcInvocation); } catch (NoSuchMethodException e) { throw new RpcException(e.getMessage(), e); } catch (ClassNotFoundException e) { throw new RpcException(e.getMessage(), e); } } return invoker.invoke(inv); } @Override public void onMessage(Result appResponse, Invoker<?> invoker, Invocation inv) { if ((inv.getMethodName().equals($INVOKE) || inv.getMethodName().equals($INVOKE_ASYNC)) && inv.getArguments() != null && inv.getArguments().length == 3 && !GenericService.class.isAssignableFrom(invoker.getInterface())) { String generic = (String) inv.getAttachment(GENERIC_KEY); if (StringUtils.isBlank(generic)) { generic = (String) RpcContext.getContext().getAttachment(GENERIC_KEY); } if (appResponse.hasException() && !(appResponse.getException() instanceof GenericException)) { appResponse.setException(new GenericException(appResponse.getException())); } if (ProtocolUtils.isJavaGenericSerialization(generic)) { try { UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512); ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(GENERIC_SERIALIZATION_NATIVE_JAVA).serialize(null, os).writeObject(appResponse.getValue()); appResponse.setValue(os.toByteArray()); } catch (IOException e) { throw new RpcException( "Generic serialization [" + GENERIC_SERIALIZATION_NATIVE_JAVA + "] serialize result failed.", e); } } else if (ProtocolUtils.isBeanGenericSerialization(generic)) { appResponse.setValue(JavaBeanSerializeUtil.serialize(appResponse.getValue(), JavaBeanAccessor.METHOD)); } else if (ProtocolUtils.isProtobufGenericSerialization(generic)) { try { UnsafeByteArrayOutputStream os = new UnsafeByteArrayOutputStream(512); ExtensionLoader.getExtensionLoader(Serialization.class) .getExtension(GENERIC_SERIALIZATION_PROTOBUF) .serialize(null, os).writeObject(appResponse.getValue()); appResponse.setValue(os.toString()); } catch (IOException e) { throw new RpcException("Generic serialization [" + GENERIC_SERIALIZATION_PROTOBUF + "] serialize result failed.", e); } } else if(ProtocolUtils.isGenericReturnRawResult(generic)) { return; } else { appResponse.setValue(PojoUtils.generalize(appResponse.getValue())); } } } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { } }
/******************************************************************************* * Copyright (c) 2013 Sebastian Funke. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html * * Contributors: * Sebastian Funke - initial API and implementation ******************************************************************************/ package de.tud.textureAttack.model; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import de.tud.textureAttack.controller.ActionController; import de.tud.textureAttack.model.AdvancedTextureImage.EditState; import de.tud.textureAttack.model.algorithms.Options; import de.tud.textureAttack.model.algorithms.attacks.AbstractAttackAlgorithm; import de.tud.textureAttack.model.algorithms.selection.AbstractSelectionAlgorithm; import de.tud.textureAttack.model.io.InvalidTextureException; import de.tud.textureAttack.view.components.StatusBar; public class WorkingImageSet { private ArrayList<AdvancedTextureImage> imageList; private ActionController actionController; public WorkingImageSet(ActionController actionController) { imageList = new ArrayList<AdvancedTextureImage>(); this.actionController = actionController; } public ArrayList<BufferedImage> getOriginialImages() { ArrayList<BufferedImage> list = new ArrayList<BufferedImage>(); for (AdvancedTextureImage img : imageList) { list.add(img.getOriginalBufferedImage()); } return list; } public void clearImages() { imageList.clear(); } public void addAdvancedImageTexture(AdvancedTextureImage img) { imageList.add(img); } public void removeAdvancedTextureImage(int i) { imageList.remove(i); } /** * Gets the absoluteFilePaths of loaded images, creates from them the * AdvancedTextureImages and stores it in the working set * * @param files * @param baseDir * Base Directory of the files, for saving later with dir * structure */ public void setTextures(File[] files, String baseDir) { if (files != null) { imageList.clear(); actionController.setProgressCount(files.length); actionController.setStatus("Loading Textures......."); for (int i = 0; i < files.length; i++) { try { actionController.setProgress(i); AdvancedTextureImage img = new AdvancedTextureImage( files[i].getAbsolutePath(), baseDir); imageList.add(img); } catch (InvalidTextureException | IOException e) { System.out.println("ERROR: " + e.getMessage()); e.printStackTrace(); } } } } public ArrayList<BufferedImage> getEditedImages() { ArrayList<BufferedImage> images = new ArrayList<BufferedImage>(); for (AdvancedTextureImage img : imageList) images.add(img.getEditedBufferedImage()); return images; } public BufferedImage getEditedImage(int index) { return imageList.get(index).getEditedBufferedImage(); } /** * Returns the original Image of the specified index (loads the image, * before) if it exists, else null * * @param selectedImagePosition * @return BufferedImage */ public BufferedImage getOriginialImage(int selectedImagePosition) { if (imageList.isEmpty() || (selectedImagePosition > imageList.size())) return null; else { if (imageList.get(selectedImagePosition).getEditedBufferedImage() == null) imageList.get(selectedImagePosition).loadImage(); return imageList.get(selectedImagePosition) .getOriginalBufferedImage(); } } /** * Returns the AdvancedTextureImage not loaded with the given Index i if it * is in the set, else null * * @param i * @return AdvancedTextureImage */ public AdvancedTextureImage getAdvancedTextureImage(int i) { if (imageList.isEmpty() || (i > imageList.size())) return null; else { return imageList.get(i); } } /** * Returns the AdvancedTextureImage loaded (load image data before, if not * loaded) with the given Index i if it is in the set, else null * * @param i * @return AdvancedTextureImage */ public AdvancedTextureImage getLoadedAdvancedTextureImage(int i) { if (imageList.isEmpty() || (i > imageList.size())) return null; else { if (imageList.get(i).getEditedBufferedImage() == null) { imageList.get(i).loadImage(); } return imageList.get(i); } } public ArrayList<AdvancedTextureImage> getAdvancedTextureImages() { return imageList; } /** * Saves all Textures of the set with their folder structure to the * specified absolutePath and deletes their tmp image files (created during * manipulation) * * @param absolutePath */ public void saveTextures(String absolutePath) { actionController.setProgressCount(imageList.size()); int i = 0; for (AdvancedTextureImage img : imageList) { if (img.getState() != EditState.unsupported){ actionController.setProgress(i); i++; img.writeTextureToPath(absolutePath); if (img.getTmpSavePath() != null) { // tmpSavePath: delete tmp image File file = new File(img.getTmpSavePath()); if (file.exists()) file.delete(); img.setTmpSavePath(null); } } } } /** * Returns the advances texture image, which matches the given * absoluteFilePath (the path from the source texture), or null if there is * no such a advanced texture image * * @param path * @return AdvancedTextureImage */ public AdvancedTextureImage getAdvancedTextureImageFromAbsoluteFilePath( String path) { for (int i = 0; i < imageList.size(); i++) { if (imageList.get(i).getAbsolutePath().equals(path)) return imageList.get(i); } return null; } /** * Manipulated all images in the set, with the given background selection * algorithm, pixel manipulation algorithm with the given options * * @param attackAlgorithm * @param selectAlgorithm * @param options */ public void manipulateAllImages(AbstractAttackAlgorithm attackAlgorithm, AbstractSelectionAlgorithm selectAlgorithm, Options options, StatusBar statusBar) { int i = 0; actionController.getStatusBar().setImageProgressParameter( imageList.size()); for (AdvancedTextureImage advImage : imageList) { if (advImage.getState() != EditState.unsupported){ advImage.processManipulation(attackAlgorithm, selectAlgorithm, options, statusBar); actionController.getStatusBar().setImageProgress(i); i++; actionController.setTextureIcon(advImage); actionController.getStatusBar().resetAlgorithms(); // reset the algorithms, because they are swingworker and need to be // reseted attackAlgorithm = (AbstractAttackAlgorithm) actionController .getAlgorithm(attackAlgorithm.getName()); selectAlgorithm = (AbstractSelectionAlgorithm) actionController .getAlgorithm(selectAlgorithm.getName()); if (actionController.getStatusBar().getCanceledAutoAttack()) break; } } actionController.getStatusBar().doneAll(); } public void saveTexture(String absolutePath, String selectedImageByPath) { AdvancedTextureImage img = getAdvancedTextureImageFromAbsoluteFilePath(selectedImageByPath); if (img.getState() != EditState.unsupported){ img.writeTextureToPath(absolutePath); if (img.getTmpSavePath() != null) { // tmpSavePath: delete tmp image File file = new File(img.getTmpSavePath()); if (file.exists()) file.delete(); img.setTmpSavePath(null); } } } public ArrayList<String> getUnsupportedTexturePaths() { ArrayList<String> result = new ArrayList<String>(); for (AdvancedTextureImage img : imageList){ if (img.getState() == EditState.unsupported) result.add(img.getAbsolutePath()); } return result; } public int getTextureCount() { return imageList.size(); } }
package ch.usi.dag.disl; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.jar.Attributes; import java.util.jar.Manifest; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import ch.usi.dag.disl.util.Logging; import ch.usi.dag.util.logging.Logger; /** * Provides access to DiSL and transformer class names discovered from manifest * files and system properties. * * @author Lubomir Bulej */ final class ClassResources { private static final String __MANIFEST__ = "META-INF/MANIFEST.MF"; private static final String __ATTR_DISL_CLASSES__ = "DiSL-Classes"; private static final String __ATTR_DISL_TRANSFORMER__ = "DiSL-Transformer"; private static final String __ATTR_DISL_TRANSFORMERS__ = "DiSL-Transformers"; private static final String __PROP_DISL_CLASSES__ = "disl.classes"; private static final String __SEPARATOR__ = ","; // private final List <DislManifest> __manifests; private ClassResources (final List <DislManifest> manifests) { __manifests = manifests; } // /** * @return Stream of all distinct resources containing DiSL classes. */ public Stream <URL> instrumentationResources () { return __manifests.stream () .filter (DislManifest::isInstrumentation) .map (DislManifest::resource) .filter (Optional::isPresent) // excludes properties .map (Optional::get) .distinct (); } /** * @return Stream of all transformer class names extracted from manifest * files and properties used to initialize a {@link DiSL} instance. */ public Stream <String> transformers () { return __manifests.stream () .flatMap (DislManifest::transformers); } /** * @return Stream of all distinct DiSL class names extracted from manifest * files and properties used to initialize a {@link DiSL} instance. */ public Stream <String> dislClasses () { return __manifests.stream () .flatMap (DislManifest::classes) .distinct (); } // /** * Discovers DiSL resources. Extracts the names of DiSL and transformer * classes from manifest files found in the class path and in properties * used to initialize a {@link DiSL} instance. */ public static final ClassResources discover (final Properties properties) { final Logger log = Logging.getPackageInstance (); // Get class names from manifests in the class path. final ManifestLoader ml = new ManifestLoader (log); final List <DislManifest> manifests = ml.loadAll (); // Get class names from system properties. final List <String> dislClasses = __getClassNames ( Optional.ofNullable (properties.getProperty (__PROP_DISL_CLASSES__)) ).orElse (Collections.emptyList ()); manifests.add (new DislManifest (dislClasses)); return new ClassResources (manifests); } // private static final Pattern __splitter__ = Pattern.compile (__SEPARATOR__); private static Optional <List <String>> __getClassNames (final Optional <String> value) { return value.map (v -> __splitter__.splitAsStream (v) .map (String::trim) .filter (s -> !s.isEmpty ()) .collect (Collectors.toList ()) ); } // private static final class ManifestLoader { private final Logger __log; ManifestLoader (final Logger log) { __log = log; } // List <DislManifest> loadAll () { return __manifestUrlStream () // .parallel () // keep ordering for transformers .map (url -> __loadManifest (url)) .filter (Optional::isPresent) .map (Optional::get) .filter (m -> !m.isEmpty ()) .collect (Collectors.toList ()); } private Stream <URL> __manifestUrlStream () { final ArrayList <URL> result = new ArrayList <> (); try { final Enumeration <URL> resources = ClassLoader.getSystemResources (__MANIFEST__); while (resources.hasMoreElements()) { result.add (resources.nextElement ()); } } catch (final IOException ioe) { __log.warn (ioe, "failed to enumerate manifest resources"); } return result.stream (); } private Optional <DislManifest> __loadManifest (final URL url) { try ( final InputStream is = url.openStream (); ) { final Manifest manifest = new Manifest (is); // // Extract DiSL and transformer class names from the manifest. // Merge classes from DiSL-Transformer and DiSL-Transformers. // final Optional <Attributes> attrs = Optional.ofNullable (manifest.getMainAttributes ()); final List <String> classes = __getClasses (attrs, __ATTR_DISL_CLASSES__); final List <String> transformers = __getClasses (attrs, __ATTR_DISL_TRANSFORMER__); transformers.addAll (__getClasses (attrs, __ATTR_DISL_TRANSFORMERS__)); if (__log.debugIsLoggable ()) { __log.debug ( "loaded %s, classes [%s], transformers [%s]", url, String.join (",", classes), String.join (",", transformers) ); } return Optional.of (new DislManifest (url, classes, transformers)); } catch (final IOException ioe) { __log.warn (ioe, "failed to load manifest at %s", url); } return Optional.empty (); } private List <String> __getClasses (final Optional <Attributes> attrs, final String attrName) { return __getClassNames ( attrs.map (a -> a.getValue (attrName)) ).orElse (Collections.emptyList ()); } } private static final class DislManifest { final Optional <URL> __url; final List <String> __classes; final List <String> __transformers; DislManifest (final List <String> classes) { this (null, classes, Collections.emptyList ()); } DislManifest (final URL url, final List <String> classes, final List <String> transformers) { __url = Optional.ofNullable (url); __classes = Objects.requireNonNull (classes); __transformers = Objects.requireNonNull (transformers); } // Stream <String> classes () { return __classes.stream (); } Stream <String> transformers () { return __transformers.stream (); } boolean isEmpty () { return __classes.isEmpty () && __transformers.isEmpty (); } boolean isInstrumentation () { return !__classes.isEmpty (); } Optional <URL> resource () { return __url; } } }