text
stringlengths
7
1.01M
package arrays; import jdk.jfr.Description; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class MergeTwoSortedArrays { @Test @Description("Happy path use case") public void testHappyPath(){ Assertions.assertArrayEquals(mergeArray( new int[]{1,2,3},new int[]{4,5,6} ),new int[]{1,2,3,4,5,6}); } @Test @Description("First array in empty") public void testFirstArrayEmpty(){ Assertions.assertArrayEquals(mergeArray( new int[]{},new int[]{4,5,6} ),new int[]{4,5,6}); } @Test @Description("Second array in empty") public void testSecondArrayEmpty(){ Assertions.assertArrayEquals(mergeArray( new int[]{1,2,3},new int[]{} ),new int[]{1,2,3}); } @Test @Description("Both array are empty ") public void testBothArrayEmpty(){ Assertions.assertArrayEquals(mergeArray( new int[]{},new int[]{} ),new int[]{}); } /** * @param first first integer input array param * @param second second integer input array param * @return int[] merged array * */ int[] mergeArray(int[] first,int[] second){ int newLength = first.length + second.length ; int[] result = new int[newLength]; int p1=0,p2=0,p3=0; //merge while both are not empty while ( p1 < first.length && p2 < second.length){ if ( first[p1] < second[p2]){ result[p3] = first[p1]; p1++; p3++; } else { result[p3] = second[p2]; p2++; p3++; } } //first is completed. Copy all remaining of second to result while (p1 == first.length && p2 < second.length){ result[p3] = second[p2]; p2++; p3++; } //second is completed. Copy all remaining of first to result while (p2 == second.length && p1 < first.length){ result[p3] = first[p1]; p1++; p3++; } return result; } }
package org.lxyqaq.spring5.dao; /** * @InterfaceName UserDao * @Description TODO * @Author lxyqaq @Email A00279565@student.ait.ie * @Date 2021/1/1 22:09 * @Version 1.0 */ public interface UserDao { public void update(); }
package com.cameraforensics.elastiprom.generators; import com.cameraforensics.elastiprom.writer.PrometheusFormatWriter; import com.cameraforensics.elastiprom.writer.SingleValueWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; public class CircuitBreakerMetricsGenerator extends MetricsGenerator<Map<String, Object>> { private static final Logger log = LoggerFactory.getLogger(CircuitBreakerMetricsGenerator.class); private static final String LABEL_NAME = "circuit_name"; @Override public PrometheusFormatWriter generateMetrics(final PrometheusFormatWriter writer, final Map<String, Object> allStats) { log.debug("Generating data about circuit breaker: {}", allStats); SingleValueWriter circuitBreakerLimit = writer .addGauge("es_breaker_limit_bytes") .withHelp("Memory limit of circuit breaker in bytes"); SingleValueWriter circuitBreakerEstimated = writer .addGauge("es_breaker_estimated_bytes") .withHelp("Estimated memory of circuit breaker in bytes"); SingleValueWriter circuitBreakerTripped = writer .addCounter("es_breaker_tripped") .withHelp("Counter of how many times circuit breaker tripped"); SingleValueWriter circuitBreakerOverhead = writer.addGauge("es_breaker_overhead") .withHelp("Overhead factor for circuit breaker"); for (Map.Entry<String, Object> entry : allStats.entrySet()) { String name = entry.getKey(); Map<String, Object> cbStats = (Map<String, Object>) entry.getValue(); circuitBreakerEstimated.longValue(cbStats.get("estimated_size_in_bytes"), LABEL_NAME, name); circuitBreakerLimit.longValue(cbStats.get("limit_size_in_bytes"), LABEL_NAME, name); circuitBreakerTripped.longValue(cbStats.get("tripped"), LABEL_NAME, name); circuitBreakerOverhead.doubleValue(cbStats.get("overhead"), LABEL_NAME, name); } return writer; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.github.kare.common; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.logging.Level; import java.util.logging.Logger; /** Common IO utilities. */ public final class IO { /** Copy buffer size in bytes. */ private static final int COPY_BUFFER_SIZE = 1024 * 4; private IO() { throw new AssertionError("No IO instances for you!"); } /** * Copy bytes from input stream {@code in} to output stream {@code out}. * * @param in Input stream to read bytes from * @param out Output stream to write bytes to * @return Number of bytes copies * @throws IOException Thrown in case of I/O error * @throws NullPointerException If either given in or out is null */ public static long copy(final InputStream in, final OutputStream out) throws IOException { final byte[] buf = new byte[COPY_BUFFER_SIZE]; int n; long byteCount = 0; while ((n = in.read(buf, 0, buf.length)) != -1) { out.write(buf, 0, n); byteCount += n; } return byteCount; } /** * Close given Closeables unless they're null. * * @param closeables Closeable instances to call close() * @throws NullPointerException If given closeables array is null */ public static void close(final Closeable... closeables) { for (final Closeable closeable : closeables) { if (closeable != null) { try { closeable.close(); } catch (final IOException e) { Logger logger = Logger.getLogger(IO.class.getName()); logger.log(Level.SEVERE, "Error while closing I/O resource", e); } } } } }
/* * JBoss, Home of Professional Open Source * Copyright 2015 Red Hat Inc. and/or its affiliates and other contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.arquillian.container.test.impl.enricher.resource; import java.util.Collection; import org.jboss.arquillian.core.api.annotation.Observes; import org.jboss.arquillian.core.spi.ServiceLoader; import org.jboss.arquillian.test.spi.enricher.resource.ResourceProvider; public class RemoteResourceCommandObserver { public void lookup(@Observes RemoteResourceCommand command, ServiceLoader serviceLoader) { Collection<ResourceProvider> resourceProviders = serviceLoader.all(ResourceProvider.class); Class<?> type = command.getType(); for (ResourceProvider resourceProvider : resourceProviders) { if (resourceProvider.canProvide(type)) { Object value = resourceProvider.lookup(command.getResource(), command.getAnnotations()); if (value == null) { throw new RuntimeException( "Provider for type " + type + " returned a null value: " + resourceProvider); } command.setResult(value); return; } } throw new IllegalArgumentException("No ResourceProvider found for type: " + type); } }
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.screens.examples.model; import java.util.List; import org.jboss.errai.common.client.api.annotations.MapsTo; import org.jboss.errai.common.client.api.annotations.Portable; import org.uberfire.backend.vfs.Path; @Portable public class ExampleProject { private Path root; private String name; private String description; private List<String> tags; public ExampleProject( final @MapsTo("root") Path root, final @MapsTo("name") String name, final @MapsTo("description") String description, final @MapsTo("tags") List<String> tags ) { this.root = root; this.name = name; this.description = description; this.tags = tags; } public Path getRoot() { return root; } public String getName() { return name; } public String getDescription() { return description; } public List<String> getTags() { return tags; } @Override public boolean equals( Object o ) { if ( this == o ) { return true; } if ( !( o instanceof ExampleProject ) ) { return false; } ExampleProject that = (ExampleProject) o; if ( !root.equals( that.root ) ) { return false; } if ( !name.equals( that.name ) ) { return false; } if ( !description.equals( that.description ) ) { return false; } return !( tags != null ? !tags.equals( that.tags ) : that.tags != null ); } @Override public int hashCode() { int result = root.hashCode(); result = 31 * result + name.hashCode(); result = ~~result; result = 31 * result + ( tags != null ? tags.hashCode() : 0 ); result = ~~result; result = 31 * result + ( description != null ? description.hashCode() : 0 ); result = ~~result; return result; } }
/* * The MIT License (MIT) * * Copyright (c) 2014-2019 Yegor Bugayenko * * 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 NON-INFRINGEMENT. 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.takes.it.fm; import com.jcabi.http.request.JdkRequest; import com.jcabi.http.response.RestResponse; import com.jcabi.http.response.XmlResponse; import com.jcabi.http.wire.VerboseWire; import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.takes.http.FtRemote; /** * Test case for {@link org.takes.http.FtBasic}. * @since 0.1 */ public final class AppTest { /** * App can work. * @param temp Temporal directory * @throws Exception If some problem inside */ @Test public void justWorks(@TempDir final Path temp) throws Exception { final File dir = temp.toFile(); Files.write(new File(dir, "hello.txt").toPath(), "hello, world!".getBytes()); new FtRemote(new App(dir)).exec( new FtRemote.Script() { @Override public void exec(final URI home) throws IOException { new JdkRequest(home) .uri().path("/f").back() .through(VerboseWire.class) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .assertXPath("//xhtml:li[.='hello.txt: 13']"); } } ); } }
/** * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. * This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. */ package com.oracle.bmc.datacatalog.model; /** * Job metric summary. * <br/> * Note: Objects should always be created or deserialized using the {@link Builder}. This model distinguishes fields * that are {@code null} because they are unset from fields that are explicitly set to {@code null}. This is done in * the setter methods of the {@link Builder}, which maintain a set of all explicitly set fields called * {@link #__explicitlySet__}. The {@link #hashCode()} and {@link #equals(Object)} methods are implemented to take * {@link #__explicitlySet__} into account. The constructor, on the other hand, does not set {@link #__explicitlySet__} * (since the constructor cannot distinguish explicit {@code null} from unset {@code null}). **/ @javax.annotation.Generated(value = "OracleSDKGenerator", comments = "API Version: 20190325") @lombok.AllArgsConstructor(onConstructor = @__({@Deprecated})) @lombok.Value @com.fasterxml.jackson.databind.annotation.JsonDeserialize(builder = JobMetricSummary.Builder.class) @com.fasterxml.jackson.annotation.JsonFilter(com.oracle.bmc.http.internal.ExplicitlySetFilter.NAME) @lombok.Builder(builderClassName = "Builder", toBuilder = true) public class JobMetricSummary { @com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder(withPrefix = "") @lombok.experimental.Accessors(fluent = true) public static class Builder { @com.fasterxml.jackson.annotation.JsonProperty("key") private String key; public Builder key(String key) { this.key = key; this.__explicitlySet__.add("key"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("description") private String description; public Builder description(String description) { this.description = description; this.__explicitlySet__.add("description"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("jobExecutionKey") private String jobExecutionKey; public Builder jobExecutionKey(String jobExecutionKey) { this.jobExecutionKey = jobExecutionKey; this.__explicitlySet__.add("jobExecutionKey"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("uri") private String uri; public Builder uri(String uri) { this.uri = uri; this.__explicitlySet__.add("uri"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("timeCreated") private java.util.Date timeCreated; public Builder timeCreated(java.util.Date timeCreated) { this.timeCreated = timeCreated; this.__explicitlySet__.add("timeCreated"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("timeInserted") private java.util.Date timeInserted; public Builder timeInserted(java.util.Date timeInserted) { this.timeInserted = timeInserted; this.__explicitlySet__.add("timeInserted"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("category") private String category; public Builder category(String category) { this.category = category; this.__explicitlySet__.add("category"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("displayName") private String displayName; public Builder displayName(String displayName) { this.displayName = displayName; this.__explicitlySet__.add("displayName"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("subCategory") private String subCategory; public Builder subCategory(String subCategory) { this.subCategory = subCategory; this.__explicitlySet__.add("subCategory"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("unit") private String unit; public Builder unit(String unit) { this.unit = unit; this.__explicitlySet__.add("unit"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("value") private String value; public Builder value(String value) { this.value = value; this.__explicitlySet__.add("value"); return this; } @com.fasterxml.jackson.annotation.JsonProperty("batchKey") private String batchKey; public Builder batchKey(String batchKey) { this.batchKey = batchKey; this.__explicitlySet__.add("batchKey"); return this; } @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set<String> __explicitlySet__ = new java.util.HashSet<String>(); public JobMetricSummary build() { JobMetricSummary __instance__ = new JobMetricSummary( key, description, jobExecutionKey, uri, timeCreated, timeInserted, category, displayName, subCategory, unit, value, batchKey); __instance__.__explicitlySet__.addAll(__explicitlySet__); return __instance__; } @com.fasterxml.jackson.annotation.JsonIgnore public Builder copy(JobMetricSummary o) { Builder copiedBuilder = key(o.getKey()) .description(o.getDescription()) .jobExecutionKey(o.getJobExecutionKey()) .uri(o.getUri()) .timeCreated(o.getTimeCreated()) .timeInserted(o.getTimeInserted()) .category(o.getCategory()) .displayName(o.getDisplayName()) .subCategory(o.getSubCategory()) .unit(o.getUnit()) .value(o.getValue()) .batchKey(o.getBatchKey()); copiedBuilder.__explicitlySet__.retainAll(o.__explicitlySet__); return copiedBuilder; } } /** * Create a new builder. */ public static Builder builder() { return new Builder(); } /** * Key of the job metric that is immutable. **/ @com.fasterxml.jackson.annotation.JsonProperty("key") String key; /** * Detailed description of the metric. **/ @com.fasterxml.jackson.annotation.JsonProperty("description") String description; /** * The unique key of the parent job execution for which the job metric resource was created. **/ @com.fasterxml.jackson.annotation.JsonProperty("jobExecutionKey") String jobExecutionKey; /** * URI to the job metric instance in the API. **/ @com.fasterxml.jackson.annotation.JsonProperty("uri") String uri; /** * The date and time the job metric was created, in the format defined by [RFC3339](https://tools.ietf.org/html/rfc3339). * Example: `2019-03-25T21:10:29.600Z` * **/ @com.fasterxml.jackson.annotation.JsonProperty("timeCreated") java.util.Date timeCreated; /** * The time the metric was logged or captured in the system where the job executed. * An [RFC3339](https://tools.ietf.org/html/rfc3339) formatted datetime string. * **/ @com.fasterxml.jackson.annotation.JsonProperty("timeInserted") java.util.Date timeInserted; /** * Category of this metric. **/ @com.fasterxml.jackson.annotation.JsonProperty("category") String category; /** * A user-friendly display name. Does not have to be unique, and it's changeable. * Avoid entering confidential information. * **/ @com.fasterxml.jackson.annotation.JsonProperty("displayName") String displayName; /** * Sub category of this metric under the category. Used for aggregating values. May be null. **/ @com.fasterxml.jackson.annotation.JsonProperty("subCategory") String subCategory; /** * Unit of this metric. **/ @com.fasterxml.jackson.annotation.JsonProperty("unit") String unit; /** * Value of this metric. **/ @com.fasterxml.jackson.annotation.JsonProperty("value") String value; /** * Batch key for grouping, may be null. **/ @com.fasterxml.jackson.annotation.JsonProperty("batchKey") String batchKey; @com.fasterxml.jackson.annotation.JsonIgnore private final java.util.Set<String> __explicitlySet__ = new java.util.HashSet<String>(); }
/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package com.graly.mes.prd.workflow.jpdl.el.impl; import java.util.MissingResourceException; import java.util.ResourceBundle; /** * * <p>This contains all of the non-public constants, including * messsage strings read from the resource file. * * @author Nathan Abramson - Art Technology Group * @author Shawn Bayern * * @version $Change: 181177 $$DateTime: 2001/06/26 08:45:09 $$Author$ **/ public class Constants { //------------------------------------- // Resources static ResourceBundle sResources = ResourceBundle.getBundle ("com.graly.mes.prd.workflow.jpdl.el.impl.Resources"); //------------------------------------- // Messages from the resource bundle //------------------------------------- public static final String EXCEPTION_GETTING_BEANINFO = getStringResource ("EXCEPTION_GETTING_BEANINFO"); public static final String NULL_EXPRESSION_STRING = getStringResource ("NULL_EXPRESSION_STRING"); public static final String PARSE_EXCEPTION = getStringResource ("PARSE_EXCEPTION"); public static final String CANT_GET_PROPERTY_OF_NULL = getStringResource ("CANT_GET_PROPERTY_OF_NULL"); public static final String NO_SUCH_PROPERTY = getStringResource ("NO_SUCH_PROPERTY"); public static final String NO_GETTER_METHOD = getStringResource ("NO_GETTER_METHOD"); public static final String ERROR_GETTING_PROPERTY = getStringResource ("ERROR_GETTING_PROPERTY"); public static final String ERROR_INVOKING_METHOD = getStringResource ("ERROR_INVOKING_METHOD"); public static final String CANT_GET_INDEXED_VALUE_OF_NULL = getStringResource ("CANT_GET_INDEXED_VALUE_OF_NULL"); public static final String CANT_GET_NULL_INDEX = getStringResource ("CANT_GET_NULL_INDEX"); public static final String NULL_INDEX = getStringResource ("NULL_INDEX"); public static final String BAD_INDEX_VALUE = getStringResource ("BAD_INDEX_VALUE"); public static final String EXCEPTION_ACCESSING_LIST = getStringResource ("EXCEPTION_ACCESSING_LIST"); public static final String EXCEPTION_ACCESSING_ARRAY = getStringResource ("EXCEPTION_ACCESSING_ARRAY"); public static final String CANT_FIND_INDEX = getStringResource ("CANT_FIND_INDEX"); public static final String TOSTRING_EXCEPTION = getStringResource ("TOSTRING_EXCEPTION"); public static final String BOOLEAN_TO_NUMBER = getStringResource ("BOOLEAN_TO_NUMBER"); public static final String STRING_TO_NUMBER_EXCEPTION = getStringResource ("STRING_TO_NUMBER_EXCEPTION"); public static final String COERCE_TO_NUMBER = getStringResource ("COERCE_TO_NUMBER"); public static final String BOOLEAN_TO_CHARACTER = getStringResource ("BOOLEAN_TO_CHARACTER"); public static final String EMPTY_STRING_TO_CHARACTER = getStringResource ("EMPTY_STRING_TO_CHARACTER"); public static final String COERCE_TO_CHARACTER = getStringResource ("COERCE_TO_CHARACTER"); public static final String NULL_TO_BOOLEAN = getStringResource ("NULL_TO_BOOLEAN"); public static final String STRING_TO_BOOLEAN = getStringResource ("STRING_TO_BOOLEAN"); public static final String COERCE_TO_BOOLEAN = getStringResource ("COERCE_TO_BOOLEAN"); public static final String COERCE_TO_OBJECT = getStringResource ("COERCE_TO_OBJECT"); public static final String NO_PROPERTY_EDITOR = getStringResource ("NO_PROPERTY_EDITOR"); public static final String PROPERTY_EDITOR_ERROR = getStringResource ("PROPERTY_EDITOR_ERROR"); public static final String ARITH_OP_NULL = getStringResource ("ARITH_OP_NULL"); public static final String ARITH_OP_BAD_TYPE = getStringResource ("ARITH_OP_BAD_TYPE"); public static final String ARITH_ERROR = getStringResource ("ARITH_ERROR"); public static final String ERROR_IN_EQUALS = getStringResource ("ERROR_IN_EQUALS"); public static final String UNARY_OP_BAD_TYPE = getStringResource ("UNARY_OP_BAD_TYPE"); public static final String NAMED_VALUE_NOT_FOUND = getStringResource ("NAMED_VALUE_NOT_FOUND"); public static final String CANT_GET_INDEXED_PROPERTY = getStringResource ("CANT_GET_INDEXED_PROPERTY"); public static final String COMPARABLE_ERROR = getStringResource ("COMPARABLE_ERROR"); public static final String BAD_IMPLICIT_OBJECT = getStringResource ("BAD_IMPLICIT_OBJECT"); public static final String ATTRIBUTE_EVALUATION_EXCEPTION = getStringResource ("ATTRIBUTE_EVALUATION_EXCEPTION"); public static final String ATTRIBUTE_PARSE_EXCEPTION = getStringResource ("ATTRIBUTE_PARSE_EXCEPTION"); public static final String UNKNOWN_FUNCTION = getStringResource ("UNKNOWN_FUNCTION"); public static final String INAPPROPRIATE_FUNCTION_ARG_COUNT = getStringResource ("INAPPROPRIATE_FUNCTION_ARG_COUNT"); public static final String FUNCTION_INVOCATION_ERROR = getStringResource ("FUNCTION_INVOCATION_ERROR"); //------------------------------------- // Getting resources //------------------------------------- /** * * **/ public static String getStringResource (String pResourceName) throws MissingResourceException { try { String ret = sResources.getString (pResourceName); if (ret == null) { String str = "ERROR: Unable to load resource " + pResourceName; System.err.println (str); throw new MissingResourceException (str, "com.graly.mes.prd.workflow.jpdl.el.impl.Constants", pResourceName); } else { return ret; } } catch (MissingResourceException exc) { System.err.println ("ERROR: Unable to load resource " + pResourceName + ": " + exc); throw exc; } } //------------------------------------- }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.table.planner.plan.nodes.exec.stream; import org.apache.flink.api.common.functions.FlatMapFunction; import org.apache.flink.api.common.functions.MapFunction; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.api.dag.Transformation; import org.apache.flink.api.java.typeutils.ResultTypeQueryable; import org.apache.flink.streaming.api.operators.StreamFlatMap; import org.apache.flink.streaming.api.operators.StreamMap; import org.apache.flink.streaming.api.operators.co.KeyedCoProcessOperator; import org.apache.flink.streaming.api.transformations.OneInputTransformation; import org.apache.flink.streaming.api.transformations.TwoInputTransformation; import org.apache.flink.streaming.api.transformations.UnionTransformation; import org.apache.flink.table.api.TableException; import org.apache.flink.table.data.RowData; import org.apache.flink.table.planner.delegation.PlannerBase; import org.apache.flink.table.planner.plan.nodes.exec.ExecEdge; import org.apache.flink.table.planner.plan.nodes.exec.ExecNodeBase; import org.apache.flink.table.planner.plan.nodes.exec.InputProperty; import org.apache.flink.table.planner.plan.nodes.exec.MultipleTransformationTranslator; import org.apache.flink.table.planner.plan.nodes.exec.spec.IntervalJoinSpec; import org.apache.flink.table.planner.plan.nodes.exec.spec.JoinSpec; import org.apache.flink.table.planner.plan.utils.JoinUtil; import org.apache.flink.table.planner.plan.utils.KeySelectorUtil; import org.apache.flink.table.runtime.generated.GeneratedJoinCondition; import org.apache.flink.table.runtime.keyselector.RowDataKeySelector; import org.apache.flink.table.runtime.operators.join.KeyedCoProcessOperatorWithWatermarkDelay; import org.apache.flink.table.runtime.operators.join.OuterJoinPaddingUtil; import org.apache.flink.table.runtime.operators.join.interval.IntervalJoinFunction; import org.apache.flink.table.runtime.operators.join.interval.ProcTimeIntervalJoin; import org.apache.flink.table.runtime.operators.join.interval.RowTimeIntervalJoin; import org.apache.flink.table.runtime.typeutils.InternalTypeInfo; import org.apache.flink.table.types.logical.RowType; import org.apache.flink.util.Collector; import org.apache.flink.util.Preconditions; import org.apache.flink.shaded.guava30.com.google.common.collect.Lists; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** {@link StreamExecNode} for a time interval stream join. */ @JsonIgnoreProperties(ignoreUnknown = true) public class StreamExecIntervalJoin extends ExecNodeBase<RowData> implements StreamExecNode<RowData>, MultipleTransformationTranslator<RowData> { private static final Logger LOGGER = LoggerFactory.getLogger(StreamExecIntervalJoin.class); public static final String FIELD_NAME_INTERVAL_JOIN_SPEC = "intervalJoinSpec"; @JsonProperty(FIELD_NAME_INTERVAL_JOIN_SPEC) private final IntervalJoinSpec intervalJoinSpec; public StreamExecIntervalJoin( IntervalJoinSpec intervalJoinSpec, InputProperty leftInputProperty, InputProperty rightInputProperty, RowType outputType, String description) { this( intervalJoinSpec, getNewNodeId(), Lists.newArrayList(leftInputProperty, rightInputProperty), outputType, description); } @JsonCreator public StreamExecIntervalJoin( @JsonProperty(FIELD_NAME_INTERVAL_JOIN_SPEC) IntervalJoinSpec intervalJoinSpec, @JsonProperty(FIELD_NAME_ID) int id, @JsonProperty(FIELD_NAME_INPUT_PROPERTIES) List<InputProperty> inputProperties, @JsonProperty(FIELD_NAME_OUTPUT_TYPE) RowType outputType, @JsonProperty(FIELD_NAME_DESCRIPTION) String description) { super(id, inputProperties, outputType, description); Preconditions.checkArgument(inputProperties.size() == 2); this.intervalJoinSpec = Preconditions.checkNotNull(intervalJoinSpec); } @Override @SuppressWarnings("unchecked") protected Transformation<RowData> translateToPlanInternal(PlannerBase planner) { ExecEdge leftInputEdge = getInputEdges().get(0); ExecEdge rightInputEdge = getInputEdges().get(1); RowType leftRowType = (RowType) leftInputEdge.getOutputType(); RowType rightRowType = (RowType) rightInputEdge.getOutputType(); Transformation<RowData> leftInputTransform = (Transformation<RowData>) leftInputEdge.translateToPlan(planner); Transformation<RowData> rightInputTransform = (Transformation<RowData>) rightInputEdge.translateToPlan(planner); RowType returnType = (RowType) getOutputType(); InternalTypeInfo<RowData> returnTypeInfo = InternalTypeInfo.of(returnType); JoinSpec joinSpec = intervalJoinSpec.getJoinSpec(); IntervalJoinSpec.WindowBounds windowBounds = intervalJoinSpec.getWindowBounds(); switch (joinSpec.getJoinType()) { case INNER: case LEFT: case RIGHT: case FULL: long relativeWindowSize = windowBounds.getLeftUpperBound() - windowBounds.getLeftLowerBound(); if (relativeWindowSize < 0) { LOGGER.warn( "The relative time interval size " + relativeWindowSize + "is negative, please check the join conditions."); return createNegativeWindowSizeJoin( joinSpec, leftInputTransform, rightInputTransform, leftRowType.getFieldCount(), rightRowType.getFieldCount(), returnTypeInfo); } else { GeneratedJoinCondition joinCondition = JoinUtil.generateConditionFunction( planner.getTableConfig(), joinSpec, leftRowType, rightRowType); IntervalJoinFunction joinFunction = new IntervalJoinFunction( joinCondition, returnTypeInfo, joinSpec.getFilterNulls()); TwoInputTransformation<RowData, RowData, RowData> transform; if (windowBounds.isEventTime()) { transform = createRowTimeJoin( leftInputTransform, rightInputTransform, returnTypeInfo, joinFunction, joinSpec, windowBounds); } else { transform = createProcTimeJoin( leftInputTransform, rightInputTransform, returnTypeInfo, joinFunction, joinSpec, windowBounds); } if (inputsContainSingleton()) { transform.setParallelism(1); transform.setMaxParallelism(1); } // set KeyType and Selector for state RowDataKeySelector leftSelect = KeySelectorUtil.getRowDataSelector( joinSpec.getLeftKeys(), InternalTypeInfo.of(leftRowType)); RowDataKeySelector rightSelect = KeySelectorUtil.getRowDataSelector( joinSpec.getRightKeys(), InternalTypeInfo.of(rightRowType)); transform.setStateKeySelectors(leftSelect, rightSelect); transform.setStateKeyType(leftSelect.getProducedType()); return transform; } default: throw new TableException( "Interval Join: " + joinSpec.getJoinType() + " Join between stream " + "and stream is not supported yet.\nplease re-check " + "interval join statement according to description above."); } } private static class FilterAllFlatMapFunction implements FlatMapFunction<RowData, RowData>, ResultTypeQueryable<RowData> { private static final long serialVersionUID = 1L; private final InternalTypeInfo<RowData> outputTypeInfo; public FilterAllFlatMapFunction(InternalTypeInfo<RowData> inputTypeInfo) { this.outputTypeInfo = inputTypeInfo; } @Override public void flatMap(RowData value, Collector<RowData> out) {} @Override public TypeInformation<RowData> getProducedType() { return outputTypeInfo; } } private static class PaddingLeftMapFunction implements MapFunction<RowData, RowData>, ResultTypeQueryable<RowData> { private static final long serialVersionUID = 1L; private final OuterJoinPaddingUtil paddingUtil; private final InternalTypeInfo<RowData> outputTypeInfo; public PaddingLeftMapFunction( OuterJoinPaddingUtil paddingUtil, InternalTypeInfo<RowData> returnType) { this.paddingUtil = paddingUtil; this.outputTypeInfo = returnType; } @Override public RowData map(RowData value) { return paddingUtil.padLeft(value); } @Override public TypeInformation<RowData> getProducedType() { return outputTypeInfo; } } private static class PaddingRightMapFunction implements MapFunction<RowData, RowData>, ResultTypeQueryable<RowData> { private static final long serialVersionUID = 1L; private final OuterJoinPaddingUtil paddingUtil; private final InternalTypeInfo<RowData> outputTypeInfo; public PaddingRightMapFunction( OuterJoinPaddingUtil paddingUtil, InternalTypeInfo<RowData> returnType) { this.paddingUtil = paddingUtil; this.outputTypeInfo = returnType; } @Override public RowData map(RowData value) { return paddingUtil.padRight(value); } @Override public TypeInformation<RowData> getProducedType() { return outputTypeInfo; } } @SuppressWarnings("unchecked") private Transformation<RowData> createNegativeWindowSizeJoin( JoinSpec joinSpec, Transformation<RowData> leftInputTransform, Transformation<RowData> rightInputTransform, int leftArity, int rightArity, InternalTypeInfo<RowData> returnTypeInfo) { // We filter all records instead of adding an empty source to preserve the watermarks. FilterAllFlatMapFunction allFilter = new FilterAllFlatMapFunction(returnTypeInfo); OuterJoinPaddingUtil paddingUtil = new OuterJoinPaddingUtil(leftArity, rightArity); PaddingLeftMapFunction leftPadder = new PaddingLeftMapFunction(paddingUtil, returnTypeInfo); PaddingRightMapFunction rightPadder = new PaddingRightMapFunction(paddingUtil, returnTypeInfo); int leftParallelism = leftInputTransform.getParallelism(); int rightParallelism = rightInputTransform.getParallelism(); OneInputTransformation<RowData, RowData> filterAllLeftStream = new OneInputTransformation<>( leftInputTransform, "filter all left input transformation", new StreamFlatMap<>(allFilter), returnTypeInfo, leftParallelism); OneInputTransformation<RowData, RowData> filterAllRightStream = new OneInputTransformation<>( rightInputTransform, "filter all right input transformation", new StreamFlatMap<>(allFilter), returnTypeInfo, rightParallelism); OneInputTransformation<RowData, RowData> padLeftStream = new OneInputTransformation<>( leftInputTransform, "pad left input transformation", new StreamMap<>(leftPadder), returnTypeInfo, leftParallelism); OneInputTransformation<RowData, RowData> padRightStream = new OneInputTransformation<>( rightInputTransform, "pad right input transformation", new StreamMap<>(rightPadder), returnTypeInfo, rightParallelism); switch (joinSpec.getJoinType()) { case INNER: return new UnionTransformation<>( Lists.newArrayList(filterAllLeftStream, filterAllRightStream)); case LEFT: return new UnionTransformation<>( Lists.newArrayList(padLeftStream, filterAllRightStream)); case RIGHT: return new UnionTransformation<>( Lists.newArrayList(filterAllLeftStream, padRightStream)); case FULL: return new UnionTransformation<>(Lists.newArrayList(padLeftStream, padRightStream)); default: throw new TableException("should no reach here"); } } private TwoInputTransformation<RowData, RowData, RowData> createProcTimeJoin( Transformation<RowData> leftInputTransform, Transformation<RowData> rightInputTransform, InternalTypeInfo<RowData> returnTypeInfo, IntervalJoinFunction joinFunction, JoinSpec joinSpec, IntervalJoinSpec.WindowBounds windowBounds) { InternalTypeInfo<RowData> leftTypeInfo = (InternalTypeInfo<RowData>) leftInputTransform.getOutputType(); InternalTypeInfo<RowData> rightTypeInfo = (InternalTypeInfo<RowData>) rightInputTransform.getOutputType(); ProcTimeIntervalJoin procJoinFunc = new ProcTimeIntervalJoin( joinSpec.getJoinType(), windowBounds.getLeftLowerBound(), windowBounds.getLeftUpperBound(), leftTypeInfo, rightTypeInfo, joinFunction); return new TwoInputTransformation<>( leftInputTransform, rightInputTransform, getDescription(), new KeyedCoProcessOperator<>(procJoinFunc), returnTypeInfo, leftInputTransform.getParallelism()); } private TwoInputTransformation<RowData, RowData, RowData> createRowTimeJoin( Transformation<RowData> leftInputTransform, Transformation<RowData> rightInputTransform, InternalTypeInfo<RowData> returnTypeInfo, IntervalJoinFunction joinFunction, JoinSpec joinSpec, IntervalJoinSpec.WindowBounds windowBounds) { InternalTypeInfo<RowData> leftTypeInfo = (InternalTypeInfo<RowData>) leftInputTransform.getOutputType(); InternalTypeInfo<RowData> rightTypeInfo = (InternalTypeInfo<RowData>) rightInputTransform.getOutputType(); RowTimeIntervalJoin rowJoinFunc = new RowTimeIntervalJoin( joinSpec.getJoinType(), windowBounds.getLeftLowerBound(), windowBounds.getLeftUpperBound(), 0L, // allowedLateness leftTypeInfo, rightTypeInfo, joinFunction, windowBounds.getLeftTimeIdx(), windowBounds.getRightTimeIdx()); return new TwoInputTransformation<>( leftInputTransform, rightInputTransform, getDescription(), new KeyedCoProcessOperatorWithWatermarkDelay<>( rowJoinFunc, rowJoinFunc.getMaxOutputDelay()), returnTypeInfo, leftInputTransform.getParallelism()); } }
/* * Copyright 2004-2010 the Seasar Foundation and the 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 org.seasar.doma.jdbc.id; import junit.framework.TestCase; import org.seasar.doma.internal.jdbc.mock.MockConfig; import org.seasar.doma.internal.jdbc.mock.MockResultSet; import org.seasar.doma.internal.jdbc.mock.RowData; import org.seasar.doma.jdbc.dialect.PostgresDialect; import example.entity._Emp; /** * @author taedium * */ public class BuiltinIdentityIdGeneratorTest extends TestCase { public void test_identitySelectSql() throws Exception { MockConfig config = new MockConfig(); config.setDialect(new PostgresDialect()); MockResultSet resultSet = config.dataSource.connection.preparedStatement.resultSet; resultSet.rows.add(new RowData(11L)); BuiltinIdentityIdGenerator identityIdGenerator = new BuiltinIdentityIdGenerator(); IdGenerationConfig idGenerationConfig = new IdGenerationConfig(config, _Emp.getSingletonInternal(), "EMP", "ID"); Long value = identityIdGenerator.generatePostInsert(idGenerationConfig, config.dataSource.connection.preparedStatement); assertEquals(new Long(11), value); assertEquals("select currval('EMP_ID_seq')", config.dataSource.connection.preparedStatement.sql); } }
package com.shz.dml; import org.apache.kafka.clients.admin.*; import java.util.Set; public class TopicDML { public static void main(String[] args) throws Exception { KafkaService kafkaService = new KafkaService(); //kafkaService.deleteTopic("topic03"); TopicDescription td = kafkaService.createIfNotExist("topic03"); System.out.println(td); Set<String> topics = kafkaService.listTopics(); topics.forEach(t-> System.out.println(t)); } }
package co.simplon.heroes.model; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @Entity @NoArgsConstructor public class User implements UserDetails { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; // Le username pour l'authentification private String pseudo; // Le password pour l'authentification private String motDePasse; @ElementCollection(fetch = FetchType.EAGER) private List<String> roles = Arrays.asList("USER"); @Override public Collection<? extends GrantedAuthority> getAuthorities() { List<SimpleGrantedAuthority> authorities = new ArrayList<>(); for(String role: roles) { authorities.add(new SimpleGrantedAuthority(role)); } return authorities; } @Override public String getUsername() { return pseudo; } @Override public String getPassword() { return motDePasse; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
/* * Copyright 2015, The Querydsl Team (http://www.querydsl.com/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. */ package com.querydsl.spatial; import org.jetbrains.annotations.Nullable; import org.geolatte.geom.GeometryCollection; import com.querydsl.core.types.Expression; import com.querydsl.core.types.dsl.BooleanExpression; import com.querydsl.core.types.dsl.Expressions; import com.querydsl.core.types.dsl.NumberExpression; /** * A MultiCurve is a 1-dimensional GeometryCollection whose elements are Curves. * * @author tiwe * * @param <T> */ public abstract class MultiCurveExpression<T extends GeometryCollection> extends GeometryCollectionExpression<T> { private static final long serialVersionUID = 6983316799469849656L; @Nullable private transient volatile BooleanExpression closed; @Nullable private transient volatile NumberExpression<Double> length; public MultiCurveExpression(Expression<T> mixin) { super(mixin); } /** * Returns 1 (TRUE) if this MultiCurve is closed [StartPoint ( ) = EndPoint ( ) for each * Curve in this MultiCurve]. * * @return closed */ public BooleanExpression isClosed() { if (closed == null) { closed = Expressions.booleanOperation(SpatialOps.IS_CLOSED, mixin); } return closed; } /** * The Length of this MultiCurve which is equal to the sum of the lengths of the element * Curves. * * @return length */ public NumberExpression<Double> length() { if (length == null) { length = Expressions.numberOperation(Double.class, SpatialOps.LENGTH, mixin); } return length; } }
package com.sequenceiq.cloudbreak.repository; import java.util.Set; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import com.sequenceiq.cloudbreak.common.type.ComponentType; import com.sequenceiq.cloudbreak.domain.Component; @EntityType(entityClass = Component.class) public interface ComponentRepository extends CrudRepository<Component, Long> { @Query("SELECT cv FROM Component cv WHERE cv.stack.id = :stackId AND cv.componentType = :componentType AND cv.name = :name") Component findComponentByStackIdComponentTypeName(@Param("stackId") Long stackId, @Param("componentType") ComponentType componentType, @Param("name") String name); @Query("SELECT cv FROM Component cv WHERE cv.stack.id = :stackId") Set<Component> findComponentByStackId(@Param("stackId") Long stackId); }
package com.coding.bat.Strings; public class gHappy { // // We'll say that a lowercase 'g' in a string is "happy" if there is // another 'g' immediately to its left or right. Return true if all // the g's in the given string are happy. // // // gHappy("xxggxx") → true // gHappy("xxgxx") → false // gHappy("xxggyygxx") → false String str; public gHappy(String str) { this.str = str; } public boolean isGHappy() { // Creating array of string length char[] ch = new char[str.length()]; boolean happy = true; int len = str.length(); // Copy character by character into array for (int i = 0; i < len; i++) { ch[i] = str.charAt(i); } for (int i = 0; i < len; i++) { if (str == "g") return false; if (str.endsWith("g") && ch[len - 2] != 'g') return false; if (i > 0 && ch[i] == 'g') { if (i < len - 1) { if (ch[i - 1] == 'g' || ch[i + 1] == 'g') { happy = true; } else if (ch[len - 1] == 'g') { if (ch[i + 1] == 'g') { happy = true; } } else { happy = false; } } } } return happy; } }
package javaapplication8; class Human{ string name; int age; private int sotien; } class SV extends Human{ double GPA; } class Using{ public static void main(String[] args) { Human h; SV s; h = new Human(); h = new SV(); } } //class Demo{ // boolean x; // String s; // public Demo(int x){ // System.out.println("da goi 1 constructor kieu int"); // } // public Demo(){ // // } // public Demo(byte x){ // System.out.println("da goi kieu byte"); // } // public Demo(float x){ // System.out.println("da goi kieu float"); // } //} //class Using{ // public static void main(String[] args) { // float a = 5; // Demo d = new Demo(a); // System.out.println("gia tri mac dinh cua x = " + d.x); // System.out.println("gia tri mac dinh cua s = " + d.s); // // } //} //class Human { // // private int tien; // // public int getTien() { // return tien * 2; // } // // public int getThuc() { // return tien; // } // // public void setTien(int tien) { // this.tien = tien; // } // // public void kiemtien(int tienkiemdc) { // tien += tienkiemdc; // } // // public void tieutien(int tientieu) { // tien -= tientieu; // } // //} // //class UsingHuman { // // public static void main(String[] args) { // Human Kien = new Human(); // Kien.setTien(1000); // System.out.println("Kien co " + Kien.getTien()); // System.out.println("So tien that " + Kien.getThuc()); // Kien.kiemtien(500); // Kien.tieutien(300); // Kien.kiemtien(200); // System.out.println("Kien con " + Kien.getTien()); // System.out.println("So tien thuc la " + Kien.getThuc()); // // } //} //class sv { // // String id, name; // double gpa; // // public double takeclass(String ythuc) { // if (ythuc.equals("T")) { // return 10; // } // if (ythuc.equals("K")) { // return 7; // } // if (ythuc.equals("TB")) { // return 5; // } // if (ythuc.equals("Y")) { // return 3; // } else { // return 0; // } // // } // // public double calcgpa(String y1, int hs1, String y2, int hs2, String y3, int hs3) { // return (takeclass(y1) * hs1 + takeclass(y2) * hs2 + takeclass(y3) * hs3) / (hs1 + hs2 + hs3); // } //} // //class usingsv { // // public static void main(String[] args) { // sv sv1 = new sv(); // sv1.id = "hs140001"; // sv1.name = "Nguyen Van A"; // System.out.println("Sinh vien " + sv1.name + " hoc mon PRO192 co ket qua " + sv1.takeclass("K")); // sv1.gpa = sv1.calcgpa("T", 5, "K", 4, "TB", 10); // System.out.println("Sinh vien " + sv1.name + " co ket qua GPA la " + sv1.gpa); // } //} // ////public class JavaApplication8 { //// //// public static void main(String[] args) { //// //// } ////}
package com.learn.demomarket.product.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.math.BigDecimal; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * spu信息 * * @author 996worker * @email * @date 2021-11-29 13:08:45 */ @Data @TableName("pms_spu_info") public class SpuInfoEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 商品id */ @TableId private Long id; /** * 商品名称 */ private String spuName; /** * 商品描述 */ private String spuDescription; /** * 所属分类id */ private Long catalogId; /** * 品牌id */ private Long brandId; /** * */ private BigDecimal weight; /** * 上架状态[0 - 下架,1 - 上架] */ private Integer publishStatus; /** * */ private Date createTime; /** * */ private Date updateTime; @TableField(exist = false) private String brandName; }
/* * 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.ranger.unixusersync.config; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.ranger.credentialapi.CredentialReader; import org.apache.ranger.usergroupsync.UserGroupSink; import org.apache.ranger.usergroupsync.UserGroupSource; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.apache.log4j.Logger; public class UserGroupSyncConfig { public static final String CONFIG_FILE = "ranger-ugsync-site.xml" ; private static final Logger LOG = Logger.getLogger(UserGroupSyncConfig.class) ; public static final String DEFAULT_CONFIG_FILE = "ranger-ugsync-default-site.xml" ; public static final String UGSYNC_ENABLED_PROP = "ranger.usersync.enabled" ; public static final String UGSYNC_PM_URL_PROP = "ranger.usersync.policymanager.baseURL" ; public static final String UGSYNC_MIN_USERID_PROP = "ranger.usersync.unix.minUserId" ; public static final String UGSYNC_MAX_RECORDS_PER_API_CALL_PROP = "ranger.usersync.policymanager.maxrecordsperapicall" ; public static final String UGSYNC_MOCK_RUN_PROP = "ranger.usersync.policymanager.mockrun" ; public static final String UGSYNC_SOURCE_FILE_PROC = "ranger.usersync.filesource.file"; public static final String UGSYNC_SOURCE_FILE_DELIMITER = "ranger.usersync.filesource.text.delimiterer"; private static final String SSL_KEYSTORE_PATH_PARAM = "ranger.usersync.keystore.file" ; private static final String SSL_KEYSTORE_PATH_PASSWORD_PARAM = "ranger.usersync.keystore.password" ; private static final String SSL_TRUSTSTORE_PATH_PARAM = "ranger.usersync.truststore.file" ; private static final String SSL_TRUSTSTORE_PATH_PASSWORD_PARAM = "ranger.usersync.truststore.password" ; private static final String UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_PARAM = "ranger.usersync.sleeptimeinmillisbetweensynccycle" ; private static final long UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_MIN_VALUE = 60000L; private static final long UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_UNIX_DEFAULT_VALUE = 60000L; private static final long UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_LDAP_DEFAULT_VALUE = 3600000L; private static final String UGSYNC_SOURCE_CLASS_PARAM = "ranger.usersync.source.impl.class"; private static final String UGSYNC_SINK_CLASS_PARAM = "ranger.usersync.sink.impl.class"; private static final String UGSYNC_SOURCE_CLASS = "org.apache.ranger.unixusersync.process.UnixUserGroupBuilder"; private static final String UGSYNC_SINK_CLASS = "org.apache.ranger.unixusersync.process.PolicyMgrUserGroupBuilder"; private static final String LGSYNC_SOURCE_CLASS = "org.apache.ranger.ldapusersync.process.LdapUserGroupBuilder"; private static final String LGSYNC_LDAP_URL = "ranger.usersync.ldap.url"; private static final String LGSYNC_LDAP_BIND_DN = "ranger.usersync.ldap.binddn"; private static final String LGSYNC_LDAP_BIND_KEYSTORE = "ranger.usersync.credstore.filename"; private static final String LGSYNC_LDAP_BIND_ALIAS = "ranger.usersync.ldap.bindalias"; private static final String LGSYNC_LDAP_BIND_PASSWORD = "ranger.usersync.ldap.ldapbindpassword"; private static final String LGSYNC_LDAP_AUTHENTICATION_MECHANISM = "ranger.usersync.ldap.authentication.mechanism"; private static final String DEFAULT_AUTHENTICATION_MECHANISM = "simple"; private static final String LGSYNC_SEARCH_BASE = "ranger.usersync.ldap.searchBase"; private static final String LGSYNC_USER_SEARCH_BASE = "ranger.usersync.ldap.user.searchbase"; private static final String LGSYNC_USER_SEARCH_SCOPE = "ranger.usersync.ldap.user.searchscope"; private static final String LGSYNC_USER_OBJECT_CLASS = "ranger.usersync.ldap.user.objectclass"; private static final String DEFAULT_USER_OBJECT_CLASS = "person"; private static final String LGSYNC_USER_SEARCH_FILTER = "ranger.usersync.ldap.user.searchfilter"; private static final String LGSYNC_USER_NAME_ATTRIBUTE = "ranger.usersync.ldap.user.nameattribute"; private static final String DEFAULT_USER_NAME_ATTRIBUTE = "cn"; private static final String LGSYNC_USER_GROUP_NAME_ATTRIBUTE = "ranger.usersync.ldap.user.groupnameattribute"; private static final String DEFAULT_USER_GROUP_NAME_ATTRIBUTE = "memberof,ismemberof"; public static final String UGSYNC_NONE_CASE_CONVERSION_VALUE = "none" ; public static final String UGSYNC_LOWER_CASE_CONVERSION_VALUE = "lower" ; public static final String UGSYNC_UPPER_CASE_CONVERSION_VALUE = "upper" ; private static final String UGSYNC_USERNAME_CASE_CONVERSION_PARAM = "ranger.usersync.ldap.username.caseconversion" ; private static final String DEFAULT_UGSYNC_USERNAME_CASE_CONVERSION_VALUE = UGSYNC_LOWER_CASE_CONVERSION_VALUE ; private static final String UGSYNC_GROUPNAME_CASE_CONVERSION_PARAM = "ranger.usersync.ldap.groupname.caseconversion" ; private static final String DEFAULT_UGSYNC_GROUPNAME_CASE_CONVERSION_VALUE = UGSYNC_LOWER_CASE_CONVERSION_VALUE ; private static final String DEFAULT_USER_GROUP_TEXTFILE_DELIMITER = ","; private static final String LGSYNC_PAGED_RESULTS_ENABLED = "ranger.usersync.pagedresultsenabled"; private static final boolean DEFAULT_LGSYNC_PAGED_RESULTS_ENABLED = true; private static final String LGSYNC_PAGED_RESULTS_SIZE = "ranger.usersync.pagedresultssize"; private static final int DEFAULT_LGSYNC_PAGED_RESULTS_SIZE = 500; private static final String LGSYNC_GROUP_SEARCH_ENABLED = "ranger.usersync.group.searchenabled"; private static final boolean DEFAULT_LGSYNC_GROUP_SEARCH_ENABLED = false; private static final String LGSYNC_GROUP_USER_MAP_SYNC_ENABLED = "ranger.usersync.group.usermapsyncenabled"; private static final boolean DEFAULT_LGSYNC_GROUP_USER_MAP_SYNC_ENABLED = false; private static final String LGSYNC_GROUP_SEARCH_BASE = "ranger.usersync.group.searchbase"; private static final String LGSYNC_GROUP_SEARCH_SCOPE = "ranger.usersync.group.searchscope"; private static final String LGSYNC_GROUP_OBJECT_CLASS = "ranger.usersync.group.objectclass"; private static final String DEFAULT_LGSYNC_GROUP_OBJECT_CLASS = "groupofnames"; private static final String LGSYNC_GROUP_SEARCH_FILTER = "ranger.usersync.group.searchfilter"; private static final String LGSYNC_GROUP_NAME_ATTRIBUTE = "ranger.usersync.group.nameattribute"; private static final String DEFAULT_LGSYNC_GROUP_NAME_ATTRIBUTE = "cn"; private static final String LGSYNC_GROUP_MEMBER_ATTRIBUTE_NAME = "ranger.usersync.group.memberattributename"; private static final String DEFAULT_LGSYNC_GROUP_MEMBER_ATTRIBUTE_NAME = "member"; private static final String SYNC_POLICY_MGR_KEYSTORE = "ranger.usersync.policymgr.keystore"; private static final String SYNC_POLICY_MGR_ALIAS = "ranger.usersync.policymgr.alias"; private static final String SYNC_POLICY_MGR_PASSWORD = "ranger.usersync.policymgr.password"; private static final String SYNC_POLICY_MGR_USERNAME = "ranger.usersync.policymgr.username"; private static final String DEFAULT_POLICYMGR_USERNAME = "rangerusersync"; private static final String DEFAULT_POLICYMGR_PASSWORD = "rangerusersync"; private static final String SYNC_SOURCE = "ranger.usersync.sync.source"; private static final String LGSYNC_REFERRAL = "ranger.usersync.ldap.referral"; private static final String DEFAULT_LGSYNC_REFERRAL = "ignore"; public static final String SYNC_MAPPING_USERNAME = "ranger.usersync.mapping.username.regex"; public static final String SYNC_MAPPING_GROUPNAME = "ranger.usersync.mapping.groupname.regex"; private static final String SYNC_MAPPING_USERNAME_HANDLER = "ranger.usersync.mapping.username.handler"; private static final String DEFAULT_SYNC_MAPPING_USERNAME_HANDLER = "org.apache.ranger.usergroupsync.RegEx"; private static final String SYNC_MAPPING_GROUPNAME_HANDLER = "ranger.usersync.mapping.groupname.handler"; private static final String DEFAULT_SYNC_MAPPING_GROUPNAME_HANDLER = "org.apache.ranger.usergroupsync.RegEx"; private Properties prop = new Properties() ; private static volatile UserGroupSyncConfig me = null ; public static UserGroupSyncConfig getInstance() { UserGroupSyncConfig result = me; if (result == null) { synchronized(UserGroupSyncConfig.class) { result = me ; if (result == null) { me = result = new UserGroupSyncConfig() ; } } } return result ; } private UserGroupSyncConfig() { init() ; } private void init() { readConfigFile(CONFIG_FILE); readConfigFile(DEFAULT_CONFIG_FILE); } private void readConfigFile(String fileName) { try { InputStream in = getFileInputStream(fileName); if (in != null) { try { // prop.load(in) ; DocumentBuilderFactory xmlDocumentBuilderFactory = DocumentBuilderFactory .newInstance(); xmlDocumentBuilderFactory.setIgnoringComments(true); xmlDocumentBuilderFactory.setNamespaceAware(true); DocumentBuilder xmlDocumentBuilder = xmlDocumentBuilderFactory .newDocumentBuilder(); Document xmlDocument = xmlDocumentBuilder.parse(in); xmlDocument.getDocumentElement().normalize(); NodeList nList = xmlDocument .getElementsByTagName("property"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String propertyName = ""; String propertyValue = ""; if (eElement.getElementsByTagName("name").item( 0) != null) { propertyName = eElement .getElementsByTagName("name") .item(0).getTextContent().trim(); } if (eElement.getElementsByTagName("value") .item(0) != null) { propertyValue = eElement .getElementsByTagName("value") .item(0).getTextContent().trim(); } if (prop.get(propertyName) != null) { prop.remove(propertyName) ; } prop.put(propertyName, propertyValue); } } } finally { try { in.close() ; } catch(IOException ioe) { // Ignore IOE when closing stream } } } } catch (Throwable e) { throw new RuntimeException("Unable to load configuration file [" + CONFIG_FILE + "]", e) ; } } private InputStream getFileInputStream(String path) throws FileNotFoundException { InputStream ret = null; File f = new File(path); if (f.exists()) { ret = new FileInputStream(f); } else { ret = getClass().getResourceAsStream(path); if (ret == null) { if (! path.startsWith("/")) { ret = getClass().getResourceAsStream("/" + path); } } if (ret == null) { ret = ClassLoader.getSystemClassLoader().getResourceAsStream(path) ; if (ret == null) { if (! path.startsWith("/")) { ret = ClassLoader.getSystemResourceAsStream("/" + path); } } } } return ret; } public String getUserSyncFileSource(){ String val = prop.getProperty(UGSYNC_SOURCE_FILE_PROC) ; return val; } public String getUserSyncFileSourceDelimiter(){ String val = prop.getProperty(UGSYNC_SOURCE_FILE_DELIMITER) ; if ( val == null) { val = DEFAULT_USER_GROUP_TEXTFILE_DELIMITER; } return val; } public boolean isUserSyncEnabled() { String val = prop.getProperty(UGSYNC_ENABLED_PROP) ; return (val != null && val.trim().equalsIgnoreCase("true")) ; } public boolean isMockRunEnabled() { String val = prop.getProperty(UGSYNC_MOCK_RUN_PROP) ; return (val != null && val.trim().equalsIgnoreCase("true")) ; } public String getPolicyManagerBaseURL() { return prop.getProperty(UGSYNC_PM_URL_PROP) ; } public String getMinUserId() { return prop.getProperty(UGSYNC_MIN_USERID_PROP) ; } public String getMaxRecordsPerAPICall() { return prop.getProperty(UGSYNC_MAX_RECORDS_PER_API_CALL_PROP) ; } public String getSSLKeyStorePath() { return prop.getProperty(SSL_KEYSTORE_PATH_PARAM) ; } public String getSSLKeyStorePathPassword() { return prop.getProperty(SSL_KEYSTORE_PATH_PASSWORD_PARAM) ; } public String getSSLTrustStorePath() { return prop.getProperty(SSL_TRUSTSTORE_PATH_PARAM) ; } public String getSSLTrustStorePathPassword() { return prop.getProperty(SSL_TRUSTSTORE_PATH_PASSWORD_PARAM) ; } public long getSleepTimeInMillisBetweenCycle() throws Throwable { String val = prop.getProperty(UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_PARAM) ; if (val == null) { if (LGSYNC_SOURCE_CLASS.equals(getUserGroupSource().getClass().getName())) { return UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_LDAP_DEFAULT_VALUE ; } else { return UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_UNIX_DEFAULT_VALUE ; } } else { long ret = Long.parseLong(val) ; long min_interval; if (LGSYNC_SOURCE_CLASS.equals(getUserGroupSource().getClass().getName())) { min_interval = UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_LDAP_DEFAULT_VALUE ; }else if(UGSYNC_SOURCE_CLASS.equals(getUserGroupSource().getClass().getName())){ min_interval = UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_UNIX_DEFAULT_VALUE; } else { min_interval = UGSYNC_SLEEP_TIME_IN_MILLIS_BETWEEN_CYCLE_MIN_VALUE ; } if(ret < min_interval) { LOG.info("Sleep Time Between Cycle can not be lower than [" + min_interval + "] millisec. resetting to min value.") ; ret = min_interval; } return ret; } } public UserGroupSource getUserGroupSource() throws Throwable { String val = prop.getProperty(UGSYNC_SOURCE_CLASS_PARAM) ; String syncSource = null ; if(val == null || val.trim().isEmpty()) { syncSource=getSyncSource(); } else { syncSource = val ; } String className = val ; if(syncSource!=null && syncSource.equalsIgnoreCase("UNIX")){ className = UGSYNC_SOURCE_CLASS; }else if(syncSource!=null && syncSource.equalsIgnoreCase("LDAP")){ className = LGSYNC_SOURCE_CLASS; } Class<UserGroupSource> ugSourceClass = (Class<UserGroupSource>)Class.forName(className); UserGroupSource ret = ugSourceClass.newInstance(); return ret; } public UserGroupSink getUserGroupSink() throws Throwable { String val = prop.getProperty(UGSYNC_SINK_CLASS_PARAM) ; if(val == null || val.trim().isEmpty()) { val = UGSYNC_SINK_CLASS; } Class<UserGroupSink> ugSinkClass = (Class<UserGroupSink>)Class.forName(val); UserGroupSink ret = ugSinkClass.newInstance(); return ret; } public String getLdapUrl() throws Throwable { String val = prop.getProperty(LGSYNC_LDAP_URL); if(val == null || val.trim().isEmpty()) { throw new Exception(LGSYNC_LDAP_URL + " for LdapGroupSync is not specified"); } return val; } public String getLdapBindDn() throws Throwable { String val = prop.getProperty(LGSYNC_LDAP_BIND_DN); if(val == null || val.trim().isEmpty()) { throw new Exception(LGSYNC_LDAP_BIND_DN + " for LdapGroupSync is not specified"); } return val; } public String getLdapBindPassword() { //update credential from keystore if (prop == null) { return null; } if(prop.containsKey(LGSYNC_LDAP_BIND_KEYSTORE)){ String path=prop.getProperty(LGSYNC_LDAP_BIND_KEYSTORE); String alias=LGSYNC_LDAP_BIND_ALIAS; if(path!=null && alias!=null){ if(!path.trim().isEmpty() && !alias.trim().isEmpty()){ String password=CredentialReader.getDecryptedString(path.trim(),alias.trim()); if(password!=null&& !password.trim().isEmpty() && !password.trim().equalsIgnoreCase("none")){ prop.setProperty(LGSYNC_LDAP_BIND_PASSWORD,password); } } } } return prop.getProperty(LGSYNC_LDAP_BIND_PASSWORD); } public String getLdapAuthenticationMechanism() { String val = prop.getProperty(LGSYNC_LDAP_AUTHENTICATION_MECHANISM); if(val == null || val.trim().isEmpty()) { return DEFAULT_AUTHENTICATION_MECHANISM; } return val; } public String getUserSearchBase() throws Throwable { String val = prop.getProperty(LGSYNC_USER_SEARCH_BASE); if(val == null || val.trim().isEmpty()) { val = getSearchBase(); } if(val == null || val.trim().isEmpty()) { throw new Exception(LGSYNC_USER_SEARCH_BASE + " for LdapGroupSync is not specified"); } return val; } public int getUserSearchScope() { String val = prop.getProperty(LGSYNC_USER_SEARCH_SCOPE); if (val == null || val.trim().isEmpty()) { return 2; //subtree scope } val = val.trim().toLowerCase(); if (val.equals("0") || val.startsWith("base")) { return 0; // object scope } else if (val.equals("1") || val.startsWith("one")) { return 1; // one level scope } else { return 2; // subtree scope } } public String getUserObjectClass() { String val = prop.getProperty(LGSYNC_USER_OBJECT_CLASS); if (val == null || val.trim().isEmpty()) { return DEFAULT_USER_OBJECT_CLASS; } return val; } public String getUserSearchFilter() { return prop.getProperty(LGSYNC_USER_SEARCH_FILTER); } public String getUserNameAttribute() { String val = prop.getProperty(LGSYNC_USER_NAME_ATTRIBUTE); if(val == null || val.trim().isEmpty()) { return DEFAULT_USER_NAME_ATTRIBUTE; } return val; } public String getUserGroupNameAttribute() { String val = prop.getProperty(LGSYNC_USER_GROUP_NAME_ATTRIBUTE); if(val == null || val.trim().isEmpty()) { return DEFAULT_USER_GROUP_NAME_ATTRIBUTE; } return val; } public Set<String> getUserGroupNameAttributeSet() { String uga = getUserGroupNameAttribute(); StringTokenizer st = new StringTokenizer(uga, ","); Set<String> userGroupNameAttributeSet = new HashSet<String>(); while (st.hasMoreTokens()) { userGroupNameAttributeSet.add(st.nextToken().trim()); } return userGroupNameAttributeSet; } public String getUserNameCaseConversion() { String ret = prop.getProperty(UGSYNC_USERNAME_CASE_CONVERSION_PARAM, DEFAULT_UGSYNC_USERNAME_CASE_CONVERSION_VALUE) ; return ret.trim().toLowerCase() ; } public String getGroupNameCaseConversion() { String ret = prop.getProperty(UGSYNC_GROUPNAME_CASE_CONVERSION_PARAM, DEFAULT_UGSYNC_GROUPNAME_CASE_CONVERSION_VALUE) ; return ret.trim().toLowerCase() ; } public String getSearchBase() { return prop.getProperty(LGSYNC_SEARCH_BASE); } public boolean isPagedResultsEnabled() { boolean pagedResultsEnabled; String val = prop.getProperty(LGSYNC_PAGED_RESULTS_ENABLED); if(val == null || val.trim().isEmpty()) { pagedResultsEnabled = DEFAULT_LGSYNC_PAGED_RESULTS_ENABLED; } else { pagedResultsEnabled = Boolean.valueOf(val); } return pagedResultsEnabled; } public int getPagedResultsSize() { int pagedResultsSize = DEFAULT_LGSYNC_PAGED_RESULTS_SIZE; String val = prop.getProperty(LGSYNC_PAGED_RESULTS_SIZE); if(val == null || val.trim().isEmpty()) { pagedResultsSize = DEFAULT_LGSYNC_PAGED_RESULTS_SIZE; } else { pagedResultsSize = Integer.parseInt(val); } if (pagedResultsSize < 1) { pagedResultsSize = DEFAULT_LGSYNC_PAGED_RESULTS_SIZE; } return pagedResultsSize; } public boolean isGroupSearchEnabled() { boolean groupSearchEnabled; String val = prop.getProperty(LGSYNC_GROUP_SEARCH_ENABLED); if(val == null || val.trim().isEmpty()) { groupSearchEnabled = DEFAULT_LGSYNC_GROUP_SEARCH_ENABLED; } else { groupSearchEnabled = Boolean.valueOf(val); } return groupSearchEnabled; } public boolean isGroupUserMapSyncEnabled() { boolean groupUserMapSyncEnabled; String val = prop.getProperty(LGSYNC_GROUP_USER_MAP_SYNC_ENABLED); if(val == null || val.trim().isEmpty()) { groupUserMapSyncEnabled = DEFAULT_LGSYNC_GROUP_USER_MAP_SYNC_ENABLED; } else { groupUserMapSyncEnabled = Boolean.valueOf(val); } return groupUserMapSyncEnabled; } public String getGroupSearchBase() throws Throwable { String val = prop.getProperty(LGSYNC_GROUP_SEARCH_BASE); if(val == null || val.trim().isEmpty()) { val = getSearchBase(); } if(val == null || val.trim().isEmpty()) { val = getUserSearchBase(); } return val; } public int getGroupSearchScope() { String val = prop.getProperty(LGSYNC_GROUP_SEARCH_SCOPE); if (val == null || val.trim().isEmpty()) { return 2; //subtree scope } val = val.trim().toLowerCase(); if (val.equals("0") || val.startsWith("base")) { return 0; // object scope } else if (val.equals("1") || val.startsWith("one")) { return 1; // one level scope } else { return 2; // subtree scope } } public String getGroupObjectClass() { String val = prop.getProperty(LGSYNC_GROUP_OBJECT_CLASS); if (val == null || val.trim().isEmpty()) { return DEFAULT_LGSYNC_GROUP_OBJECT_CLASS; } return val; } public String getGroupSearchFilter() { return prop.getProperty(LGSYNC_GROUP_SEARCH_FILTER); } public String getUserGroupMemberAttributeName() { String val = prop.getProperty(LGSYNC_GROUP_MEMBER_ATTRIBUTE_NAME); if (val == null || val.trim().isEmpty()) { return DEFAULT_LGSYNC_GROUP_MEMBER_ATTRIBUTE_NAME; } return val; } public String getGroupNameAttribute() { String val = prop.getProperty(LGSYNC_GROUP_NAME_ATTRIBUTE); if (val == null || val.trim().isEmpty()) { return DEFAULT_LGSYNC_GROUP_NAME_ATTRIBUTE; } return val; } public String getProperty(String aPropertyName) { return prop.getProperty(aPropertyName) ; } public String getProperty(String aPropertyName, String aDefaultValue) { return prop.getProperty(aPropertyName, aDefaultValue) ; } public String getPolicyMgrPassword(){ //update credential from keystore String password=null; if(prop!=null && prop.containsKey(SYNC_POLICY_MGR_KEYSTORE)){ password=prop.getProperty(SYNC_POLICY_MGR_PASSWORD); if(password!=null && !password.isEmpty()){ return password; } } if(prop!=null && prop.containsKey(SYNC_POLICY_MGR_KEYSTORE) && prop.containsKey(SYNC_POLICY_MGR_ALIAS)){ String path=prop.getProperty(SYNC_POLICY_MGR_KEYSTORE); String alias=prop.getProperty(SYNC_POLICY_MGR_ALIAS,"policymgr.user.password"); if(path!=null && alias!=null){ if(!path.trim().isEmpty() && !alias.trim().isEmpty()){ try{ password=CredentialReader.getDecryptedString(path.trim(),alias.trim()); }catch(Exception ex){ password=null; } if(password!=null&& !password.trim().isEmpty() && !password.trim().equalsIgnoreCase("none")){ prop.setProperty(SYNC_POLICY_MGR_PASSWORD,password); return password; } } } } return null; } public String getPolicyMgrUserName() { String userName=null; if(prop!=null && prop.containsKey(SYNC_POLICY_MGR_USERNAME)){ userName=prop.getProperty(SYNC_POLICY_MGR_USERNAME); if(userName!=null && !userName.isEmpty()){ return userName; } } return null; } public String getDefaultPolicyMgrUserName(){ return DEFAULT_POLICYMGR_USERNAME; } public String getDefaultPolicyMgrPassword(){ return DEFAULT_POLICYMGR_PASSWORD; } public String getSyncSource() { String syncSource=null; if(prop!=null && prop.containsKey(SYNC_SOURCE)){ syncSource=prop.getProperty(SYNC_SOURCE); if(syncSource==null||syncSource.trim().isEmpty()){ syncSource=null; }else{ syncSource=syncSource.trim(); } } return syncSource; } public String getContextReferral() { String referral="ignore"; if(prop!=null && prop.containsKey(LGSYNC_REFERRAL)){ referral=prop.getProperty(LGSYNC_REFERRAL); if(referral==null||referral.trim().isEmpty()){ referral=DEFAULT_LGSYNC_REFERRAL; }else{ referral=referral.trim().toLowerCase(); } } return referral; } public List<String> getAllRegexPatterns(String baseProperty) throws Throwable { List<String> regexPatterns = new ArrayList<String>(); if (prop != null) { String baseRegex = prop.getProperty(baseProperty); if (baseRegex == null) { return regexPatterns; } regexPatterns.add(baseRegex); int i = 1; String nextRegex = prop.getProperty(baseProperty + "." + i);; while (nextRegex != null) { regexPatterns.add(nextRegex); i++; nextRegex = prop.getProperty(baseProperty + "." + i); } } return regexPatterns; } public String getUserSyncMappingUserNameHandler() { String val = prop.getProperty(SYNC_MAPPING_USERNAME_HANDLER) ; if(val == null) { val = DEFAULT_SYNC_MAPPING_USERNAME_HANDLER; } return val; } public String getUserSyncMappingGroupNameHandler() { String val = prop.getProperty(SYNC_MAPPING_GROUPNAME_HANDLER) ; if(val == null) { val = DEFAULT_SYNC_MAPPING_GROUPNAME_HANDLER; } return val; } }
package com.mycompany.myapp.web.rest; import com.mycompany.myapp.domain.Region; import com.mycompany.myapp.service.RegionService; import com.mycompany.myapp.web.rest.errors.BadRequestAlertException; import io.github.jhipster.web.util.HeaderUtil; import io.github.jhipster.web.util.ResponseUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Optional; import java.util.stream.StreamSupport; import static org.elasticsearch.index.query.QueryBuilders.*; /** * REST controller for managing {@link com.mycompany.myapp.domain.Region}. */ @RestController @RequestMapping("/api") public class RegionResource { private final Logger log = LoggerFactory.getLogger(RegionResource.class); private static final String ENTITY_NAME = "region"; @Value("${jhipster.clientApp.name}") private String applicationName; private final RegionService regionService; public RegionResource(RegionService regionService) { this.regionService = regionService; } /** * {@code POST /regions} : Create a new region. * * @param region the region to create. * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new region, or with status {@code 400 (Bad Request)} if the region has already an ID. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PostMapping("/regions") public ResponseEntity<Region> createRegion(@RequestBody Region region) throws URISyntaxException { log.debug("REST request to save Region : {}", region); if (region.getId() != null) { throw new BadRequestAlertException("A new region cannot already have an ID", ENTITY_NAME, "idexists"); } Region result = regionService.save(region); return ResponseEntity.created(new URI("/api/regions/" + result.getId())) .headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString())) .body(result); } /** * {@code PUT /regions} : Updates an existing region. * * @param region the region to update. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated region, * or with status {@code 400 (Bad Request)} if the region is not valid, * or with status {@code 500 (Internal Server Error)} if the region couldn't be updated. * @throws URISyntaxException if the Location URI syntax is incorrect. */ @PutMapping("/regions") public ResponseEntity<Region> updateRegion(@RequestBody Region region) throws URISyntaxException { log.debug("REST request to update Region : {}", region); if (region.getId() == null) { throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull"); } Region result = regionService.save(region); return ResponseEntity.ok() .headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, region.getId().toString())) .body(result); } /** * {@code GET /regions} : get all the regions. * * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of regions in body. */ @GetMapping("/regions") public List<Region> getAllRegions() { log.debug("REST request to get all Regions"); return regionService.findAll(); } /** * {@code GET /regions/:id} : get the "id" region. * * @param id the id of the region to retrieve. * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the region, or with status {@code 404 (Not Found)}. */ @GetMapping("/regions/{id}") public ResponseEntity<Region> getRegion(@PathVariable Long id) { log.debug("REST request to get Region : {}", id); Optional<Region> region = regionService.findOne(id); return ResponseUtil.wrapOrNotFound(region); } /** * {@code DELETE /regions/:id} : delete the "id" region. * * @param id the id of the region to delete. * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}. */ @DeleteMapping("/regions/{id}") public ResponseEntity<Void> deleteRegion(@PathVariable Long id) { log.debug("REST request to delete Region : {}", id); regionService.delete(id); return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build(); } /** * {@code SEARCH /_search/regions?query=:query} : search for the region corresponding * to the query. * * @param query the query of the region search. * @return the result of the search. */ @GetMapping("/_search/regions") public List<Region> searchRegions(@RequestParam String query) { log.debug("REST request to search Regions for query {}", query); return regionService.search(query); } }
package com.sequenceiq.cloudbreak.workspace.authorization; import java.util.Set; import java.util.stream.Collectors; import javax.inject.Inject; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import com.sequenceiq.authorization.service.UmsAuthorizationService; import com.sequenceiq.cloudbreak.auth.altus.Crn; import com.sequenceiq.cloudbreak.auth.altus.GrpcUmsClient; import com.sequenceiq.cloudbreak.workspace.authorization.api.WorkspaceRole; import com.sequenceiq.cloudbreak.workspace.model.User; @Service public class UmsWorkspaceAuthorizationService extends UmsAuthorizationService { private static final Logger LOGGER = LoggerFactory.getLogger(UmsWorkspaceAuthorizationService.class); @Inject private GrpcUmsClient umsClient; public void assignResourceRoleToUserInWorkspace(User user, String workspaceCrn, WorkspaceRole role) { umsClient.assignResourceRole(user.getUserCrn(), workspaceCrn, role.getCrn(user.getUserCrn()), getRequestId()); } public void unassignResourceRoleFromUserInWorkspace(User user, String workspaceCrn, WorkspaceRole role) { umsClient.unassignResourceRole(user.getUserCrn(), workspaceCrn, role.getCrn(user.getUserCrn()), getRequestId()); } public Set<WorkspaceRole> getUserRolesInWorkspace(User user, String workspaceCrn) { return umsClient.listResourceRoleAssigments(user.getUserCrn(), user.getUserCrn(), getRequestId()).stream() .filter(resourceAssignment -> StringUtils.equals(workspaceCrn, resourceAssignment.getResourceCrn())) .map(resourceAssignment -> WorkspaceRole.getByUmsName(Crn.fromString(resourceAssignment.getResourceRoleCrn()).getResource())) .collect(Collectors.toSet()); } public void removeResourceRolesOfUserInWorkspace(Set<User> users, String workspaceCrn) { users.stream().forEach(user -> getUserRolesInWorkspace(user, workspaceCrn).stream() .forEach(role -> unassignResourceRoleFromUserInWorkspace(user, workspaceCrn, role))); } public void notifyAltusAboutResourceDeletion(User currentUser, String workspaceCrn) { umsClient.notifyResourceDeleted(currentUser.getUserCrn(), workspaceCrn, getRequestId()); } public Set<String> getUserIdsOfWorkspace(User currentUser, String workspaceCrn) { Set<String> userIds = umsClient.listAssigneesOfResource(currentUser.getUserCrn(), currentUser.getUserCrn(), workspaceCrn, getRequestId()) .stream() .map(resourceAssignee -> Crn.fromString(resourceAssignee.getAssigneeCrn()).getResource()) .collect(Collectors.toSet()); return userIds; } }
package br.com.podrao.auth.core.ports.incoming; import br.com.podrao.auth.core.models.commands.CadastrarFuncaoCommand; public interface CadastrarFuncao { void executar(CadastrarFuncaoCommand command); }
/** * This class is a simple example for how to use the sorting classes. * It sorts three numbers, and measures how long it takes. */ public class SortTestExample { public static void main(String[] args){ // Create three key value pairs KeyValuePair[] testArray = new KeyValuePair[3]; testArray[0] = new KeyValuePair(10, 20); testArray[1] = new KeyValuePair(5, 20); testArray[2] = new KeyValuePair(8, 20); // Create a stopwatch StopWatch watch = new StopWatch(); ISort sortingObject = new SorterA(); // Do the sorting watch.start(); sortingObject.sort(testArray); watch.stop(); System.out.println(testArray[0]); System.out.println(testArray[1]); System.out.println(testArray[2]); System.out.println("Time: " + watch.getTime()); } }
package com.unisinos.m2.mateusmanica.calculadoradecombustivel; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class CalcCostOfPath extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calc_cost_of_path); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.askCalcPricePathBt: calculate(); return; case R.id.newCalcCostBt: clearFields(); return; case R.id.backCalcCostBt: finish(); } } private void calculate() { //Get the value for consumption, price of fuel and distance to be run String distance = ((EditText)findViewById(R.id.disRunNum)).getText().toString(); String priceLiter = ((EditText)findViewById(R.id.literPriceNum)).getText().toString(); String consumV = ((EditText)findViewById(R.id.consumVNum)).getText().toString(); //Check if the fields are filled if (consumV.equals("") || priceLiter.equals("") || distance.equals("")){ launchToast("Preencha: distancia a percorrer, consumo do veículo e preço do combustível"); return; } Double consumVNum = Double.valueOf(consumV); Double priceNum = Double.valueOf(priceLiter); Double distanceNum = Double.valueOf(distance); double finalPrice = distanceNum / consumVNum * priceNum; ((TextView)findViewById(R.id.ansPathPriceTxt)).setText("R$" + finalPrice); } private void clearFields() { ((EditText)findViewById(R.id.disRunNum)).setText(""); ((EditText)findViewById(R.id.literPriceNum)).setText(""); ((EditText)findViewById(R.id.consumVNum)).setText(""); } private void launchToast(String message){ Context context = getApplicationContext(); CharSequence text = message; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } }
package io.renren.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * * * @author Mark * @email sunlightcs@gmail.com * @date 2019-11-16 14:45:19 */ @Data @TableName("sys_app_template") public class SysAppTemplateEntity implements Serializable { private static final long serialVersionUID = 1L; /** * */ @TableId private Long id; /** * app模板id */ private String templateId; /** * 0打开 1关闭 */ private Integer isOpen; /** * 创建时间 */ private Date createTime; }
/******************************************************************************* * * Pentaho Data Integration * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * * This file is dual-licensed under the Apache Software License V2 and is * also available under the terms of the GNU Lesser GPL version 2.1 as provided * for by the author of the algorithm below (Dr. Graham King). * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ /****************************************************************************** * Copyright (c) 2006 Graham King and 2007 Hitachi Vantara. All rights reserved. * This software was developed by Hitachi Vantara and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is samatar Hassan. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations. ******************************************************************************/ package org.pentaho.di.trans.steps.randomccnumber; import java.util.List; import java.util.Stack; import java.util.Vector; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.i18n.BaseMessages; public class RandomCreditCardNumberGenerator { /* * 2006 Graham King graham@darkcoding.net * * 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 2 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, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * www.darkcoding.net * * From : Graham King <graham (at) gkgk dot org> To : samatar hassan <sahass78 (at) yahoo dot fr> Envoye le : Mer 8 * decembre 2010, 22h 30min 55s Objet : Re: CreditCardNumberGenerator LGPL grant - Hitachi Vantara data Integration Hi * Samatar, Thanks for getting in touch. Yes, I am happy to grant Pentaho Data Integration an LGPL exception, meaning * that solely for inclusion in Pentaho Data Integration, the credit card code hosted at darkcoding.net can be * considered LGPL licensed. All the best, Graham */ private static Class<?> PKG = RandomCCNumberGeneratorMeta.class; // for i18n purposes, needed by Translator2!! public static final int CARD_TYPE_AMEX = 0; public static final int CARD_TYPE_DINERS = 1; public static final int CARD_TYPE_DISCOVER = 2; public static final int CARD_TYPE_ENROUTE = 3; public static final int CARD_TYPE_JCB_15 = 4; public static final int CARD_TYPE_JCB_16 = 5; public static final int CARD_TYPE_MASTERCARD = 6; public static final int CARD_TYPE_VISA = 7; public static final int CARD_TYPE_VOYAGER = 8; public static final int CARD_TYPE_AIRPLUS = 9; public static final int CARD_TYPE_BANKCARD = 10; public static final int CARD_TYPE_MAESTRO = 11; public static final int CARD_TYPE_SOLO = 12; public static final int CARD_TYPE_SWITCH = 13; public static final int CARD_TYPE_LASER = 14; public static final String[] cardTypes = { "American Express", "Diners", "Discover", "En Route", "JCB1", "JCB2", "MasterCard", "Visa", "Voyager", "Airplus", "BankCard", "Maestro", "Solo", "Switch", "Laser" }; private static final String[] VISA_PREFIX_LIST = new String[] { "4539", "4556", "4916", "4532", "4929", "40240071", "4485", "4716", "4" }; private static final String[] MASTERCARD_PREFIX_LIST = new String[] { "51", "52", "53", "54", "55" }; private static final String[] AMEX_PREFIX_LIST = new String[] { "34", "37" }; private static final String[] DISCOVER_PREFIX_LIST = new String[] { "6011" }; private static final String[] DINERS_PREFIX_LIST = new String[] { "300", "301", "302", "303", "36", "38" }; private static final String[] ENROUTE_PREFIX_LIST = new String[] { "2014", "2149" }; private static final String[] JCB_15_PREFIX_LIST = new String[] { "2100", "1800" }; private static final String[] JCB_16_PREFIX_LIST = new String[] { "3088", "3096", "3112", "3158", "3337", "3528" }; private static final String[] VOYAGER_PREFIX_LIST = new String[] { "8699" }; private static final String[] AIRPLUS_PREFIX_LIST = new String[] { "192", "122" }; private static final String[] BANKCARD_PREFIX_LIST = new String[] { "56" }; private static final String[] MAESTRO_PREFIX_LIST = new String[] { "5020", "6" }; private static final String[] SOLO_PREFIX_LIST = new String[] { "6334", "6767" }; private static final String[] SWITCH_PREFIX_LIST = new String[] { "4903", "4905", "4911", "4936", "564182", "633110", "6333", "6759" }; private static final String[] LASER_PREFIX_LIST = new String[] { "6304", "6706", "6771", "6709" }; private static final int[] VISA_LENGTH_LIST = new int[] { 13, 16 }; private static final int[] MASTERCARD_LENGTH_LIST = new int[] { 16 }; private static final int[] AMEX_LENGTH_LIST = new int[] { 15 }; private static final int[] DISCOVER_LENGTH_LIST = new int[] { 16 }; private static final int[] DINERS_LENGTH_LIST = new int[] { 14 }; private static final int[] ENROUTE_LENGTH_LIST = new int[] { 15 }; private static final int[] JCB_15_LENGTH_LIST = new int[] { 15 }; private static final int[] JCB_16_LENGTH_LIST = new int[] { 16 }; private static final int[] VOYAGER_LENGTH_LIST = new int[] { 15 }; private static final int[] AIRPLUS_LENGTH_LIST = new int[] {}; private static final int[] BANKCARD_LENGTH_LIST = new int[] { 16 }; private static final int[] MAESTRO_LENGTH_LIST = new int[] { 16 }; private static final int[] SOLO_LENGTH_LIST = new int[] { 16, 18, 19 }; private static final int[] SWITCH_LENGTH_LIST = new int[] { 16, 18, 19 }; private static final int[] LASER_LENGTH_LIST = new int[] { 16, 17, 18, 19 }; public static int getCardType( String typeName ) { if ( typeName == null ) { return 0; } for ( int i = 0; i < cardTypes.length; i++ ) { if ( cardTypes[i].equalsIgnoreCase( typeName ) ) { return i; } } return 0; } public static String getCardName( int id ) { return ( id > -1 && id < cardTypes.length ? cardTypes[id] : null ); } private static String strrev( String str ) { if ( str == null ) { return ""; } String revstr = ""; for ( int i = str.length() - 1; i >= 0; i-- ) { revstr += str.charAt( i ); } return revstr; } /* * 'prefix' is the start of the CC number as a string, any number of digits. 'length' is the length of the CC number * to generate. Typically 13 or 16 */ private static String completed_number( String prefix, int length ) { String ccnumber = prefix; // generate digits while ( ccnumber.length() < ( length - 1 ) ) { ccnumber += new Double( Math.floor( Math.random() * 10 ) ).intValue(); } // reverse number and convert to int String reversedCCnumberString = strrev( ccnumber ); List<Integer> reversedCCnumberList = new Vector<Integer>(); for ( int i = 0; i < reversedCCnumberString.length(); i++ ) { reversedCCnumberList.add( new Integer( String.valueOf( reversedCCnumberString.charAt( i ) ) ) ); } // calculate sum int sum = 0; int pos = 0; Integer[] reversedCCnumber = reversedCCnumberList.toArray( new Integer[reversedCCnumberList.size()] ); while ( pos < length - 1 ) { int odd = reversedCCnumber[pos] * 2; if ( odd > 9 ) { odd -= 9; } sum += odd; if ( pos != ( length - 2 ) ) { sum += reversedCCnumber[pos + 1]; } pos += 2; } // calculate check digit int checkdigit = new Double( ( ( Math.floor( sum / 10 ) + 1 ) * 10 - sum ) % 10 ).intValue(); ccnumber += checkdigit; return ccnumber; } private static String[] credit_card_number( String[] prefixList, int length, int howMany ) { Stack<String> result = new Stack<String>(); for ( int i = 0; i < howMany; i++ ) { int randomArrayIndex = (int) Math.floor( Math.random() * prefixList.length ); String ccnumber = prefixList[randomArrayIndex]; result.push( completed_number( ccnumber, length ) ); } return result.toArray( new String[result.size()] ); } private static void checkLength( int cardType, int size, int[] lengths ) throws KettleException { if ( lengths.length == 0 ) { return; } for ( int i = 0; i < lengths.length; i++ ) { if ( size == lengths[i] ) { // The size is supported for the card type return; } } throw new KettleException( BaseMessages .getString( PKG, "RandomCreditCardNumbberGenerator.UnSupportedLength", String.valueOf( size ), getCardName( cardType ) ) ); } public static String[] GenerateCreditCardNumbers( int cardType, int size, int howMany ) throws KettleException { String[] cards = null; switch ( cardType ) { case CARD_TYPE_MASTERCARD: checkLength( cardType, size, MASTERCARD_LENGTH_LIST ); cards = credit_card_number( MASTERCARD_PREFIX_LIST, size, howMany ); break; case CARD_TYPE_AMEX: checkLength( cardType, size, AMEX_LENGTH_LIST ); cards = credit_card_number( AMEX_PREFIX_LIST, size, howMany ); break; case CARD_TYPE_DINERS: checkLength( cardType, size, DINERS_LENGTH_LIST ); cards = credit_card_number( DINERS_PREFIX_LIST, size, howMany ); break; case CARD_TYPE_DISCOVER: checkLength( cardType, size, DISCOVER_LENGTH_LIST ); cards = credit_card_number( DISCOVER_PREFIX_LIST, size, howMany ); break; case CARD_TYPE_ENROUTE: checkLength( cardType, size, ENROUTE_LENGTH_LIST ); cards = credit_card_number( ENROUTE_PREFIX_LIST, size, howMany ); break; case CARD_TYPE_JCB_15: checkLength( cardType, size, JCB_15_LENGTH_LIST ); cards = credit_card_number( JCB_15_PREFIX_LIST, size, howMany ); break; case CARD_TYPE_JCB_16: checkLength( cardType, size, JCB_16_LENGTH_LIST ); cards = credit_card_number( JCB_16_PREFIX_LIST, size, howMany ); break; case CARD_TYPE_VISA: checkLength( cardType, size, VISA_LENGTH_LIST ); cards = credit_card_number( VISA_PREFIX_LIST, size, howMany ); break; case CARD_TYPE_VOYAGER: checkLength( cardType, size, VOYAGER_LENGTH_LIST ); cards = credit_card_number( VOYAGER_PREFIX_LIST, size, howMany ); break; case CARD_TYPE_AIRPLUS: checkLength( cardType, size, AIRPLUS_LENGTH_LIST ); cards = credit_card_number( AIRPLUS_PREFIX_LIST, size, howMany ); break; case CARD_TYPE_BANKCARD: checkLength( cardType, size, BANKCARD_LENGTH_LIST ); cards = credit_card_number( BANKCARD_PREFIX_LIST, size, howMany ); break; case CARD_TYPE_MAESTRO: checkLength( cardType, size, MAESTRO_LENGTH_LIST ); cards = credit_card_number( MAESTRO_PREFIX_LIST, size, howMany ); break; case CARD_TYPE_SOLO: checkLength( cardType, size, SOLO_LENGTH_LIST ); cards = credit_card_number( SOLO_PREFIX_LIST, size, howMany ); break; case CARD_TYPE_SWITCH: checkLength( cardType, size, SWITCH_LENGTH_LIST ); cards = credit_card_number( SWITCH_PREFIX_LIST, size, howMany ); break; case CARD_TYPE_LASER: checkLength( cardType, size, LASER_LENGTH_LIST ); cards = credit_card_number( LASER_PREFIX_LIST, size, howMany ); break; default: throw new KettleException( BaseMessages.getString( PKG, "RandomCreditCardNumbberGenerator.UnknownCardtype", String.valueOf( cardType ) ) ); } return cards; } }
/* * 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.settings.dashboard.conditional; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.provider.Settings; import android.util.Log; import com.android.internal.logging.nano.MetricsProto.MetricsEvent; import com.android.settings.R; import com.android.settingslib.WirelessUtils; public class AirplaneModeCondition extends Condition { public static String TAG = "APM_Condition"; private final Receiver mReceiver; private static final IntentFilter AIRPLANE_MODE_FILTER = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED); public AirplaneModeCondition(ConditionManager conditionManager) { super(conditionManager); mReceiver = new Receiver(); } @Override public void refreshState() { Log.d(TAG, "APM condition refreshed"); setActive(WirelessUtils.isAirplaneModeOn(mManager.getContext())); } @Override protected BroadcastReceiver getReceiver() { return mReceiver; } @Override protected IntentFilter getIntentFilter() { return AIRPLANE_MODE_FILTER; } @Override public Drawable getIcon() { return mManager.getContext().getDrawable(R.drawable.ic_airplane); } @Override protected void setActive(boolean active) { super.setActive(active); Log.d(TAG, "setActive was called with " + active); } @Override public CharSequence getTitle() { return mManager.getContext().getString(R.string.condition_airplane_title); } @Override public CharSequence getSummary() { return mManager.getContext().getString(R.string.condition_airplane_summary); } @Override public CharSequence[] getActions() { return new CharSequence[] {mManager.getContext().getString(R.string.condition_turn_off)}; } @Override public void onPrimaryClick() { mManager.getContext().startActivity( new Intent(Settings.ACTION_WIRELESS_SETTINGS) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); } @Override public void onActionClick(int index) { if (index == 0) { ConnectivityManager.from(mManager.getContext()).setAirplaneMode(false); setActive(false); } else { throw new IllegalArgumentException("Unexpected index " + index); } } @Override public int getMetricsConstant() { return MetricsEvent.SETTINGS_CONDITION_AIRPLANE_MODE; } public static class Receiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(intent.getAction())) { ConditionManager.get(context).getCondition(AirplaneModeCondition.class) .refreshState(); } } } }
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package DECL|package|org.apache.camel.component.as2.api.protocol package|package name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|as2 operator|. name|api operator|. name|protocol package|; end_package begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|as2 operator|. name|api operator|. name|AS2ClientManager import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|as2 operator|. name|api operator|. name|AS2Constants import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|as2 operator|. name|api operator|. name|AS2Header import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|as2 operator|. name|api operator|. name|InvalidAS2NameException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|as2 operator|. name|api operator|. name|util operator|. name|AS2Utils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|http operator|. name|HttpException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|http operator|. name|HttpRequest import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|http operator|. name|HttpRequestInterceptor import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|http operator|. name|protocol operator|. name|HttpContext import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|http operator|. name|protocol operator|. name|HttpCoreContext import|; end_import begin_class DECL|class|RequestAS2 specifier|public class|class name|RequestAS2 implements|implements name|HttpRequestInterceptor block|{ DECL|field|as2Version specifier|private specifier|final name|String name|as2Version decl_stmt|; DECL|field|clientFQDN specifier|private specifier|final name|String name|clientFQDN decl_stmt|; DECL|method|RequestAS2 (String as2Version, String clientFQDN) specifier|public name|RequestAS2 parameter_list|( name|String name|as2Version parameter_list|, name|String name|clientFQDN parameter_list|) block|{ name|this operator|. name|as2Version operator|= name|as2Version expr_stmt|; name|this operator|. name|clientFQDN operator|= name|clientFQDN expr_stmt|; block|} annotation|@ name|Override DECL|method|process (HttpRequest request, HttpContext context) specifier|public name|void name|process parameter_list|( name|HttpRequest name|request parameter_list|, name|HttpContext name|context parameter_list|) throws|throws name|HttpException throws|, name|IOException block|{ name|HttpCoreContext name|coreContext init|= name|HttpCoreContext operator|. name|adapt argument_list|( name|context argument_list|) decl_stmt|; comment|/* MIME header */ name|request operator|. name|addHeader argument_list|( name|AS2Header operator|. name|MIME_VERSION argument_list|, name|AS2Constants operator|. name|MIME_VERSION argument_list|) expr_stmt|; comment|/* Subject header */ name|String name|subject init|= name|coreContext operator|. name|getAttribute argument_list|( name|AS2ClientManager operator|. name|SUBJECT argument_list|, name|String operator|. name|class argument_list|) decl_stmt|; name|request operator|. name|addHeader argument_list|( name|AS2Header operator|. name|SUBJECT argument_list|, name|subject argument_list|) expr_stmt|; comment|/* From header */ name|String name|from init|= name|coreContext operator|. name|getAttribute argument_list|( name|AS2ClientManager operator|. name|FROM argument_list|, name|String operator|. name|class argument_list|) decl_stmt|; name|request operator|. name|addHeader argument_list|( name|AS2Header operator|. name|FROM argument_list|, name|from argument_list|) expr_stmt|; comment|/* AS2-Version header */ name|request operator|. name|addHeader argument_list|( name|AS2Header operator|. name|AS2_VERSION argument_list|, name|as2Version argument_list|) expr_stmt|; comment|/* AS2-From header */ name|String name|as2From init|= name|coreContext operator|. name|getAttribute argument_list|( name|AS2ClientManager operator|. name|AS2_FROM argument_list|, name|String operator|. name|class argument_list|) decl_stmt|; try|try block|{ name|AS2Utils operator|. name|validateAS2Name argument_list|( name|as2From argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|InvalidAS2NameException name|e parameter_list|) block|{ throw|throw operator|new name|HttpException argument_list|( literal|"Invalid AS-From name" argument_list|, name|e argument_list|) throw|; block|} name|request operator|. name|addHeader argument_list|( name|AS2Header operator|. name|AS2_FROM argument_list|, name|as2From argument_list|) expr_stmt|; comment|/* AS2-To header */ name|String name|as2To init|= name|coreContext operator|. name|getAttribute argument_list|( name|AS2ClientManager operator|. name|AS2_TO argument_list|, name|String operator|. name|class argument_list|) decl_stmt|; try|try block|{ name|AS2Utils operator|. name|validateAS2Name argument_list|( name|as2To argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|InvalidAS2NameException name|e parameter_list|) block|{ throw|throw operator|new name|HttpException argument_list|( literal|"Invalid AS-To name" argument_list|, name|e argument_list|) throw|; block|} name|request operator|. name|addHeader argument_list|( name|AS2Header operator|. name|AS2_TO argument_list|, name|as2To argument_list|) expr_stmt|; comment|/* Message-Id header*/ comment|// SHOULD be set to aid in message reconciliation name|request operator|. name|addHeader argument_list|( name|AS2Header operator|. name|MESSAGE_ID argument_list|, name|AS2Utils operator|. name|createMessageId argument_list|( name|clientFQDN argument_list|) argument_list|) expr_stmt|; block|} block|} end_class end_unit
package oneapp.onechat.chat.network; /** * Created by 何帅 on 2016/7/2. */ import android.os.Handler; import android.os.Looper; import android.widget.ImageView; import com.google.gson.Gson; import com.google.gson.internal.$Gson$Types; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.FileNameMap; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import okhttp3.Cache; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Cookie; import okhttp3.CookieJar; import okhttp3.FormBody; import okhttp3.Headers; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okio.BufferedSink; import okio.GzipSink; import okio.Okio; import oneapp.onechat.oneandroid.chatsdk.OneAccountHelper; import oneapp.onechat.oneandroid.chatsdk.OneOpenHelper; import oneapp.onechat.oneandroid.graphenechain.interfaces.ProgressRequestListener; import oneapp.onechat.oneandroid.onemessage.beanchat.util.NetUtils; import oneapp.onechat.oneandroid.onewallet.modle.Result; import oneapp.onechat.oneandroid.onewallet.modle.ServiceUrlBean; import oneapp.onechat.oneandroid.onewallet.network.ServiceConstants; import oneapp.onechat.oneandroid.onewallet.util.BaseUtils; import oneapp.onechat.oneandroid.onewallet.util.LogUtils; import oneapp.onechat.oneandroid.onewallet.util.StringUtils; /** * Created by zhy on 15/8/17. */ public class OkHttpClientManager { private static OkHttpClientManager mInstance; private OkHttpClient mOkHttpClient; private Handler mDelivery; private Gson mGson; private static final OkHttpClient.Builder builder = new OkHttpClient.Builder(); private static final String TAG = "OkHttpClientManager"; private OkHttpClientManager() { //cookie enabled builder.connectTimeout(ServiceConstants.HTTP_TIMEOUT_SECONDS, TimeUnit.SECONDS).cookieJar(new CookieJar() { private final HashMap<HttpUrl, List<Cookie>> cookieStore = new HashMap<>(); @Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) { cookieStore.put(url, cookies); } @Override public List<Cookie> loadForRequest(HttpUrl url) { List<Cookie> cookies = cookieStore.get(url); return cookies != null ? cookies : new ArrayList<Cookie>(); } }).cache(new Cache(new File(OneAccountHelper.getContext().getCacheDir(), "http_cache"), 1024 * 1024 * 100)); // builder.addInterceptor(new GzipRequestInterceptor());//gzip mOkHttpClient = builder.build(); mDelivery = new Handler(Looper.getMainLooper()); mGson = new Gson(); } public static OkHttpClientManager getInstance() { if (mInstance == null) { synchronized (OkHttpClientManager.class) { if (mInstance == null) { mInstance = new OkHttpClientManager(); } } } return mInstance; } /** * 异步的post请求 * * @param url * @param callback * @param params */ private void _postAsyn(ServiceUrlBean url, final ResultCallback callback, Param[] params, boolean ifCheckCode, boolean ifMainTask) { Request request = buildPostRequest(url.getHost_url(), params); deliveryResult(url.getService_key(), callback, request, ifCheckCode, ifMainTask); } /** * 异步的post请求 * * @param url * @param callback * @param params */ private void _postAsyn(ServiceUrlBean url, final ResultCallback callback, Param[] params, boolean ifCheckCode) { Request request = buildPostRequest(url.getHost_url(), params); deliveryResult(url.getService_key(), callback, request, ifCheckCode, true); } /** * 异步的post请求 * * @param url * @param callback * @param params */ private void _postAsyn(ServiceUrlBean url, final ResultCallback callback, Param[] params) { Request request = buildPostRequest(url.getHost_url(), params); deliveryResult(url.getService_key(), callback, request); } /** * 异步的get请求 * * @param url * @param callback */ private void _getAsyn(ServiceUrlBean url, final ResultCallback callback, HashMap<String, String> params, boolean ifAddPublicParam, boolean ifMainTask) { Request request = buildGetRequest(url.getHost_url(), params, ifAddPublicParam); deliveryResult(url.getService_key(), callback, request, true, ifMainTask); } /** * 异步的post请求 * * @param url * @param callback * @param params */ private void _postAsyn(ServiceUrlBean url, final ResultCallback callback, Map<String, String> params) { Param[] paramsArr = map2Params(params); Request request = buildPostRequest(url.getHost_url(), paramsArr); deliveryResult(url.getService_key(), callback, request); } /** * 同步基于post的文件上传 * * @param params * @return */ private Response _post(String url, File[] files, String[] fileKeys, Param[] params) throws IOException { Request request = buildMultipartFormRequest(url, files, fileKeys, null, params); return mOkHttpClient.newCall(request).execute(); } private Response _post(String url, File file, String fileKey) throws IOException { Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null, null); return mOkHttpClient.newCall(request).execute(); } private Response _post(String url, File file, String fileKey, Param[] params) throws IOException { Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null, params); return mOkHttpClient.newCall(request).execute(); } /** * 异步基于post的文件上传 * * @param url * @param callback * @param files * @param fileKeys * @throws IOException */ private void _postAsyn(ServiceUrlBean url, ResultCallback callback, File[] files, String[] fileKeys, Param[] params) throws IOException { Request request = buildMultipartFormRequest(url.getHost_url(), files, fileKeys, null, params); deliveryResult(url.getService_key(), callback, request); } /** * 异步基于post的文件上传,单文件不带参数上传 * * @param url * @param callback * @param file * @param fileKey * @throws IOException */ private void _postAsyn(ServiceUrlBean url, ResultCallback callback, File file, String fileKey) throws IOException { Request request = buildMultipartFormRequest(url.getHost_url(), new File[]{file}, new String[]{fileKey}, null, null); deliveryResult(url.getService_key(), callback, request); } /** * 异步基于post的文件上传,单文件且携带其他form参数上传 * * @param url * @param callback * @param file * @param fileKey * @param params * @throws IOException */ private void _postAsyn(ServiceUrlBean url, ResultCallback callback, File file, String fileKey, Param[] params) throws IOException { Request request = buildMultipartFormRequest(url.getHost_url(), new File[]{file}, new String[]{fileKey}, null, params); deliveryResult(url.getService_key(), callback, request); } /** * 异步基于post的文件上传,单文件且携带其他form参数上传 * * @param url * @param callback * @param file * @param fileKey * @param params * @throws IOException 带进度 */ private void _postAsyn(ServiceUrlBean url, ResultCallback callback, File file, String fileKey, ProgressRequestListener progressRequestListener, Param[] params) throws IOException { Request request = buildMultipartFormRequest(url.getHost_url(), new File[]{file}, new String[]{fileKey}, progressRequestListener, params); deliveryResult(url.getService_key(), callback, request); } /** * 异步基于post的文件上传,单文件且携带其他form参数上传 * * @param url * @param callback * @param files * @param fileKeys * @param params * @throws IOException 带进度 */ private void _postAsyn(ServiceUrlBean url, ResultCallback callback, File[] files, String[] fileKeys, ProgressRequestListener progressRequestListener, Param[] params) throws IOException { Request request = buildMultipartFormRequest(url.getHost_url(), files, fileKeys, progressRequestListener, params); deliveryResult(url.getService_key(), callback, request); } /** * 异步下载文件 * * @param url * @param destFileDir 本地文件存储的文件夹 * @param callback */ private void _downloadAsyn(final String url, final String destFileDir, final ResultCallback callback) { final Request request = new Request.Builder() .url(url) .build(); final Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { sendFailedStringCallback(request, e, true, callback); } @Override public void onResponse(Call call, Response response) throws IOException { InputStream is = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream fos = null; try { is = response.body().byteStream(); File file = new File(destFileDir, getFileName(url)); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } fos.flush(); //如果下载文件成功,第一个参数为文件的绝对路径 sendSuccessResultCallback(file.getAbsolutePath(), true, callback); } catch (IOException e) { sendFailedStringCallback(response.request(), e, true, callback); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (fos != null) fos.close(); } catch (IOException e) { } } } }); } private String getFileName(String path) { int separatorIndex = path.lastIndexOf("/"); return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length()); } private void setErrorResId(final ImageView view, final int errorResId) { mDelivery.post(new Runnable() { @Override public void run() { view.setImageResource(errorResId); } }); } //*************对外公布的方法************ public static void getAsyn(ServiceUrlBean url, ResultCallback callback, HashMap<String, String> params) { getInstance()._getAsyn(url, callback, params, true, true); } public static void getAsyn(ServiceUrlBean url, ResultCallback callback, HashMap<String, String> params, boolean ifAddPublicParam, boolean ifMainTask) { getInstance()._getAsyn(url, callback, params, ifAddPublicParam, ifMainTask); } public static void postAsyn(ServiceUrlBean url, final ResultCallback callback, Param[] params, boolean ifCheckCode, boolean ifMainTask) { getInstance()._postAsyn(url, callback, params, ifCheckCode, ifMainTask); } public static void postAsyn(ServiceUrlBean url, final ResultCallback callback, Param[] params, boolean ifCheckCode) { getInstance()._postAsyn(url, callback, params, ifCheckCode); } public static void postAsyn(ServiceUrlBean url, final ResultCallback callback, Param[] params) { getInstance()._postAsyn(url, callback, params); } public static void postAsyn(ServiceUrlBean url, final ResultCallback callback, Map<String, String> params) { getInstance()._postAsyn(url, callback, params); } public static Response post(String url, File[] files, String[] fileKeys, Param[] params) throws IOException { return getInstance()._post(url, files, fileKeys, params); } public static Response post(String url, File file, String fileKey) throws IOException { return getInstance()._post(url, file, fileKey); } public static Response post(String url, File file, String fileKey, Param[] params) throws IOException { return getInstance()._post(url, file, fileKey, params); } public static void postAsyn(ServiceUrlBean url, ResultCallback callback, File[] files, String[] fileKeys, Param[] params) throws IOException { getInstance()._postAsyn(url, callback, files, fileKeys, params); } public static void postAsyn(ServiceUrlBean url, ResultCallback callback, File[] files, String[] fileKeys, ProgressRequestListener progressRequestListener, Param[] params) throws IOException { getInstance()._postAsyn(url, callback, files, fileKeys, progressRequestListener, params); } public static void postAsyn(ServiceUrlBean url, ResultCallback callback, File file, String fileKey) throws IOException { getInstance()._postAsyn(url, callback, file, fileKey); } public static void postAsyn(ServiceUrlBean url, ResultCallback callback, File file, String fileKey, Param[] params) throws IOException { getInstance()._postAsyn(url, callback, file, fileKey, params); } //带进度 public static void postAsyn(ServiceUrlBean url, ResultCallback callback, File file, String fileKey, ProgressRequestListener progressRequestListener, Param[] params) throws IOException { getInstance()._postAsyn(url, callback, file, fileKey, progressRequestListener, params); } public static void downloadAsyn(ServiceUrlBean url, String destDir, ResultCallback callback) { getInstance()._downloadAsyn(url.getHost_url(), destDir, callback); } //**************************** private String guessMimeType(String path) { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String contentTypeFor = fileNameMap.getContentTypeFor(path); if (contentTypeFor == null) { contentTypeFor = "application/octet-stream"; } return contentTypeFor; } private Param[] validateParam(Param[] params) { if (params == null) return new Param[0]; else return params; } private Param[] map2Params(Map<String, String> params) { if (params == null) return new Param[0]; int size = params.size(); Param[] res = new Param[size]; Set<Map.Entry<String, String>> entries = params.entrySet(); int i = 0; for (Map.Entry<String, String> entry : entries) { res[i++] = new Param(entry.getKey(), entry.getValue()); } return res; } private static final String SESSION_KEY = "Set-Cookie"; private static final String mSessionKey = "JSESSIONID"; private Map<String, String> mSessions = new HashMap<String, String>(); /** * 取消所有接口 * * @return */ public void cancelAll() { try { mOkHttpClient.dispatcher().cancelAll(); } catch (Exception e) { } } private void deliveryResult(final String serviceKey, final ResultCallback callback, final Request request) { deliveryResult(serviceKey, callback, request, true, true); } private void deliveryResult(final String serviceKey, final ResultCallback callback, final Request request, final boolean ifCheckCode, final boolean ifMainTask) { mOkHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { if (!NetUtils.hasNetwork(OneAccountHelper.getContext())) { // ToastUtils.simpleToast(R.string.network_unavailable); } else if (!StringUtils.equalsNull(serviceKey)) { ServiceConstants.ResetServiceByKey(serviceKey); } sendFailedStringCallback(request, e, serviceKey, ifMainTask, callback); } @Override public void onResponse(Call call, Response response) throws IOException { try { // final String string = response.body().string(); //改为流式传输,防止OOM final String string = BaseUtils.inputStream2String(response.body().byteStream()); if (!StringUtils.equalsNull(string)) { LogUtils.d("http-->", string); if (callback.mType == String.class) { sendSuccessResultCallback(string, ifMainTask, callback); } else { Result result = mGson.fromJson(string, callback.mType); if (ifCheckCode) { boolean b = OneOpenHelper.checkResultCode(result); // if (result.getCode() == 100800 || result.getCode() == 100900) { // String url = response.toString(); // LogUtils.d(url); // } } sendSuccessResultCallback(result, ifMainTask, callback); } } else { sendFailedStringCallback(response.request(), new NullPointerException("string null"), ifMainTask, callback); } } catch (com.google.gson.JsonParseException e)//Json解析的错误 { sendFailedStringCallback(response.request(), e, ifMainTask, callback); } catch (Exception e) { sendFailedStringCallback(response.request(), e, ifMainTask, callback); } } }); } private void sendFailedStringCallback(final Request request, final Exception e, boolean ifMainTask, final ResultCallback callback) { sendFailedStringCallback(request, e, null, ifMainTask, callback); } private void sendFailedStringCallback(final Request request, final Exception e, final String serviceKey, boolean ifMainTask, final ResultCallback callback) { if (ifMainTask) { mDelivery.post(new Runnable() { @Override public void run() { try { if (callback != null) callback.onError(request, e); } catch (Exception e2) { e2.printStackTrace(); } } }); } else { try { if (callback != null) callback.onError(request, e); } catch (Exception e3) { e3.printStackTrace(); } } } private void sendSuccessResultCallback(final Object object, boolean ifMainTask, final ResultCallback callback) { if (ifMainTask) { mDelivery.post(new Runnable() { @Override public void run() { if (callback != null) { try { callback.onResponse(object); } catch (Exception e) { e.printStackTrace(); } } } }); } else { if (callback != null) { try { callback.onResponse(object); } catch (Exception e) { e.printStackTrace(); } } } } private Request buildPostRequest(String url, Param[] params) { FormBody.Builder builder = new FormBody.Builder(); boolean ifHasParams = false; if (params != null) { for (Param param : params) { String value = param.value; if (StringUtils.equalsNull(value)) { value = ""; } builder.add(param.key, value); ifHasParams = true; } } url = BaseUtils.buildUrl(url, ServiceConstants.GetHttpPublicParams()); if (ifHasParams) { RequestBody requestBody = builder.build(); return new Request.Builder() .url(url) .post(requestBody) .build(); } else { return new Request.Builder() .url(url) .build(); } } private Request buildPostRequest2(String url, Param[] params) { MultipartBody.Builder builder = new MultipartBody.Builder(); builder.setType(MultipartBody.FORM); boolean ifHasParams = false; if (params != null) { for (Param param : params) { // if (StringUtils.equalsNull(param.key)) { // builder.addPart(Headers.of("Content-Type", "application/json"), // RequestBody.create(null, param.value)); // } else String value = param.value; if (StringUtils.equalsNull(value)) { value = ""; } builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""), RequestBody.create(null, value)); ifHasParams = true; } } // for (Map.Entry<String, String> entry : ServiceConstants.SERVICE_PUBLIC_PARAMS.entrySet()) { // if (!StringUtils.equalsNull(entry.getValue())) // builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""), // RequestBody.create(null, entry.getValue())); // } url = BaseUtils.buildUrl(url, ServiceConstants.GetHttpPublicParams()); if (ifHasParams) { RequestBody requestBody = builder.build(); return new Request.Builder() .url(url) .post(requestBody) .build(); } else { return new Request.Builder() .url(url) .build(); } } //无参请求 private Request buildGetRequest(String url, HashMap<String, String> params, boolean ifAddPublicParam) { if (params == null) { params = new HashMap<>(); } if (ifAddPublicParam) { params.putAll(ServiceConstants.GetHttpPublicParams()); } url = BaseUtils.buildUrl(url, params); return new Request.Builder() .url(url) .build(); } // // //返回进度 // // private Request buildMultipartFormRequest(String url, File[] files, String[] fileKeys, ProgressRequestListener progressRequestListener, Param[] params) { params = validateParam(params); MultipartBody.Builder builder = new MultipartBody.Builder(); builder.setType(MultipartBody.FORM); if (params != null) for (Param param : params) { if (!StringUtils.equalsNull(param.value)) { builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""), RequestBody.create(null, param.value)); } } if (files != null) { RequestBody fileBody = null; for (int i = 0; i < files.length; i++) { File file = files[i]; String fileName = file.getName(); fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file); //TODO 根据文件名设置contentType builder.addFormDataPart(fileKeys[i], fileName, fileBody); } } url = BaseUtils.buildUrl(url, ServiceConstants.GetHttpPublicParams()); RequestBody requestBody = builder.build(); if (progressRequestListener != null) return new Request.Builder() .url(url) .post(new ProgressRequestBody(requestBody, progressRequestListener)) .build(); else return new Request.Builder() .url(url) .post(requestBody) .build(); } public static abstract class ResultCallback<T> { Type mType; public ResultCallback() { mType = getSuperclassTypeParameter(getClass()); } static Type getSuperclassTypeParameter(Class<?> subclass) { Type superclass = subclass.getGenericSuperclass(); if (superclass instanceof Class) { throw new RuntimeException("Missing type parameter."); } ParameterizedType parameterized = (ParameterizedType) superclass; return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]); } public abstract void onError(Request request, Exception e); public abstract void onResponse(T response); } public static class Param { public Param() { } public Param(String key, String value) { this.key = key; this.value = value; } String key; String value; } } class GzipRequestInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) { return chain.proceed(originalRequest); } Request compressedRequest = originalRequest.newBuilder() .header("Content-Encoding", "gzip") .method(originalRequest.method(), gzip(originalRequest.body())) .build(); return chain.proceed(compressedRequest); } private RequestBody gzip(final RequestBody body) { return new RequestBody() { @Override public MediaType contentType() { return body.contentType(); } @Override public long contentLength() { return -1; // We don't know the compressed length in advance! } @Override public void writeTo(BufferedSink sink) throws IOException { BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); body.writeTo(gzipSink); gzipSink.close(); } }; } }
package org.jabref.logic.specialfields; import java.util.Arrays; import java.util.List; import java.util.Optional; import org.jabref.model.FieldChange; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.FieldName; import org.jabref.model.entry.Keyword; import org.jabref.model.entry.KeywordList; import org.jabref.model.entry.specialfields.SpecialField; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class SpecialFieldsUtilsTest { @Test public void syncKeywordsFromSpecialFieldsWritesToKeywords() { BibEntry entry = new BibEntry(); entry.setField("ranking", "rank2"); SpecialFieldsUtils.syncKeywordsFromSpecialFields(entry, ','); assertEquals(Optional.of("rank2"), entry.getField("keywords")); } @Test public void syncKeywordsFromSpecialFieldsCausesChange() { BibEntry entry = new BibEntry(); entry.setField("ranking", "rank2"); List<FieldChange> changes = SpecialFieldsUtils.syncKeywordsFromSpecialFields(entry, ','); assertTrue(changes.size() > 0); } @Test public void syncKeywordsFromSpecialFieldsOverwritesKeywords() { BibEntry entry = new BibEntry(); entry.setField("ranking", "rank2"); entry.setField("keywords", "rank3"); SpecialFieldsUtils.syncKeywordsFromSpecialFields(entry, ','); assertEquals(Optional.of("rank2"), entry.getField("keywords")); } @Test public void syncKeywordsFromSpecialFieldsForEmptyFieldCausesNoChange() { BibEntry entry = new BibEntry(); List<FieldChange> changes = SpecialFieldsUtils.syncKeywordsFromSpecialFields(entry, ','); assertFalse(changes.size() > 0); } @Test public void syncSpecialFieldsFromKeywordWritesToSpecialField() { BibEntry entry = new BibEntry(); entry.setField("keywords", "rank2"); SpecialFieldsUtils.syncSpecialFieldsFromKeywords(entry, ','); assertEquals(Optional.of("rank2"), entry.getField("ranking")); } @Test public void syncSpecialFieldsFromKeywordCausesChange() { BibEntry entry = new BibEntry(); entry.setField("keywords", "rank2"); List<FieldChange> changes = SpecialFieldsUtils.syncSpecialFieldsFromKeywords(entry, ','); assertTrue(changes.size() > 0); } @Test public void syncSpecialFieldsFromKeywordCausesNoChangeWhenKeywordsAreEmpty() { BibEntry entry = new BibEntry(); List<FieldChange> changes = SpecialFieldsUtils.syncSpecialFieldsFromKeywords(entry, ','); assertFalse(changes.size() > 0); } @Test public void updateFieldRemovesSpecialFieldKeywordWhenKeywordSyncIsUsed() { BibEntry entry = new BibEntry(); SpecialField specialField = SpecialField.PRINTED; Keyword specialFieldKeyword = specialField.getKeyWords().get(0); // Add the special field SpecialFieldsUtils.updateField(specialField, specialFieldKeyword.get(), entry, true, true, ','); // Remove it List<FieldChange> changes = SpecialFieldsUtils.updateField(specialField, specialFieldKeyword.get(), entry, true, true, ','); assertEquals(Arrays.asList(new FieldChange(entry, specialField.getFieldName(), specialFieldKeyword.get(), null), new FieldChange(entry, FieldName.KEYWORDS, specialFieldKeyword.get(), null)), changes); KeywordList remainingKeywords = entry.getKeywords(','); assertFalse(remainingKeywords.contains(specialFieldKeyword)); } }
package com.example.fourbutton; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { Button button1, button2, button3, button4; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setIcon(R.drawable.ic_launcher); button1 = (Button) findViewById(R.id.button1); button1.setBackgroundColor(Color.GRAY); button2 = (Button) findViewById(R.id.button2); button2.setBackgroundColor(Color.GREEN); button3 = (Button) findViewById(R.id.button3); button3.setBackgroundColor(Color.RED); button4 = (Button) findViewById(R.id.button4); button4.setBackgroundColor(Color.YELLOW); button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.nate.com")); startActivity(mIntent); } }); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:/911")); startActivity(mIntent); } }); button3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent mIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("content://media/internal/images/media")); startActivity(mIntent); } }); button4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
package com.haiyang.spring.input.fromfile; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableBatchProcessing public class FromFileApplication { public static void main(String[] args) { SpringApplication.run(FromFileApplication.class, args); } }
package com.yandex.ydb.table.result.impl; import java.util.HashMap; import java.util.Map; import com.yandex.ydb.ValueProtos; import com.yandex.ydb.table.result.ValueReader; /** * @author Sergey Polovko */ final class ProtoStructValueReader extends AbstractValueReader { private final ValueProtos.Type type; private final AbstractValueReader[] memberReaders; private final Map<String, Integer> nameIdx; private ValueProtos.Value value; ProtoStructValueReader(ValueProtos.Type type, AbstractValueReader[] memberReaders) { this.type = type; this.memberReaders = memberReaders; this.nameIdx = buildNameIdx(type.getStructType()); } private static HashMap<String, Integer> buildNameIdx(ValueProtos.StructType structType) { HashMap<String, Integer> nameIdx = new HashMap<>(structType.getMembersCount()); for (int i = 0; i < structType.getMembersCount(); i++) { nameIdx.put(structType.getMembers(i).getName(), i); } return nameIdx; } @Override protected ValueProtos.Type getProtoType() { return type; } @Override protected ValueProtos.Value getProtoValue() { return value; } @Override protected void setProtoValue(ValueProtos.Value value) { this.value = value; } @Override public int getStructMembersCount() { return memberReaders.length; } @Override public String getStructMemberName(int index) { return type.getStructType().getMembers(index).getName(); } @Override public ValueReader getStructMember(int index) { AbstractValueReader memberReader = memberReaders[index]; memberReader.setProtoValue(value.getItems(index)); return memberReader; } @Override public ValueReader getStructMember(String name) { Integer index = nameIdx.get(name); if (index == null) { throw new IllegalArgumentException("unknown member name: '" + name + '\''); } return getStructMember(index); } @Override public void toString(StringBuilder sb) { sb.append("Struct["); for (int i = 0; i < getStructMembersCount(); i++) { String name = getStructMemberName(i); sb.append(name).append(": "); getStructMember(i).toString(sb); sb.append(", "); } if (getStructMembersCount() > 0) { sb.setLength(sb.length() - 2); } sb.append(']'); } }
package ai.nightfall.scan.model; /** * The exception thrown when the Nightfall client is unable to process a request due to an unexpected error. */ public class NightfallClientException extends BaseNightfallException { /** * Create a new instance of this exception. * * @param message an error message */ public NightfallClientException(String message) { super(message); } }
/* * 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.camel.itest.jetty; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.ResolveEndpointFailedException; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.support.ResourceHelper; import org.apache.camel.test.AvailablePortFinder; import org.apache.camel.test.junit5.CamelTestSupport; import org.apache.camel.util.ObjectHelper; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class JettyVelocityTest extends CamelTestSupport { private int port; @Test void testClasspath() { Map<String, Object> map = new HashMap<>(); map.put("firstName", "John"); map.put("lastName", "Doe"); String response = template.requestBodyAndHeaders("velocity:org/apache/camel/itest/jetty/header.vm", "", map, String.class); assertEquals("Dear Doe, John", response); } @Test void testClasspathInvalidParameter() { try { Map<String, Object> map = new HashMap<>(); map.put("firstName", "John"); map.put("lastName", "Doe"); template.requestBodyAndHeaders("velocity:org/apache/camel/itest/jetty/?name=header.vm", "", map, String.class); fail("Should have thrown exception"); } catch (ResolveEndpointFailedException e) { assertTrue(e.getMessage().endsWith("Unknown parameters=[{name=header.vm}]")); } } @Test void testHttp() { Map<String, Object> map = new HashMap<>(); map.put("firstName", "John"); map.put("lastName", "Doe"); String response = template.requestBodyAndHeaders("velocity://http://localhost:" + port + "/test?name=header.vm", "", map, String.class); assertEquals("Dear Doe, John", response); } @Override protected RouteBuilder createRouteBuilder() { port = AvailablePortFinder.getNextAvailable(); return new RouteBuilder() { public void configure() { from("jetty:http://localhost:" + port + "/test") .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { String name = exchange.getIn().getHeader("name", String.class); ObjectHelper.notNull(name, "name"); name = "org/apache/camel/itest/jetty/" + name; InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(exchange.getContext(), name); String xml = exchange.getContext().getTypeConverter().convertTo(String.class, is); exchange.getMessage().setBody(xml); exchange.getMessage().setHeader(Exchange.CONTENT_TYPE, "text/plain"); } }); } }; } }
package example.repo; import example.model.Customer1721; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer1721Repository extends CrudRepository<Customer1721, Long> { List<Customer1721> findByLastName(String lastName); }
/* * 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.camel.dataformat.bindy.fixed.dynamic; import java.math.BigDecimal; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import org.apache.camel.EndpointInject; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.dataformat.bindy.annotation.DataField; import org.apache.camel.dataformat.bindy.annotation.FixedLengthRecord; import org.apache.camel.model.dataformat.BindyDataFormat; import org.apache.camel.model.dataformat.BindyType; import org.apache.camel.test.junit5.CamelTestSupport; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; /** * This test validates the marshalling / unmarshalling of a fixed-length data field for which the length of the field is * defined by the value of another field in the record. */ public class BindyFixedLengthDynamicFieldTest extends CamelTestSupport { public static final String URI_DIRECT_MARSHALL = "direct:marshall"; public static final String URI_DIRECT_UNMARSHALL = "direct:unmarshall"; public static final String URI_MOCK_MARSHALL_RESULT = "mock:marshall-result"; public static final String URI_MOCK_UNMARSHALL_RESULT = "mock:unmarshall-result"; private static final String TEST_RECORD = "10A9Pauline^M^ISIN10XD12345678BUYShare000002500.45USD01-08-2009\r\n"; private static final String TEST_RECORD_WITH_EXTRA_CHARS = "10A9Pauline^M^ISIN10XD12345678BUYShare000002500.45USD01-08-2009x\r\n"; @EndpointInject(URI_MOCK_MARSHALL_RESULT) private MockEndpoint marshallResult; @EndpointInject(URI_MOCK_UNMARSHALL_RESULT) private MockEndpoint unmarshallResult; // ************************************************************************* // TESTS // ************************************************************************* @Test public void testUnmarshallMessage() throws Exception { unmarshallResult.expectedMessageCount(1); template.sendBody(URI_DIRECT_UNMARSHALL, TEST_RECORD); unmarshallResult.assertIsSatisfied(); // check the model BindyFixedLengthDynamicFieldTest.Order order = (BindyFixedLengthDynamicFieldTest.Order) unmarshallResult.getReceivedExchanges().get(0).getIn().getBody(); assertEquals(10, order.getOrderNr()); // the field is not trimmed assertEquals("Pauline", order.getFirstName()); assertEquals("M", order.getLastName()); assertEquals("XD12345678", order.getInstrumentNumber()); } @Test public void testFailWhenUnmarshallMessageWithUnmappedChars() throws Exception { unmarshallResult.reset(); unmarshallResult.expectedMessageCount(0); try { template.sendBody(URI_DIRECT_UNMARSHALL, TEST_RECORD_WITH_EXTRA_CHARS); } catch (Exception e) { assertTrue(e.getCause() instanceof IllegalArgumentException); assertTrue(e.getCause().getMessage().contains("unmapped characters")); return; } fail("An error is expected when unmapped characters are encountered in the fixed length record"); } @Test public void testMarshallMessage() throws Exception { BindyFixedLengthDynamicFieldTest.Order order = new Order(); order.setOrderNr(10); order.setOrderType("BUY"); order.setClientNr("A9"); order.setFirstName("Pauline"); order.setLastName("M"); order.setAmount(new BigDecimal("2500.45")); order.setInstrumentCode("ISIN"); order.setInstrumentNumberLen(10); order.setInstrumentNumber("XD12345678"); order.setInstrumentType("Share"); order.setCurrency("USD"); Calendar calendar = new GregorianCalendar(); calendar.set(2009, 7, 1); order.setOrderDate(calendar.getTime()); marshallResult.expectedMessageCount(1); marshallResult.expectedBodiesReceived(Arrays.asList(new String[] { TEST_RECORD })); template.sendBody(URI_DIRECT_MARSHALL, order); marshallResult.assertIsSatisfied(); } // ************************************************************************* // ROUTES // ************************************************************************* @Override protected RouteBuilder createRouteBuilder() throws Exception { RouteBuilder routeBuilder = new RouteBuilder() { @Override public void configure() throws Exception { BindyDataFormat bindy = new BindyDataFormat() .locale("en") .classType(BindyFixedLengthDynamicFieldTest.Order.class) .fixed(); from(URI_DIRECT_MARSHALL) .marshal(bindy) .to(URI_MOCK_MARSHALL_RESULT); from(URI_DIRECT_UNMARSHALL) .unmarshal().bindy(BindyType.Fixed, BindyFixedLengthDynamicFieldTest.Order.class) .to(URI_MOCK_UNMARSHALL_RESULT); } }; return routeBuilder; } // ************************************************************************* // DATA MODEL // ************************************************************************* @FixedLengthRecord() public static class Order { @DataField(pos = 1, length = 2) private int orderNr; @DataField(pos = 2, length = 2) private String clientNr; @DataField(pos = 3, delimiter = "^") private String firstName; @DataField(pos = 4, delimiter = "^") private String lastName; @DataField(pos = 5, length = 4) private String instrumentCode; @DataField(pos = 6, length = 2, align = "R", paddingChar = '0') private int instrumentNumberLen; @DataField(pos = 7, length = 10) private String instrumentNumber; @DataField(pos = 8, length = 3) private String orderType; @DataField(pos = 9, length = 5) private String instrumentType; @DataField(pos = 10, precision = 2, length = 12, paddingChar = '0') private BigDecimal amount; @DataField(pos = 11, length = 3) private String currency; @DataField(pos = 12, length = 10, pattern = "dd-MM-yyyy") private Date orderDate; public int getOrderNr() { return orderNr; } public void setOrderNr(int orderNr) { this.orderNr = orderNr; } public String getClientNr() { return clientNr; } public void setClientNr(String clientNr) { this.clientNr = clientNr; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getInstrumentCode() { return instrumentCode; } public void setInstrumentCode(String instrumentCode) { this.instrumentCode = instrumentCode; } public void setInstrumentNumberLen(int instrumentNumberLen) { this.instrumentNumberLen = instrumentNumberLen; } public int getInstrumentNumberLen() { return instrumentNumberLen; } public String getInstrumentNumber() { return instrumentNumber; } public void setInstrumentNumber(String instrumentNumber) { this.instrumentNumber = instrumentNumber; } public String getOrderType() { return orderType; } public void setOrderType(String orderType) { this.orderType = orderType; } public String getInstrumentType() { return instrumentType; } public void setInstrumentType(String instrumentType) { this.instrumentType = instrumentType; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public Date getOrderDate() { return orderDate; } public void setOrderDate(Date orderDate) { this.orderDate = orderDate; } @Override public String toString() { return "Model : " + Order.class.getName() + " : " + this.orderNr + ", " + this.orderType + ", " + String.valueOf(this.amount) + ", " + this.instrumentCode + ", " + this.instrumentNumber + ", " + this.instrumentType + ", " + this.currency + ", " + this.clientNr + ", " + this.firstName + ", " + this.lastName + ", " + String.valueOf(this.orderDate); } } }
// This file is part of PDQ (https://github.com/ProofDrivenQuerying/pdq) which is released under the MIT license. // See accompanying LICENSE for copyright notice and full details. package uk.ac.ox.cs.pdq.test.algebra; import java.util.Set; import org.junit.Assert; import org.junit.Test; import uk.ac.ox.cs.pdq.algebra.AccessTerm; import uk.ac.ox.cs.pdq.algebra.Condition; import uk.ac.ox.cs.pdq.algebra.ConjunctiveCondition; import uk.ac.ox.cs.pdq.algebra.JoinTerm; import uk.ac.ox.cs.pdq.algebra.RelationalTerm; import uk.ac.ox.cs.pdq.db.AccessMethodDescriptor; import uk.ac.ox.cs.pdq.db.Attribute; import uk.ac.ox.cs.pdq.db.Relation; import uk.ac.ox.cs.pdq.db.tuple.Tuple; import uk.ac.ox.cs.pdq.db.tuple.TupleType; import uk.ac.ox.cs.pdq.test.util.PdqTest; public class JoinTermTest extends PdqTest { // Dummy concrete class for testing. public class DummyJoinTerm extends JoinTerm { private static final long serialVersionUID = 1L; public DummyJoinTerm(RelationalTerm leftChild, RelationalTerm rightChild) { super(leftChild, rightChild); } public DummyJoinTerm(RelationalTerm leftChild, RelationalTerm rightChild, Condition joinCondition) { super(leftChild, rightChild); } public Condition computeJoinCondition() { return super.getJoinConditions(); } } // Attributes in the internal schema. Attribute[] attributes_nation = new Attribute[] { Attribute.create(Integer.class, "nationKey"), Attribute.create(String.class, "name"), Attribute.create(Integer.class, "regionKey"), Attribute.create(String.class, "comment") }; Attribute[] attributes_region = new Attribute[] { Attribute.create(Integer.class, "regionKey"), Attribute.create(String.class, "name"), Attribute.create(String.class, "comment") }; // Attributes in the external schema. Attribute[] attributes_N = new Attribute[] { Attribute.create(Integer.class, "N_NATIONKEY"), Attribute.create(String.class, "N_NAME"), Attribute.create(Integer.class, "N_REGIONKEY"), Attribute.create(String.class, "N_COMMENT") }; Attribute[] attributes_R = new Attribute[] { Attribute.create(Integer.class, "R_REGIONKEY"), Attribute.create(String.class, "R_NAME"), Attribute.create(String.class, "R_COMMENT") }; @Test public void testJoinTerm() { JoinTerm target; AccessTerm leftChild; AccessTerm rightChild; /* * Using the internal schema. */ leftChild = AccessTerm.create(Relation.create("r", attributes_nation), AccessMethodDescriptor.create("am", new Integer[] {0})); rightChild = AccessTerm.create(Relation.create("r", attributes_region), AccessMethodDescriptor.create("am", new Integer[] {0})); // Construct with the default join condition. target = JoinTerm.create(leftChild, rightChild); Assert.assertTrue(target instanceof JoinTerm); // Construct with a custom join condition. //joinCondition = TypeEqualityCondition.create(2, 4); target = JoinTerm.create(leftChild, rightChild); Assert.assertTrue(target instanceof JoinTerm); // Test with an invalid custom join condition (types are different). //joinCondition = TypeEqualityCondition.create(2, 5); boolean caught; caught = false; try { JoinTerm.create(leftChild, rightChild); } catch (IllegalStateException e) { caught = true; } Assert.assertFalse(caught); /* * None of the attribute names are equal in the external schema * (due to the N_ and R_ prefixes) so attempting to construct * a JoinTerm fails to result in a valid join condition. */ caught = false; try { JoinTerm.create(leftChild, rightChild); } catch (IllegalStateException e) { caught = true; } Assert.assertFalse(caught); /* * Instead we must provide a custom join condition to join on the 2nd * NATION attribute (i.e. N_REGIONKEY) and the 0th REGION attribute * (i.e. R_REGIONKEY). */ //joinCondition = TypeEqualityCondition.create(2, 4); target = JoinTerm.create(leftChild, rightChild); Assert.assertTrue(target instanceof JoinTerm); } @Test public void testComputeJoinCondition() { DummyJoinTerm target; Condition result; RelationalTerm leftChild; RelationalTerm rightChild; leftChild = AccessTerm.create(Relation.create("r", attributes_nation), AccessMethodDescriptor.create("am", new Integer[] {0})); rightChild = AccessTerm.create(Relation.create("r", attributes_region), AccessMethodDescriptor.create("am", new Integer[] {0})); target = new DummyJoinTerm(leftChild, rightChild); result = target.computeJoinCondition(); // By default, the join condition is that of the "natural join". That is, join // on all attributes with common names. Assert.assertTrue(result instanceof ConjunctiveCondition); Assert.assertEquals(3, ((ConjunctiveCondition) result).getNumberOfConjuncts()); ((ConjunctiveCondition) result).getSimpleConditions(); } @Test public void testGetJoinConditionTuple() { AccessTerm leftChild; AccessTerm rightChild; /* * Using the external schema. */ leftChild = AccessTerm.create(Relation.create("r", new Attribute[] { Attribute.create(Integer.class, "c") }), AccessMethodDescriptor.create("am", new Integer[] {0})); rightChild = AccessTerm.create(Relation.create("r", new Attribute[] { Attribute.create(Integer.class, "c") }), AccessMethodDescriptor.create("am", new Integer[] {0})); JoinTerm.create(leftChild, rightChild); // Construct some tuples to pass as arguments to getJoinCondition(). TupleType ttNation = TupleType.DefaultFactory.create(Integer.class, String.class, Integer.class, String.class); Tuple tupleNation = ttNation.createTuple(5, "ETHIOPIA", 0, "abc"); TupleType ttRegion = TupleType.DefaultFactory.create(Integer.class, String.class, String.class); Tuple tupleRegion1 = ttRegion.createTuple(0, "AFRICA", "xyz"); Tuple tupleRegion2 = ttRegion.createTuple(1, "AMERICA", "ijk"); tupleNation.appendTuple(tupleRegion1); tupleNation.appendTuple(tupleRegion2); JoinTerm.create(leftChild, rightChild); // The join condition is _not_ satisfied, since the value at index 0 in tupleNation // does not match that at index 0 in tupleRegion. // Now repeat with a custom join condition which matches both: // - N_REGIONKEY with R_REGIONKEY, and // - N_COMMENT with R_COMMENT. JoinTerm.create(leftChild, rightChild); Tuple tupleRegion3 = ttRegion.createTuple(0, "AFRICA", "abc"); tupleNation.appendTuple(tupleRegion3); // The join condition is satisfied on tuple3 only, since that tuple // matches both the REGIONKEY and COMMENT from tupleNation. } @Test public void testJoinMap() { AccessTerm leftChild; AccessTerm rightChild; leftChild = AccessTerm.create(Relation.create("r", new Attribute[] { Attribute.create(Integer.class, "c") }), AccessMethodDescriptor.create("am", new Integer[] {0})); rightChild = AccessTerm.create(Relation.create("r", new Attribute[] { Attribute.create(Integer.class, "c") }), AccessMethodDescriptor.create("am", new Integer[] {0})); // Construct with the default join condition. JoinTerm.create(leftChild, rightChild); JoinTerm.create(leftChild, rightChild); } /* * Tests the JoinTerm class by calling every method. * Other classes are used as required. * INPUTS: None * OUTPUTS: Documented below * PERFORMANCE: On 11/4/2018 this JUnit test returned in 0.5s on Mark's machine */ @Test public void testCreation() { Relation relation1 = Relation.create("relation1", new Attribute[] { Attribute.create(String.class, "attribute1") }); Relation relation2 = Relation.create("relation2", new Attribute[] { Attribute.create(String.class, "attribute2")}); RelationalTerm child1 = AccessTerm.create(relation1, AccessMethodDescriptor.create("am", new Integer[] {0})); RelationalTerm child2 = AccessTerm.create(relation2, AccessMethodDescriptor.create("am", new Integer[] {0})); // Constructor tests invariant JoinTerm jt = JoinTerm.create(child1, child2); // JoinTerm.equals null should be false boolean b = jt.equals(null); Assert.assertFalse(b); // JoinTerm.getClass has an expected name Assert.assertTrue(jt.getClass().getName() == "uk.ac.ox.cs.pdq.algebra.JoinTerm"); // JoinTerm.hashCode is non negative int h = jt.hashCode(); Assert.assertTrue(h >= 0); // JoinTerm.toString is #1=#2&#3=#4 String s = jt.toString(); Assert.assertTrue(s.equals("Join{[]Access{relation1,am[#0=attribute1]},Access{relation2,am[#0=attribute2]}}")); // RelationalTerm returned from JoinTerm.getAccesses is invariant Set<AccessTerm> sat = jt.getAccesses(); Assert.assertNotNull(sat); Assert.assertFalse(sat.isEmpty()); // RelationalTerm returned from JoinTerm.getChild is invariant RelationalTerm p = jt.getChild(0); Assert.assertNotNull(p); // array returned from JoinTerm.getChildren has zero length RelationalTerm[] pp = jt.getChildren(); Assert.assertTrue(pp.length == 2); // Class returned from getClass has name JoinTerm Assert.assertTrue(jt.getClass().getName() == "uk.ac.ox.cs.pdq.algebra.JoinTerm"); // RelationalTerm returned from JoinTerm.getInputAttribute is invariant Attribute aa = jt.getInputAttribute(0); Assert.assertNotNull(aa); // array returned from JoinTerm.getInputAttributes has zero length Attribute[] aaa = jt.getInputAttributes(); Assert.assertTrue(aaa.length == 2); // JoinTerm.getJoinCondition is invariant Condition c = jt.getJoinConditions(); Assert.assertNotNull(c); // JoinTerm.getNumberOfInputAttributes is one int nia = jt.getNumberOfInputAttributes(); Assert.assertTrue(nia == 2); // JoinTerm.getNumberOfOutputAttributes is one int noa = jt.getNumberOfOutputAttributes(); Assert.assertTrue(noa == 2); // JoinTerm.getOutputAttribute is invariant Attribute oa = jt.getOutputAttribute(0); Assert.assertNotNull(oa); // JoinTerm.getOutputAttributes has length three Attribute[] oas = jt.getOutputAttributes(); Assert.assertTrue(oas.length == 2); // isClosed is true boolean b2 = jt.isClosed(); Assert.assertFalse(b2); } }
package com.xstudio.controllers.framework; import org.apache.ibatis.session.RowBounds; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Created by kira on 16/8/21. */ public interface IList { List<LinkedHashMap<String, Object>> all(RowBounds pagination, Map<String, String> map); }
package com.github.teocci.socket.tester.ui; import javax.swing.*; import java.awt.*; import com.github.teocci.socket.tester.model.PortModel; import com.github.teocci.socket.tester.util.Util; /** * Created by teocci. * * @author teocci@yandex.com on 2017-Jun-21 */ public class PortDialog extends JDialog { public static final int UDP = 1; public static final int TCP = 2; private PortModel model; /** * Creates a new instance of PortDialog */ public PortDialog(JFrame parent, int type) { super(parent); if (type == TCP) { setTitle("Standard TCP Port"); model = new PortModel("TCP-PORTS"); } else { setTitle("Select UDP port"); model = new PortModel("UDP-PORTS"); } Container cp = getContentPane(); JTable table = new JTable(model); cp.add(new JScrollPane(table)); setSize(300, 200); Util.centerWindow(this); } public String getPort() { return model.getPort(); } }
package tms; import android.content.BroadcastReceiver; import android.content.Context; import com.lenovo.lps.sus.c.c; import com.tencent.tmsecure.common.BaseManager; import com.tencent.tmsecure.common.ManagerCreator; import com.tencent.tmsecure.module.phoneservice.IpDialHeaders; import com.tencent.tmsecure.module.phoneservice.IpDialManagerSetting; import com.tencent.tmsecure.module.phoneservice.IpDialPhoneNumber; import com.tencent.tmsecure.module.phoneservice.IpDialProvinceCity; import com.tencent.tmsecure.module.phoneservice.LocationManager; import com.tencent.tmsecure.utils.Log; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public final class fi extends BaseManager { af a; IpDialManagerSetting b; LocationManager c; private IpDialManagerSetting b() { IpDialManagerSetting ipDialManagerSetting = new IpDialManagerSetting(); String a2 = this.a.a("ip_dial_setting", (String) null); if (a2 != null) { try { ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(r.a(a2)); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); ipDialManagerSetting.copyFrom((IpDialManagerSetting) objectInputStream.readObject()); objectInputStream.close(); byteArrayInputStream.close(); } catch (Exception e) { Log.i("IpDialManagerImpl", e.getMessage()); } } b("call [getIpDialSettingFromDB]"); return ipDialManagerSetting; } private void b(String str) { Log.i("IpDialManagerImpl", str); Log.i("IpDialManagerImpl", "SETTING Dial Mode: " + this.b.getIpDialMode()); Log.i("IpDialManagerImpl", "SETTING Ip Head: " + this.b.getIpHeader()); Log.i("IpDialManagerImpl", "SETTING Local Phone:" + this.b.getLocalPhoneLocation().getProvince() + this.b.getLocalPhoneLocation().getCity()); Log.i("IpDialManagerImpl", "SETTING Excluded Area: " + this.b.getExcludedAreaList().listToString()); Log.i("IpDialManagerImpl", "SETTING Excluded Phone: " + this.b.getExcludedPhoneNumberList().listToString()); } private String c(String str) { String ipHeader = this.b.getIpHeader(); return (str == null || ipHeader == null || str.startsWith(ipHeader)) ? str : ipHeader + str; } public final IpDialManagerSetting a() { return new IpDialManagerSetting(this.b); } public final String a(String str) { int i = 5; if (str != null && str.length() > 5) { if (this.b.b != null) { i = this.b.b.length(); } String substring = str.substring(0, i); if (IpDialHeaders.IP_HEADER_17911.equals(substring) ? true : IpDialHeaders.IP_HEADER_17951.equals(substring) ? true : IpDialHeaders.IP_HEADER_10193.equals(substring) ? true : IpDialHeaders.IP_HEADER_17910.equals(substring) ? true : IpDialHeaders.IP_HEADER_12520.equals(substring) ? true : IpDialHeaders.IP_HEADER_12583.equals(substring) ? true : IpDialHeaders.IP_HEADER_96688.equals(substring) ? true : IpDialHeaders.IP_HEADER_17901.equals(substring) ? true : IpDialHeaders.IP_HEADER_12593.equals(substring) ? true : IpDialHeaders.IP_HEADER_17909.equals(substring) ? true : this.b.b != null && this.b.b.equals(substring)) { Log.i("IpDialManagerImpl", str + "has IP header, remove the header(" + str.substring(0, i) + ")"); str = str.substring(i); } else { Log.i("IpDialManagerImpl", str + "don't has IP header, go to next step!"); } } StringBuffer stringBuffer = new StringBuffer(); StringBuffer stringBuffer2 = new StringBuffer(); this.c.getLocation(stringBuffer, stringBuffer2, new StringBuffer(), str); String[] split = stringBuffer2.toString().split(" "); IpDialProvinceCity ipDialProvinceCity = new IpDialProvinceCity(); if (split.length > 1) { ipDialProvinceCity.setProvince(split[0].trim()); ipDialProvinceCity.setCity(split[1].trim()); } else { ipDialProvinceCity.setProvince(split[0].trim()); } boolean existed = this.b.getExcludedAreaList().existed(ipDialProvinceCity); Log.i("IpDialManagerImpl", str + " is {" + stringBuffer2.toString() + c.Q); Log.i("IpDialManagerImpl", str + (existed ? " existed" : " not existed") + " in EXCLUDED-AREA list!"); if (!existed) { boolean existed2 = this.b.getExcludedPhoneNumberList().existed(new IpDialPhoneNumber("", str)); Log.i("IpDialManagerImpl", str + (existed2 ? " existed" : " not existed") + " in EXCLUDED-PHONE list!"); if (!existed2) { b("call [getDialPhoneNumber]"); switch (this.b.getIpDialMode()) { case 0: Log.i("IpDialManagerImpl", "use IP-DIAL-MODE when dialing long-distance calls."); if (str == null || str.length() > 8) { StringBuffer stringBuffer3 = new StringBuffer(); StringBuffer stringBuffer4 = new StringBuffer(); this.c.getLocation(stringBuffer3, stringBuffer4, new StringBuffer(), str); String replace = stringBuffer4.toString().trim().replace(" ", ""); String str2 = this.b.getLocalPhoneLocation().getProvince() + this.b.getLocalPhoneLocation().getCity(); Log.i("IpDialManagerImpl", "LocationTrime{" + replace + "} compare localPhone{" + str2 + c.Q); if ((replace.length() <= 0 || replace.compareTo(str2) != 0) && !str.startsWith("400") && !str.startsWith("800")) { Log.i("IpDialManagerImpl", "WHEN-DIAL-LONG-DISTANCE-CALL: You are dialing IP call"); return c(str); } Log.i("IpDialManagerImpl", "WHEN-DIAL-LONG-DISTANCE-CALL: You are dialing local call"); return str; } Log.i("IpDialManagerImpl", str + "'s length less than 8, so do nothing!"); return str; case 1: Log.i("IpDialManagerImpl", "use IP-DIAL-MODE when dialing any calls."); return c(str); case 2: Log.i("IpDialManagerImpl", "not use IP-DIAL-MODE."); return str; default: return str; } } } Log.i("IpDialManagerImpl", str + " is in excluded area or phone list."); return str; } public final void a(IpDialManagerSetting ipDialManagerSetting) { if (ipDialManagerSetting != null) { synchronized (ipDialManagerSetting) { this.b.copyFrom(ipDialManagerSetting); try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(this.b); objectOutputStream.flush(); String a2 = r.a(byteArrayOutputStream.toByteArray()); objectOutputStream.close(); this.a.a("ip_dial_setting", a2, true); } catch (Exception e) { Log.i("IpDialManagerImpl", e.getMessage()); } } b("call [SetIpDialSetting]"); } } public final void a(String str, BroadcastReceiver broadcastReceiver) { if (str != null) { broadcastReceiver.setResultData(str); } } @Override // com.tencent.tmsecure.common.BaseManager public final void onCreate(Context context) { this.a = new af("IpDialProperty"); this.c = (LocationManager) ManagerCreator.getManager(LocationManager.class); this.b = new IpDialManagerSetting(); this.b.copyFrom(b()); } }
package org.ethereum.jsontestsuite; import org.ethereum.jsontestsuite.suite.BlockTestCase; import org.ethereum.jsontestsuite.suite.BlockTestSuite; import org.ethereum.jsontestsuite.suite.StateTestCase; import org.ethereum.jsontestsuite.suite.StateTestSuite; import org.ethereum.jsontestsuite.suite.TestCase; import org.ethereum.jsontestsuite.suite.TestRunner; import org.ethereum.jsontestsuite.suite.TestSuite; import org.ethereum.jsontestsuite.suite.runners.StateTestRunner; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.junit.Assert; import org.junit.Assume; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import static org.junit.Assert.assertTrue; /** * Test file specific for tests maintained in the GitHub repository * by the Ethereum DEV team. <br/> * * @see <a href="https://github.com/ethereum/tests/">https://github.com/ethereum/tests/</a> */ public class GitHubJSONTestSuite { private static Logger logger = LoggerFactory.getLogger("TCK-Test"); protected static void runGitHubJsonVMTest(String json, String testName) throws ParseException { Assume.assumeFalse("Online test is not available", json.equals("")); JSONParser parser = new JSONParser(); JSONObject testSuiteObj = (JSONObject) parser.parse(json); TestSuite testSuite = new TestSuite(testSuiteObj); Iterator<TestCase> testIterator = testSuite.iterator(); for (TestCase testCase : testSuite.getAllTests()) { String prefix = " "; if (testName.equals(testCase.getName())) prefix = " => "; logger.info(prefix + testCase.getName()); } while (testIterator.hasNext()) { TestCase testCase = testIterator.next(); if (testName.equals((testCase.getName()))) { TestRunner runner = new TestRunner(); List<String> result = runner.runTestCase(testCase); Assert.assertTrue(result.isEmpty()); return; } } } protected static void runGitHubJsonVMTest(String json) throws ParseException { Set<String> excluded = new HashSet<>(); runGitHubJsonVMTest(json, excluded); } protected static void runGitHubJsonVMTest(String json, Set<String> excluded) throws ParseException { Assume.assumeFalse("Online test is not available", json.equals("")); JSONParser parser = new JSONParser(); JSONObject testSuiteObj = (JSONObject) parser.parse(json); TestSuite testSuite = new TestSuite(testSuiteObj); Iterator<TestCase> testIterator = testSuite.iterator(); for (TestCase testCase : testSuite.getAllTests()) { String prefix = " "; if (excluded.contains(testCase.getName())) prefix = "[X] "; logger.info(prefix + testCase.getName()); } while (testIterator.hasNext()) { TestCase testCase = testIterator.next(); if (excluded.contains(testCase.getName())) continue; TestRunner runner = new TestRunner(); List<String> result = runner.runTestCase(testCase); Assert.assertTrue(result.isEmpty()); } } protected static void runGitHubJsonSingleBlockTest(String json, String testName) throws ParseException, IOException { BlockTestSuite testSuite = new BlockTestSuite(json); Set<String> testCollection = testSuite.getTestCases().keySet(); for (String testCase : testCollection) { if (testCase.equals(testName)) logger.info(" => " + testCase); else logger.info(" " + testCase); } runSingleBlockTest(testSuite, testName); } protected static void runGitHubJsonBlockTest(String json, Set<String> excluded) throws ParseException, IOException { Assume.assumeFalse("Online test is not available", json.equals("")); BlockTestSuite testSuite = new BlockTestSuite(json); Set<String> testCases = testSuite.getTestCases().keySet(); Map<String, Boolean> summary = new HashMap<>(); for (String testCase : testCases) if ( excluded.contains(testCase)) logger.info(" [X] " + testCase); else logger.info(" " + testCase); for (String testName : testCases) { if ( excluded.contains(testName)) { logger.info(" Not running: " + testName); continue; } List<String> result = runSingleBlockTest(testSuite, testName); if (!result.isEmpty()) summary.put(testName, false); else summary.put(testName, true); } logger.info(""); logger.info(""); logger.info("Summary: "); logger.info("========="); int fails = 0; int pass = 0; for (String key : summary.keySet()){ if (summary.get(key)) ++pass; else ++fails; String sumTest = String.format("%-60s:^%s", key, (summary.get(key) ? "OK" : "FAIL")). replace(' ', '.'). replace("^", " "); logger.info(sumTest); } logger.info(" - Total: Pass: {}, Failed: {} - ", pass, fails); Assert.assertTrue(fails == 0); } protected static void runGitHubJsonBlockTest(String json) throws ParseException, IOException { Set<String> excluded = new HashSet<>(); runGitHubJsonBlockTest(json, excluded); } private static List<String> runSingleBlockTest(BlockTestSuite testSuite, String testName){ BlockTestCase blockTestCase = testSuite.getTestCases().get(testName); TestRunner runner = new TestRunner(); logger.info("\n\n ***************** Running test: {} ***************************** \n\n", testName); List<String> result = runner.runTestCase(blockTestCase); logger.info("--------- POST Validation---------"); if (!result.isEmpty()) for (String single : result) logger.info(single); return result; } public static void runStateTest(String jsonSuite) throws IOException { runStateTest(jsonSuite, new HashSet<String>()); } public static void runStateTest(String jsonSuite, String testName) throws IOException { StateTestSuite stateTestSuite = new StateTestSuite(jsonSuite); Map<String, StateTestCase> testCases = stateTestSuite.getTestCases(); for (String testCase : testCases.keySet()) { if (testCase.equals(testName)) logger.info(" => " + testCase); else logger.info(" " + testCase); } StateTestCase testCase = testCases.get(testName); if (testCase != null){ String output = String.format("* running: %s *", testName); String line = output.replaceAll(".", "*"); logger.info(line); logger.info(output); logger.info(line); List<String> fails = StateTestRunner.run(testCases.get(testName)); Assert.assertTrue(fails.isEmpty()); } else { logger.error("Sorry test case doesn't exist: {}", testName); } } public static void runStateTest(String jsonSuite, Set<String> excluded) throws IOException { StateTestSuite stateTestSuite = new StateTestSuite(jsonSuite); Map<String, StateTestCase> testCases = stateTestSuite.getTestCases(); Map<String, Boolean> summary = new HashMap<>(); for (String testCase : testCases.keySet()) { if ( excluded.contains(testCase)) logger.info(" [X] " + testCase); else logger.info(" " + testCase); } Set<String> testNames = stateTestSuite.getTestCases().keySet(); for (String testName : testNames){ if (excluded.contains(testName)) continue; String output = String.format("* running: %s *", testName); String line = output.replaceAll(".", "*"); logger.info(line); logger.info(output); logger.info(line); List<String> result = StateTestRunner.run(testCases.get(testName)); if (!result.isEmpty()) summary.put(testName, false); else summary.put(testName, true); } logger.info("Summary: "); logger.info("========="); int fails = 0; int pass = 0; for (String key : summary.keySet()){ if (summary.get(key)) ++pass; else ++fails; String sumTest = String.format("%-60s:^%s", key, (summary.get(key) ? "OK" : "FAIL")). replace(' ', '.'). replace("^", " "); logger.info(sumTest); } logger.info(" - Total: Pass: {}, Failed: {} - ", pass, fails); Assert.assertTrue(fails == 0); } }
package com.lesliefish; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); BeanTest test = context.getBean(BeanTest.class); test.getMessage(); ((ClassPathXmlApplicationContext) context).registerShutdownHook(); } }
/** * Copyright (c) 2015-2017, Chill Zhuang 庄骞 (smallchill@163.com). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.stylefeng.guns.core.beetl; import com.stylefeng.guns.core.admin.Administrator; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.beetl.core.GroupTemplate; public class ShiroExt { private static final String NAMES_DELIMETER = ","; /** * 获取当前 Subject * * @return Subject */ protected static Subject getSubject() { return SecurityUtils.getSubject(); } /** * 获取封装的 ShiroUser * * @return ShiroUser */ public Administrator getUser() { if (isGuest()) { return null; } else { return (Administrator) getSubject().getPrincipals().getPrimaryPrincipal(); } } /** * 验证当前用户是否属于该角色?,使用时与lacksRole 搭配使用 * * @param roleName 角色名 * @return 属于该角色:true,否则false */ public boolean hasRole(String roleName) { return getSubject() != null && roleName != null && roleName.length() > 0 && getSubject().hasRole(roleName); } /** * 与hasRole标签逻辑相反,当用户不属于该角色时验证通过。 * * @param roleName 角色名 * @return 不属于该角色:true,否则false */ public boolean lacksRole(String roleName) { return !hasRole(roleName); } /** * 验证当前用户是否属于以下任意一个角色。 * * @param roleNames 角色列表 * @return 属于:true,否则false */ public boolean hasAnyRoles(String roleNames) { boolean hasAnyRole = false; Subject subject = getSubject(); if (subject != null && roleNames != null && roleNames.length() > 0) { for (String role : roleNames.split(NAMES_DELIMETER)) { if (subject.hasRole(role.trim())) { hasAnyRole = true; break; } } } return hasAnyRole; } /** * 验证当前用户是否属于以下所有角色。 * * @param roleNames 角色列表 * @return 属于:true,否则false */ public boolean hasAllRoles(String roleNames) { boolean hasAllRole = true; Subject subject = getSubject(); if (subject != null && roleNames != null && roleNames.length() > 0) { for (String role : roleNames.split(NAMES_DELIMETER)) { if (!subject.hasRole(role.trim())) { hasAllRole = false; break; } } } return hasAllRole; } /** * 验证当前用户是否拥有指定权限,使用时与lacksPermission 搭配使用 * * @param permission 权限名 * @return 拥有权限:true,否则false */ public boolean hasPermission(String permission) { return getSubject() != null && permission != null && permission.length() > 0 && getSubject().isPermitted(permission); } /** * 与hasPermission标签逻辑相反,当前用户没有制定权限时,验证通过。 * * @param permission 权限名 * @return 拥有权限:true,否则false */ public boolean lacksPermission(String permission) { return !hasPermission(permission); } /** * 已认证通过的用户。不包含已记住的用户,这是与user标签的区别所在。与notAuthenticated搭配使用 * * @return 通过身份验证:true,否则false */ public boolean authenticated() { return getSubject() != null && getSubject().isAuthenticated(); } /** * 未认证通过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户。。 * * @return 没有通过身份验证:true,否则false */ public boolean notAuthenticated() { return !authenticated(); } /** * 认证通过或已记住的用户。与guset搭配使用。 * * @return 用户:true,否则 false */ public boolean isUser() { return getSubject() != null && getSubject().getPrincipal() != null; } /** * 验证当前用户是否为“访客”,即未认证(包含未记住)的用户。用user搭配使用 * * @return 访客:true,否则false */ public boolean isGuest() { return !isUser(); } /** * 输出当前用户信息,通常为登录帐号信息。 * * @return 当前用户信息 */ public String principal() { if (getSubject() != null) { Object principal = getSubject().getPrincipal(); return principal.toString(); } return ""; } public static void main(String[] args) { GroupTemplate gt = new GroupTemplate(); gt.registerFunctionPackage("shiro", new ShiroExt()); } }
package com.ycsoft.business.dao.prod; import java.util.Collection; import java.util.List; import org.springframework.stereotype.Component; import com.ycsoft.beans.prod.PProdStaticRes; import com.ycsoft.commons.constants.SystemConstants; import com.ycsoft.daos.abstracts.BaseEntityDao; import com.ycsoft.daos.core.JDBCException; import com.ycsoft.sysmanager.dto.prod.ProdCountyResDto; @Component public class PProdStaticResDao extends BaseEntityDao<PProdStaticRes> { /** * @Description: * @date Jul 26, 2010 3:32:25 PM */ private static final long serialVersionUID = 6418745555748578784L; public PProdStaticResDao() {} public List<ProdCountyResDto> queryStaticResByprodId(String prodId) throws JDBCException { String sql = " select ? county_id,t2.res_name,t2.res_id from p_prod_static_res t1,p_res t2 where t1.res_id = t2.res_id and t1.prod_id = ? " + "union all " + "select t1.county_id county_id,t2.res_name,t2.res_id from P_PROD_COUNTY_RES t1,p_res t2 where t1.res_id = t2.res_id and t1.prod_id = ? "; return this.createQuery(ProdCountyResDto.class, sql,SystemConstants.COUNTY_ALL,prodId,prodId).list(); } public void deleteStatic (String prodId,List<String> list) throws Exception { String sql = "delete p_prod_static_res where prod_id = '"+prodId+"' and res_id = ? "; executeBatch(sql,list.toArray()); } public List<PProdStaticRes> queryBaseProdRes() throws JDBCException{ String sql = "select r.res_id from p_prod t,p_prod_static_res r where t.is_base =? and t.prod_id=r.prod_id"; return createQuery(sql,SystemConstants.BOOLEAN_TRUE).list(); } public String[] queryResByProdIds(Collection<String> prodIds) throws JDBCException{ String prodIdStr =""; for (String prodId:prodIds){ prodIdStr += ",'"+prodId+"'"; } prodIdStr = prodIdStr.substring(1); String sql = "select distinct b.external_res_id res_id from p_prod_static_res a,t_server_res b " + " where a.res_id=b.boss_res_id and a.prod_id in ("+prodIdStr+")"; List<PProdStaticRes> list = this.createQuery(sql).list(); String[] resIds = new String[list.size()]; int i=0; for(PProdStaticRes res:list){ resIds[i] = res.getRes_id(); i++; } return resIds; } public String[] queryExternalRes(String prodId) throws JDBCException{ String sql = "select distinct b.external_res_id res_id from p_prod_static_res a,t_server_res b " + " where a.res_id=b.boss_res_id and a.prod_id =? "; List<PProdStaticRes> list = this.createQuery(sql,prodId).list(); String[] resIds = new String[list.size()]; int i=0; for(PProdStaticRes res:list){ resIds[i] = res.getRes_id(); i++; } return resIds; } }
package com.ps.jms.config; import com.ps.jms.ConfirmationReceiver; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.listener.DefaultMessageListenerContainer; @Configuration @Import(JmsCommonConfig.class) public class JmsProducerConfig { private final JmsCommonConfig jmsCommonConfig; @Autowired public JmsProducerConfig(JmsCommonConfig jmsCommonConfig) { this.jmsCommonConfig = jmsCommonConfig; } @Bean public JmsTemplate jmsTemplate() { final JmsTemplate jmsTemplate = new JmsTemplate(); jmsTemplate.setConnectionFactory(jmsCommonConfig.connectionFactory()); jmsTemplate.setDefaultDestination(jmsCommonConfig.userQueue()); return jmsTemplate; } @Bean public ConfirmationReceiver confirmationReceiver() { return new ConfirmationReceiver(); } @Bean public DefaultMessageListenerContainer containerListener() { final DefaultMessageListenerContainer listener = new DefaultMessageListenerContainer(); listener.setConnectionFactory(jmsCommonConfig.connectionFactory()); listener.setDestination(jmsCommonConfig.confirmationQueue()); listener.setMessageListener(confirmationReceiver()); return listener; } }
package uristqwerty.CraftGuide.client.ui; import org.lwjgl.input.Keyboard; import uristqwerty.gui_craftguide.components.GuiElement; import java.util.HashMap; import java.util.Map; public class GuiScrollBar extends GuiElement implements IButtonListener, ISliderListener { private GuiSlider handle; private float min = 0, max = 1, value = 0; private static float scrollMultiplier = 1; private int pageSize; private Map<GuiElement, Object[]> buttons = new HashMap<GuiElement, Object[]>(); private int rowSize; public static interface ScrollBarAlignmentCallback { float alignScrollBar(GuiScrollBar guiScrollBar, float oldValue, float newValue); } private ScrollBarAlignmentCallback alignmentCallback; public GuiScrollBar(int x, int y, int width, int height, GuiSlider handle) { super(x, y, width, height); this.handle = handle; addElement(handle); handle.addSliderListener(this); } public GuiScrollBar addButton(GuiButton button, int scrollValue, boolean scrollPages) { addElement(button); button.addButtonListener(this); buttons.put(button, new Object[]{scrollValue, scrollPages}); return this; } public GuiElement setPageSize(int pageSize) { this.pageSize = pageSize; return this; } public GuiElement setRowSize(int rowSize) { this.rowSize = rowSize; return this; } public GuiScrollBar setScale(float min, float max) { float value = this.max > 0? (this.value - this.min) / (this.max - this.min) : 0; handle.setValue(0, value); this.min = min; this.max = max; this.value = (value * (max - min)) + min; return this; } public float getValue() { return value; } @Override public void onButtonEvent(GuiButton button, Event eventType) { if(eventType == Event.PRESS) { if(buttons.containsKey(button)) { Object[] data = buttons.get(button); if((Boolean)data[1]) { scrollPages((Integer)data[0]); } else { scrollLines((Integer)data[0]); } } } } @Override public void onKeyTyped(char eventChar, int eventKey) { super.onKeyTyped(eventChar, eventKey); switch(eventKey) { case Keyboard.KEY_UP: scrollLines(-1, true); break; case Keyboard.KEY_DOWN: scrollLines(1, true); break; case Keyboard.KEY_LEFT: case Keyboard.KEY_PRIOR: scrollPages(-1); break; case Keyboard.KEY_RIGHT: case Keyboard.KEY_NEXT: scrollPages(1); break; case Keyboard.KEY_HOME: scrollToStart(); break; case Keyboard.KEY_END: scrollToEnd(); break; } } @Override public void scrollWheelTurned(int change) { scrollLines(change, true); super.scrollWheelTurned(change); } public void scrollPages(int pages) { scrollPixels(pages * pageSize); } public void scrollLines(int lines) { scrollLines(lines, false); } public void scrollLines(int lines, boolean align) { if(align && alignmentCallback != null) { float newValue = value + lines * rowSize * scrollMultiplier; newValue = alignmentCallback.alignScrollBar(this, value, newValue); setValue(newValue); } else { scrollPixels(lines * rowSize); } } public void scrollPixels(int pixels) { setValue(value + pixels * scrollMultiplier); } public void scrollToStart() { setValue(min); } public void scrollToEnd() { setValue(max); } @Override public void onSliderMoved(GuiSlider slider) { setValue(slider.getPosY() * max + min); } private void setValue(float value) { if(value < min) { value = min; } if(value > max) { value = max; } this.value = value; handle.setValue(0, (value - min) / (max - min)); } public float getMax() { return max; } public static void setScrollMultiplier(int i) { scrollMultiplier = i; } public void setAlignmentCallback(ScrollBarAlignmentCallback alignmentCallback) { this.alignmentCallback = alignmentCallback; } }
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.keycloak.migration.migrators; import org.keycloak.component.ComponentModel; import org.keycloak.migration.ModelVersion; import org.keycloak.models.ImpersonationConstants; import org.keycloak.models.KeycloakSession; import org.keycloak.models.LDAPConstants; import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; import org.keycloak.models.cache.UserCache; import org.keycloak.models.utils.DefaultAuthenticationFlows; import org.keycloak.models.utils.DefaultRequiredActions; import org.keycloak.models.utils.KeycloakModelUtils; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.storage.UserStorageProviderModel; import java.util.Arrays; import java.util.List; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ public class MigrateTo1_4_0 implements Migration { public static final ModelVersion VERSION = new ModelVersion("1.4.0"); public ModelVersion getVersion() { return VERSION; } public void migrate(KeycloakSession session) { List<RealmModel> realms = session.realms().getRealms(); for (RealmModel realm : realms) { migrateRealm(session, realm); } } protected void migrateRealm(KeycloakSession session, RealmModel realm) { if (realm.getAuthenticationFlows().size() == 0) { DefaultAuthenticationFlows.migrateFlows(realm); DefaultRequiredActions.addActions(realm); } ImpersonationConstants.setupImpersonationService(session, realm); migrateLDAPMappers(session, realm); migrateUsers(session, realm); } @Override public void migrateImport(KeycloakSession session, RealmModel realm, RealmRepresentation rep, boolean skipUserDependent) { migrateRealm(session, realm); } private void migrateLDAPMappers(KeycloakSession session, RealmModel realm) { List<String> mandatoryInLdap = Arrays.asList("username", "username-cn", "first name", "last name"); for (UserStorageProviderModel providerModel : realm.getUserStorageProviders()) { if (providerModel.getProviderId().equals(LDAPConstants.LDAP_PROVIDER)) { List<ComponentModel> mappers = realm.getComponents(providerModel.getId()); for (ComponentModel mapper : mappers) { if (mandatoryInLdap.contains(mapper.getName())) { mapper = new ComponentModel(mapper); // don't want to modify cache mapper.getConfig().putSingle("is.mandatory.in.ldap", "true"); realm.updateComponent(mapper); } } } } } private void migrateUsers(KeycloakSession session, RealmModel realm) { List<UserModel> users = session.userLocalStorage().getUsers(realm, false); for (UserModel user : users) { String email = user.getEmail(); email = KeycloakModelUtils.toLowerCaseSafe(email); if (email != null && !email.equals(user.getEmail())) { user.setEmail(email); UserCache userCache = session.userCache(); if (userCache != null) { userCache.evict(realm, user); } } } } }
package Chapter1_4High; //Exercise 1.4.15 public class ThreeSumFaster { public int threeSumFaster(long[] a){ int cnt=0; int len=a.length; for(int j=0;j<len-2;j++){ for(int k=j+1,h=len-1;k<h;){ if(a[j]+a[k]+a[h]<0){ k++; }else if(a[j]+a[k]+a[h]>0){ h--; }else{ k++; h--; ++cnt; } } } return cnt; } }
/* * Copyright 2012-2022 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.context.config; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import org.apache.commons.logging.Log; import org.springframework.boot.BootstrapRegistry.InstanceSupplier; import org.springframework.boot.BootstrapRegistry.Scope; import org.springframework.boot.ConfigurableBootstrapContext; import org.springframework.boot.DefaultPropertiesPropertySource; import org.springframework.boot.context.config.ConfigDataEnvironmentContributors.BinderOption; import org.springframework.boot.context.properties.bind.BindException; import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; import org.springframework.boot.context.properties.bind.PlaceholdersResolver; import org.springframework.boot.context.properties.source.ConfigurationPropertySource; import org.springframework.boot.logging.DeferredLogFactory; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.log.LogMessage; import org.springframework.util.StringUtils; /** * Wrapper around a {@link ConfigurableEnvironment} that can be used to import and apply * {@link ConfigData}. Configures the initial set of * {@link ConfigDataEnvironmentContributors} by wrapping property sources from the Spring * {@link Environment} and adding the initial set of locations. * <p> * The initial locations can be influenced via the {@link #LOCATION_PROPERTY}, * {@value #ADDITIONAL_LOCATION_PROPERTY} and {@value #IMPORT_PROPERTY} properties. If no * explicit properties are set, the {@link #DEFAULT_SEARCH_LOCATIONS} will be used. * * @author Phillip Webb * @author Madhura Bhave */ class ConfigDataEnvironment { /** * Property used override the imported locations. */ static final String LOCATION_PROPERTY = "spring.config.location"; /** * Property used to provide additional locations to import. */ static final String ADDITIONAL_LOCATION_PROPERTY = "spring.config.additional-location"; /** * Property used to provide additional locations to import. */ static final String IMPORT_PROPERTY = "spring.config.import"; /** * Property used to determine what action to take when a * {@code ConfigDataNotFoundAction} is thrown. * @see ConfigDataNotFoundAction */ static final String ON_NOT_FOUND_PROPERTY = "spring.config.on-not-found"; /** * Default search locations used if not {@link #LOCATION_PROPERTY} is found. */ static final ConfigDataLocation[] DEFAULT_SEARCH_LOCATIONS; static { List<ConfigDataLocation> locations = new ArrayList<>(); locations.add(ConfigDataLocation.of("optional:classpath:/;optional:classpath:/config/")); locations.add(ConfigDataLocation.of("optional:file:./;optional:file:./config/;optional:file:./config/*/")); DEFAULT_SEARCH_LOCATIONS = locations.toArray(new ConfigDataLocation[0]); } private static final ConfigDataLocation[] EMPTY_LOCATIONS = new ConfigDataLocation[0]; private static final Bindable<ConfigDataLocation[]> CONFIG_DATA_LOCATION_ARRAY = Bindable .of(ConfigDataLocation[].class); private static final Bindable<List<String>> STRING_LIST = Bindable.listOf(String.class); private static final BinderOption[] ALLOW_INACTIVE_BINDING = {}; private static final BinderOption[] DENY_INACTIVE_BINDING = { BinderOption.FAIL_ON_BIND_TO_INACTIVE_SOURCE }; private final DeferredLogFactory logFactory; private final Log logger; private final ConfigDataNotFoundAction notFoundAction; private final ConfigurableBootstrapContext bootstrapContext; private final ConfigurableEnvironment environment; private final ConfigDataLocationResolvers resolvers; private final Collection<String> additionalProfiles; private final ConfigDataEnvironmentUpdateListener environmentUpdateListener; private final ConfigDataLoaders loaders; private final ConfigDataEnvironmentContributors contributors; /** * Create a new {@link ConfigDataEnvironment} instance. * @param logFactory the deferred log factory * @param bootstrapContext the bootstrap context * @param environment the Spring {@link Environment}. * @param resourceLoader {@link ResourceLoader} to load resource locations * @param additionalProfiles any additional profiles to activate * @param environmentUpdateListener optional * {@link ConfigDataEnvironmentUpdateListener} that can be used to track * {@link Environment} updates. */ ConfigDataEnvironment(DeferredLogFactory logFactory, ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment, ResourceLoader resourceLoader, Collection<String> additionalProfiles, ConfigDataEnvironmentUpdateListener environmentUpdateListener) { Binder binder = Binder.get(environment); UseLegacyConfigProcessingException.throwIfRequested(binder); this.logFactory = logFactory; this.logger = logFactory.getLog(getClass()); this.notFoundAction = binder.bind(ON_NOT_FOUND_PROPERTY, ConfigDataNotFoundAction.class) .orElse(ConfigDataNotFoundAction.FAIL); this.bootstrapContext = bootstrapContext; this.environment = environment; this.resolvers = createConfigDataLocationResolvers(logFactory, bootstrapContext, binder, resourceLoader); this.additionalProfiles = additionalProfiles; this.environmentUpdateListener = (environmentUpdateListener != null) ? environmentUpdateListener : ConfigDataEnvironmentUpdateListener.NONE; this.loaders = new ConfigDataLoaders(logFactory, bootstrapContext, resourceLoader.getClassLoader()); this.contributors = createContributors(binder); } protected ConfigDataLocationResolvers createConfigDataLocationResolvers(DeferredLogFactory logFactory, ConfigurableBootstrapContext bootstrapContext, Binder binder, ResourceLoader resourceLoader) { return new ConfigDataLocationResolvers(logFactory, bootstrapContext, binder, resourceLoader); } private ConfigDataEnvironmentContributors createContributors(Binder binder) { this.logger.trace("Building config data environment contributors"); MutablePropertySources propertySources = this.environment.getPropertySources(); List<ConfigDataEnvironmentContributor> contributors = new ArrayList<>(propertySources.size() + 10); PropertySource<?> defaultPropertySource = null; for (PropertySource<?> propertySource : propertySources) { if (DefaultPropertiesPropertySource.hasMatchingName(propertySource)) { defaultPropertySource = propertySource; } else { this.logger.trace(LogMessage.format("Creating wrapped config data contributor for '%s'", propertySource.getName())); contributors.add(ConfigDataEnvironmentContributor.ofExisting(propertySource)); } } contributors.addAll(getInitialImportContributors(binder)); if (defaultPropertySource != null) { this.logger.trace("Creating wrapped config data contributor for default property source"); contributors.add(ConfigDataEnvironmentContributor.ofExisting(defaultPropertySource)); } return createContributors(contributors); } protected ConfigDataEnvironmentContributors createContributors( List<ConfigDataEnvironmentContributor> contributors) { return new ConfigDataEnvironmentContributors(this.logFactory, this.bootstrapContext, contributors); } ConfigDataEnvironmentContributors getContributors() { return this.contributors; } private List<ConfigDataEnvironmentContributor> getInitialImportContributors(Binder binder) { List<ConfigDataEnvironmentContributor> initialContributors = new ArrayList<>(); addInitialImportContributors(initialContributors, bindLocations(binder, IMPORT_PROPERTY, EMPTY_LOCATIONS)); addInitialImportContributors(initialContributors, bindLocations(binder, ADDITIONAL_LOCATION_PROPERTY, EMPTY_LOCATIONS)); addInitialImportContributors(initialContributors, bindLocations(binder, LOCATION_PROPERTY, DEFAULT_SEARCH_LOCATIONS)); return initialContributors; } private ConfigDataLocation[] bindLocations(Binder binder, String propertyName, ConfigDataLocation[] other) { return binder.bind(propertyName, CONFIG_DATA_LOCATION_ARRAY).orElse(other); } private void addInitialImportContributors(List<ConfigDataEnvironmentContributor> initialContributors, ConfigDataLocation[] locations) { for (int i = locations.length - 1; i >= 0; i--) { initialContributors.add(createInitialImportContributor(locations[i])); } } private ConfigDataEnvironmentContributor createInitialImportContributor(ConfigDataLocation location) { this.logger.trace(LogMessage.format("Adding initial config data import from location '%s'", location)); return ConfigDataEnvironmentContributor.ofInitialImport(location); } /** * Process all contributions and apply any newly imported property sources to the * {@link Environment}. */ void processAndApply() { ConfigDataImporter importer = new ConfigDataImporter(this.logFactory, this.notFoundAction, this.resolvers, this.loaders); registerBootstrapBinder(this.contributors, null, DENY_INACTIVE_BINDING); ConfigDataEnvironmentContributors contributors = processInitial(this.contributors, importer); ConfigDataActivationContext activationContext = createActivationContext( contributors.getBinder(null, BinderOption.FAIL_ON_BIND_TO_INACTIVE_SOURCE)); contributors = processWithoutProfiles(contributors, importer, activationContext); activationContext = withProfiles(contributors, activationContext); contributors = processWithProfiles(contributors, importer, activationContext); applyToEnvironment(contributors, activationContext, importer.getLoadedLocations(), importer.getOptionalLocations()); } private ConfigDataEnvironmentContributors processInitial(ConfigDataEnvironmentContributors contributors, ConfigDataImporter importer) { this.logger.trace("Processing initial config data environment contributors without activation context"); contributors = contributors.withProcessedImports(importer, null); registerBootstrapBinder(contributors, null, DENY_INACTIVE_BINDING); return contributors; } private ConfigDataActivationContext createActivationContext(Binder initialBinder) { this.logger.trace("Creating config data activation context from initial contributions"); try { return new ConfigDataActivationContext(this.environment, initialBinder); } catch (BindException ex) { if (ex.getCause() instanceof InactiveConfigDataAccessException) { throw (InactiveConfigDataAccessException) ex.getCause(); } throw ex; } } private ConfigDataEnvironmentContributors processWithoutProfiles(ConfigDataEnvironmentContributors contributors, ConfigDataImporter importer, ConfigDataActivationContext activationContext) { this.logger.trace("Processing config data environment contributors with initial activation context"); contributors = contributors.withProcessedImports(importer, activationContext); registerBootstrapBinder(contributors, activationContext, DENY_INACTIVE_BINDING); return contributors; } private ConfigDataActivationContext withProfiles(ConfigDataEnvironmentContributors contributors, ConfigDataActivationContext activationContext) { this.logger.trace("Deducing profiles from current config data environment contributors"); Binder binder = contributors.getBinder(activationContext, (contributor) -> !contributor.hasConfigDataOption(ConfigData.Option.IGNORE_PROFILES), BinderOption.FAIL_ON_BIND_TO_INACTIVE_SOURCE); try { Set<String> additionalProfiles = new LinkedHashSet<>(this.additionalProfiles); additionalProfiles.addAll(getIncludedProfiles(contributors, activationContext)); Profiles profiles = new Profiles(this.environment, binder, additionalProfiles); return activationContext.withProfiles(profiles); } catch (BindException ex) { if (ex.getCause() instanceof InactiveConfigDataAccessException) { throw (InactiveConfigDataAccessException) ex.getCause(); } throw ex; } } private Collection<? extends String> getIncludedProfiles(ConfigDataEnvironmentContributors contributors, ConfigDataActivationContext activationContext) { PlaceholdersResolver placeholdersResolver = new ConfigDataEnvironmentContributorPlaceholdersResolver( contributors, activationContext, null, true); Set<String> result = new LinkedHashSet<>(); for (ConfigDataEnvironmentContributor contributor : contributors) { ConfigurationPropertySource source = contributor.getConfigurationPropertySource(); if (source != null && !contributor.hasConfigDataOption(ConfigData.Option.IGNORE_PROFILES)) { Binder binder = new Binder(Collections.singleton(source), placeholdersResolver); binder.bind(Profiles.INCLUDE_PROFILES, STRING_LIST).ifBound((includes) -> { if (!contributor.isActive(activationContext)) { InactiveConfigDataAccessException.throwIfPropertyFound(contributor, Profiles.INCLUDE_PROFILES); InactiveConfigDataAccessException.throwIfPropertyFound(contributor, Profiles.INCLUDE_PROFILES.append("[0]")); } result.addAll(includes); }); } } return result; } private ConfigDataEnvironmentContributors processWithProfiles(ConfigDataEnvironmentContributors contributors, ConfigDataImporter importer, ConfigDataActivationContext activationContext) { this.logger.trace("Processing config data environment contributors with profile activation context"); contributors = contributors.withProcessedImports(importer, activationContext); registerBootstrapBinder(contributors, activationContext, ALLOW_INACTIVE_BINDING); return contributors; } private void registerBootstrapBinder(ConfigDataEnvironmentContributors contributors, ConfigDataActivationContext activationContext, BinderOption... binderOptions) { this.bootstrapContext.register(Binder.class, InstanceSupplier .from(() -> contributors.getBinder(activationContext, binderOptions)).withScope(Scope.PROTOTYPE)); } private void applyToEnvironment(ConfigDataEnvironmentContributors contributors, ConfigDataActivationContext activationContext, Set<ConfigDataLocation> loadedLocations, Set<ConfigDataLocation> optionalLocations) { checkForInvalidProperties(contributors); checkMandatoryLocations(contributors, activationContext, loadedLocations, optionalLocations); MutablePropertySources propertySources = this.environment.getPropertySources(); applyContributor(contributors, activationContext, propertySources); DefaultPropertiesPropertySource.moveToEnd(propertySources); Profiles profiles = activationContext.getProfiles(); this.logger.trace(LogMessage.format("Setting default profiles: %s", profiles.getDefault())); this.environment.setDefaultProfiles(StringUtils.toStringArray(profiles.getDefault())); this.logger.trace(LogMessage.format("Setting active profiles: %s", profiles.getActive())); this.environment.setActiveProfiles(StringUtils.toStringArray(profiles.getActive())); this.environmentUpdateListener.onSetProfiles(profiles); } private void applyContributor(ConfigDataEnvironmentContributors contributors, ConfigDataActivationContext activationContext, MutablePropertySources propertySources) { this.logger.trace("Applying config data environment contributions"); for (ConfigDataEnvironmentContributor contributor : contributors) { PropertySource<?> propertySource = contributor.getPropertySource(); if (contributor.getKind() == ConfigDataEnvironmentContributor.Kind.BOUND_IMPORT && propertySource != null) { if (!contributor.isActive(activationContext)) { this.logger.trace( LogMessage.format("Skipping inactive property source '%s'", propertySource.getName())); } else { this.logger .trace(LogMessage.format("Adding imported property source '%s'", propertySource.getName())); propertySources.addLast(propertySource); this.environmentUpdateListener.onPropertySourceAdded(propertySource, contributor.getLocation(), contributor.getResource()); } } } } private void checkForInvalidProperties(ConfigDataEnvironmentContributors contributors) { for (ConfigDataEnvironmentContributor contributor : contributors) { InvalidConfigDataPropertyException.throwOrWarn(this.logger, contributor); } } private void checkMandatoryLocations(ConfigDataEnvironmentContributors contributors, ConfigDataActivationContext activationContext, Set<ConfigDataLocation> loadedLocations, Set<ConfigDataLocation> optionalLocations) { Set<ConfigDataLocation> mandatoryLocations = new LinkedHashSet<>(); for (ConfigDataEnvironmentContributor contributor : contributors) { if (contributor.isActive(activationContext)) { mandatoryLocations.addAll(getMandatoryImports(contributor)); } } for (ConfigDataEnvironmentContributor contributor : contributors) { if (contributor.getLocation() != null) { mandatoryLocations.remove(contributor.getLocation()); } } mandatoryLocations.removeAll(loadedLocations); mandatoryLocations.removeAll(optionalLocations); if (!mandatoryLocations.isEmpty()) { for (ConfigDataLocation mandatoryLocation : mandatoryLocations) { this.notFoundAction.handle(this.logger, new ConfigDataLocationNotFoundException(mandatoryLocation)); } } } private Set<ConfigDataLocation> getMandatoryImports(ConfigDataEnvironmentContributor contributor) { List<ConfigDataLocation> imports = contributor.getImports(); Set<ConfigDataLocation> mandatoryLocations = new LinkedHashSet<>(imports.size()); for (ConfigDataLocation location : imports) { if (!location.isOptional()) { mandatoryLocations.add(location); } } return mandatoryLocations; } }
// Copyright 2013 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; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.HeaderViewListAdapter; import android.widget.ListPopupWindow; import android.widget.PopupWindow; import android.widget.TextView; import org.chromium.base.CalledByNative; import org.chromium.base.ThreadUtils; import org.chromium.content.browser.NavigationClient; import org.chromium.content_public.browser.NavigationEntry; import org.chromium.content_public.browser.NavigationHistory; import org.chromium.ui.base.LocalizationUtils; import java.util.HashSet; import java.util.Set; /** * A popup that handles displaying the navigation history for a given tab. */ public class NavigationPopup extends ListPopupWindow implements AdapterView.OnItemClickListener { private static final int FAVICON_SIZE_DP = 16; private static final int MAXIMUM_HISTORY_ITEMS = 8; private final Context mContext; private final NavigationClient mNavigationClient; private final NavigationHistory mHistory; private final NavigationAdapter mAdapter; private final ListItemFactory mListItemFactory; private final int mFaviconSize; private long mNativeNavigationPopup; /** * Constructs a new popup with the given history information. * * @param context The context used for building the popup. * @param navigationClient The owner of the history being displayed. * @param isForward Whether to request forward navigation entries. */ public NavigationPopup( Context context, NavigationClient navigationClient, boolean isForward) { super(context, null, android.R.attr.popupMenuStyle); mContext = context; mNavigationClient = navigationClient; mHistory = mNavigationClient.getDirectedNavigationHistory( isForward, MAXIMUM_HISTORY_ITEMS); mAdapter = new NavigationAdapter(); float density = mContext.getResources().getDisplayMetrics().density; mFaviconSize = (int) (density * FAVICON_SIZE_DP); setModal(true); setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED); setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); setOnItemClickListener(this); setAdapter(new HeaderViewListAdapter(null, null, mAdapter)); mListItemFactory = new ListItemFactory(context); } /** * @return Whether a navigation popup is valid for the given page. */ public boolean shouldBeShown() { return mHistory.getEntryCount() > 0; } @Override public void show() { if (mNativeNavigationPopup == 0) initializeNative(); super.show(); } @Override public void dismiss() { if (mNativeNavigationPopup != 0) { nativeDestroy(mNativeNavigationPopup); mNativeNavigationPopup = 0; } super.dismiss(); } private void initializeNative() { ThreadUtils.assertOnUiThread(); mNativeNavigationPopup = nativeInit(); Set<String> requestedUrls = new HashSet<String>(); for (int i = 0; i < mHistory.getEntryCount(); i++) { NavigationEntry entry = mHistory.getEntryAtIndex(i); if (entry.getFavicon() != null) continue; String url = entry.getUrl(); if (!requestedUrls.contains(url)) { nativeFetchFaviconForUrl(mNativeNavigationPopup, url); requestedUrls.add(url); } } nativeFetchFaviconForUrl(mNativeNavigationPopup, nativeGetHistoryUrl()); } @CalledByNative private void onFaviconUpdated(String url, Object favicon) { for (int i = 0; i < mHistory.getEntryCount(); i++) { NavigationEntry entry = mHistory.getEntryAtIndex(i); if (TextUtils.equals(url, entry.getUrl())) entry.updateFavicon((Bitmap) favicon); } mAdapter.notifyDataSetChanged(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { NavigationEntry entry = (NavigationEntry) parent.getItemAtPosition(position); mNavigationClient.goToNavigationIndex(entry.getIndex()); dismiss(); } private void updateBitmapForTextView(TextView view, Bitmap bitmap) { Drawable faviconDrawable = null; if (bitmap != null) { faviconDrawable = new BitmapDrawable(mContext.getResources(), bitmap); ((BitmapDrawable) faviconDrawable).setGravity(Gravity.FILL); } else { faviconDrawable = new ColorDrawable(Color.TRANSPARENT); } faviconDrawable.setBounds(0, 0, mFaviconSize, mFaviconSize); view.setCompoundDrawables(faviconDrawable, null, null, null); } private static class ListItemFactory { private static final int LIST_ITEM_HEIGHT_DP = 48; private static final int PADDING_DP = 8; private static final int TEXT_SIZE_SP = 18; private static final float FADE_LENGTH_DP = 25.0f; private static final float FADE_STOP = 0.75f; int mFadeEdgeLength; int mFadePadding; int mListItemHeight; int mPadding; boolean mIsLayoutDirectionRTL; Context mContext; public ListItemFactory(Context context) { mContext = context; computeFadeDimensions(); } private void computeFadeDimensions() { // Fade with linear gradient starting 25dp from right margin. // Reaches 0% opacity at 75% length. (Simulated with extra padding) float density = mContext.getResources().getDisplayMetrics().density; float fadeLength = (FADE_LENGTH_DP * density); mFadeEdgeLength = (int) (fadeLength * FADE_STOP); mFadePadding = (int) (fadeLength * (1 - FADE_STOP)); mListItemHeight = (int) (density * LIST_ITEM_HEIGHT_DP); mPadding = (int) (density * PADDING_DP); mIsLayoutDirectionRTL = LocalizationUtils.isLayoutRtl(); } public TextView createListItem() { TextView view = new TextView(mContext); view.setFadingEdgeLength(mFadeEdgeLength); view.setHorizontalFadingEdgeEnabled(true); view.setSingleLine(); view.setTextSize(TEXT_SIZE_SP); view.setMinimumHeight(mListItemHeight); view.setGravity(Gravity.CENTER_VERTICAL); view.setCompoundDrawablePadding(mPadding); if (!mIsLayoutDirectionRTL) { view.setPadding(mPadding, 0, mPadding + mFadePadding , 0); } else { view.setPadding(mPadding + mFadePadding, 0, mPadding, 0); } return view; } } private class NavigationAdapter extends BaseAdapter { @Override public int getCount() { return mHistory.getEntryCount(); } @Override public Object getItem(int position) { return mHistory.getEntryAtIndex(position); } @Override public long getItemId(int position) { return ((NavigationEntry) getItem(position)).getIndex(); } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view; if (convertView != null && convertView instanceof TextView) { view = (TextView) convertView; } else { view = mListItemFactory.createListItem(); } NavigationEntry entry = (NavigationEntry) getItem(position); String entryText = entry.getTitle(); if (TextUtils.isEmpty(entryText)) entryText = entry.getVirtualUrl(); if (TextUtils.isEmpty(entryText)) entryText = entry.getUrl(); view.setText(entryText); updateBitmapForTextView(view, entry.getFavicon()); return view; } } private static native String nativeGetHistoryUrl(); private native long nativeInit(); private native void nativeDestroy(long nativeNavigationPopup); private native void nativeFetchFaviconForUrl(long nativeNavigationPopup, String url); }
/* * 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.ambari.server.controller; public class RepositoryResponse { private String stackName; private String stackVersion; private String baseUrl; private String osType; private String repoId; private String repoName; private String mirrorsList; private String defaultBaseUrl; private Long repositoryVersionId; private String versionDefinitionId; private Long clusterVersionId; private boolean unique; public RepositoryResponse(String baseUrl, String osType, String repoId, String repoName, String mirrorsList, String defaultBaseUrl) { setBaseUrl(baseUrl); setOsType(osType); setRepoId(repoId); setRepoName(repoName); setMirrorsList(mirrorsList); setDefaultBaseUrl(defaultBaseUrl); } public String getStackName() { return stackName; } public void setStackName(String stackName) { this.stackName = stackName; } public String getStackVersion() { return stackVersion; } public void setStackVersion(String stackVersion) { this.stackVersion = stackVersion; } public String getBaseUrl() { return baseUrl; } public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } public String getOsType() { return osType; } public void setOsType(String osType) { this.osType = osType; } public String getRepoId() { return repoId; } public void setRepoId(String repoId) { this.repoId = repoId; } public String getRepoName() { return repoName; } public void setRepoName(String repoName) { this.repoName = repoName; } public String getMirrorsList() { return mirrorsList; } public void setMirrorsList(String mirrorsList) { this.mirrorsList = mirrorsList; } public String getDefaultBaseUrl() { return defaultBaseUrl; } public void setDefaultBaseUrl(String url) { this.defaultBaseUrl = url; } public Long getRepositoryVersionId() { return repositoryVersionId; } public void setRepositoryVersionId(Long repositoryVersionId) { this.repositoryVersionId = repositoryVersionId; } /** * @param id the version definition id */ public void setVersionDefinitionId(String id) { versionDefinitionId = id; } /** * @return the version definition id */ public String getVersionDefinitionId() { return versionDefinitionId; } /** * @param id the cluster version id for the response */ public void setClusterVersionId(Long id) { clusterVersionId = id; } /** * @return the cluster version id for the response */ public Long getClusterVersionId() { return clusterVersionId; } public boolean isUnique() { return unique; } public void setUnique(boolean unique) { this.unique = unique; } }
/* * Copyright 2020 ChenJun (power4j@outlook.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.power4j.ji.admin.modules.social.common.constant; import com.power4j.ji.common.security.social.SocialConstant; import com.power4j.kit.common.data.dict.annotation.DictValue; import com.power4j.kit.common.data.dict.annotation.Label; import com.power4j.kit.common.data.dict.annotation.MapDict; import java.util.function.Function; /** * @author CJ (power4j@outlook.com) * @date 2021/9/1 * @since 1.0 */ @MapDict(code = "social_type_flags", name = "社交账号类型") public enum SocialTypeEnum { /** * 微信小程序 */ @Label("微信小程序") WX_MA(SocialConstant.SOCIAL_KEY_WX_MINI_APP); @DictValue private final String value; SocialTypeEnum(String value) { this.value = value; } public String getValue() { return value; } /** * 解析 * @param value 被解析的数据,可以是null * @param defValue 默认值 * @return 如果解析失败返回默认值 */ public static SocialTypeEnum parseOrDefault(final String value, final SocialTypeEnum defValue) { if (value == null) { return defValue; } for (SocialTypeEnum o : SocialTypeEnum.values()) { if (o.getValue().equals(value)) { return o; } } return defValue; } /** * 解析 * @param value 被解析的数据 * @return 如果解析失败返回 null */ public static SocialTypeEnum parseOrNull(final String value) { return parseOrDefault(value, null); } /** * 解析 * @param value 被解析的数据 * @param thrower 异常抛出器 * @return 如果解析失败抛出异常 */ public static SocialTypeEnum parseOrThrow(final String value, Function<String, RuntimeException> thrower) { SocialTypeEnum o = parseOrDefault(value, null); if (o == null) { throw thrower.apply(value); } return o; } /** * 解析 * @param value 被解析的数据 * @return 如果解析失败抛出 IllegalArgumentException */ public static SocialTypeEnum parse(final String value) throws IllegalArgumentException { return parseOrThrow(value, (v) -> new IllegalArgumentException("Invalid value : " + v)); } }
package src.CountAndSay; /** * @author mingqiao * @Date 2019/8/18 */ public class CountAndSay { /** * 读懂题意后,模拟就行了注意边界 * @param n * @return */ public String countAndSay(int n) { if (n == 1) { return "1"; } int count = 1; StringBuilder ans = new StringBuilder(); String prefix = countAndSay(n - 1) + '#'; for (int i = 0; i < prefix.length() - 1; i++) { if (prefix.charAt(i) == prefix.charAt(i + 1)) { count++; } else { ans.append(count); ans.append(prefix.charAt(i)); count = 1; } } return ans.toString(); } }
/* * Copyright 2015 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.compiler.integrationtests; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.TimeUnit; import org.drools.compiler.Address; import org.drools.compiler.Cheese; import org.drools.compiler.Cheesery; import org.drools.core.ClockType; import org.drools.compiler.CommonTestMethodBase; import org.drools.compiler.FactA; import org.drools.compiler.FactB; import org.drools.compiler.FactC; import org.kie.api.runtime.rule.FactHandle; import org.drools.compiler.Message; import org.drools.compiler.Order; import org.drools.compiler.OrderItem; import org.drools.compiler.Person; import org.drools.compiler.PersonInterface; import org.drools.compiler.SpecialString; import org.drools.compiler.State; import org.drools.compiler.StockTick; import org.drools.compiler.Triangle; import org.drools.core.audit.WorkingMemoryConsoleLogger; import org.drools.core.time.SessionPseudoClock; import org.junit.Test; import org.kie.api.KieBase; import org.kie.api.KieBaseConfiguration; import org.kie.api.conf.RemoveIdentitiesOption; import org.kie.internal.KnowledgeBase; import org.kie.internal.KnowledgeBaseFactory; import org.kie.internal.builder.KnowledgeBuilder; import org.kie.internal.builder.KnowledgeBuilderFactory; import org.kie.internal.definition.KnowledgePackage; import org.kie.api.event.rule.AfterMatchFiredEvent; import org.kie.api.event.rule.AgendaEventListener; import org.kie.internal.io.ResourceFactory; import org.kie.internal.runtime.StatefulKnowledgeSession; import org.kie.api.io.ResourceType; import org.kie.api.runtime.KieSessionConfiguration; import org.kie.api.runtime.conf.ClockTypeOption; import org.kie.api.time.SessionClock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FirstOrderLogicTest extends CommonTestMethodBase { private static Logger logger = LoggerFactory.getLogger(FirstOrderLogicTest.class); protected StatefulKnowledgeSession createKnowledgeSession(KnowledgeBase kbase) { return kbase.newStatefulKnowledgeSession(); } @Test public void testCollect() throws Exception { List results = new ArrayList(); KieBase kbase = loadKnowledgeBase("test_Collect.drl"); StatefulKnowledgeSession wm = createKnowledgeSession((KnowledgeBase) kbase); wm.setGlobal( "results", results ); wm.insert( new Cheese( "stilton", 10 ) ); wm.insert( new Cheese( "stilton", 7 ) ); wm.insert( new Cheese( "stilton", 8 ) ); wm.insert( new Cheese( "brie", 5 ) ); wm.insert( new Cheese( "provolone", 150 ) ); wm = SerializationHelper.getSerialisedStatefulKnowledgeSession(wm, true); results = (List) wm.getGlobal( "results" ); wm.insert( new Cheese( "provolone", 20 ) ); wm.insert( new Person( "Bob", "stilton" ) ); wm.insert( new Person( "Mark", "provolone" ) ); wm = SerializationHelper.getSerialisedStatefulKnowledgeSession(wm, true); results = (List) wm.getGlobal( "results" ); wm.fireAllRules(); wm = SerializationHelper.getSerialisedStatefulKnowledgeSession(wm, true); results = (List) wm.getGlobal( "results" ); assertEquals( 1, results.size() ); assertEquals( 3, ((Collection) results.get( 0 )).size() ); assertEquals( ArrayList.class.getName(), results.get( 0 ).getClass().getName() ); } @Test public void testCollectNodeSharing() throws Exception { KieBase kbase = loadKnowledgeBase("test_collectNodeSharing.drl"); StatefulKnowledgeSession wm = createKnowledgeSession((KnowledgeBase) kbase); List results = new ArrayList(); wm.setGlobal( "results", results ); wm = SerializationHelper.getSerialisedStatefulKnowledgeSession(wm, true); results = (List) wm.getGlobal( "results" ); wm.insert( new Cheese( "stilton", 10 ) ); wm = SerializationHelper.getSerialisedStatefulKnowledgeSession(wm, true); results = (List) wm.getGlobal( "results" ); wm.insert( new Cheese( "brie", 15 ) ); wm.fireAllRules(); wm = SerializationHelper.getSerialisedStatefulKnowledgeSession(wm, true); results = (List) wm.getGlobal( "results" ); assertEquals( 1, results.size() ); assertEquals( 2, ((List) results.get( 0 )).size() ); } @Test public void testCollectModify() throws Exception { KieBase kbase = loadKnowledgeBase("test_Collect.drl"); StatefulKnowledgeSession wm = createKnowledgeSession((KnowledgeBase) kbase); List results = new ArrayList(); wm.setGlobal( "results", results ); final Cheese[] cheese = new Cheese[]{new Cheese( "stilton", 10 ), new Cheese( "stilton", 2 ), new Cheese( "stilton", 5 ), new Cheese( "brie", 15 ), new Cheese( "brie", 16 ), new Cheese( "provolone", 8 )}; final Person bob = new Person( "Bob", "stilton" ); final FactHandle[] cheeseHandles = new FactHandle[cheese.length]; for ( int i = 0; i < cheese.length; i++ ) { cheeseHandles[i] = (FactHandle) wm.insert( cheese[i] ); } final FactHandle bobHandle = (FactHandle) wm.insert( bob ); // ---------------- 1st scenario int fireCount = 0; wm.fireAllRules(); assertEquals( ++fireCount, results.size() ); assertEquals( 3, ((Collection) results.get( fireCount - 1 )).size() ); assertEquals( ArrayList.class.getName(), results.get( fireCount - 1 ).getClass().getName() ); // ---------------- 2nd scenario final int index = 1; cheese[index].setPrice( 9 ); wm.update( cheeseHandles[index], cheese[index] ); wm.fireAllRules(); assertEquals( ++fireCount, results.size() ); assertEquals( 3, ((Collection) results.get( fireCount - 1 )).size() ); assertEquals( ArrayList.class.getName(), results.get( fireCount - 1 ).getClass().getName() ); // ---------------- 3rd scenario bob.setLikes( "brie" ); wm.update( bobHandle, bob ); wm.fireAllRules(); assertEquals( fireCount, results.size() ); // ---------------- 4th scenario wm.retract( cheeseHandles[3] ); wm.fireAllRules(); // should not have fired as per constraint assertEquals( fireCount, results.size() ); } @Test public void testCollectResultConstraints() throws Exception { KieBase kbase = loadKnowledgeBase("test_CollectResultConstraints.drl"); StatefulKnowledgeSession wm = createKnowledgeSession((KnowledgeBase) kbase); List results = new ArrayList(); wm.setGlobal( "results", results ); wm.insert( new Cheese( "stilton", 10 ) ); wm = SerializationHelper.getSerialisedStatefulKnowledgeSession(wm, true); results = (List) wm.getGlobal( "results" ); wm.fireAllRules(); assertEquals( 1, results.size() ); assertEquals( 1, ((Collection) results.get( 0 )).size() ); wm.insert( new Cheese( "stilton", 7 ) ); wm.insert( new Cheese( "stilton", 8 ) ); wm.fireAllRules(); wm = SerializationHelper.getSerialisedStatefulKnowledgeSession(wm, true); results = (List) wm.getGlobal( "results" ); assertEquals( 1, results.size() ); // It's 3 as while the rule does not fire, it does continue to evaluate and update the collection assertEquals( 3, ((Collection) results.get( 0 )).size() ); assertEquals( ArrayList.class.getName(), results.get( 0 ).getClass().getName() ); } @Test public void testExistsWithBinding() throws Exception { KieBase kbase = loadKnowledgeBase("test_ExistsWithBindings.drl"); StatefulKnowledgeSession wm = createKnowledgeSession((KnowledgeBase) kbase); final List list = new ArrayList(); wm.setGlobal( "results", list ); final Cheese c = new Cheese( "stilton", 10 ); final Person p = new Person( "Mark", "stilton" ); wm.insert( c ); wm.insert( p ); wm.fireAllRules(); assertTrue( list.contains( c.getType() ) ); assertEquals( 1, list.size() ); } @Test public void testNot() throws Exception { KieBase kbase = loadKnowledgeBase("not_rule_test.drl"); StatefulKnowledgeSession wm = createKnowledgeSession((KnowledgeBase) kbase); final List list = new ArrayList(); wm.setGlobal( "list", list ); final Cheese stilton = new Cheese( "stilton", 5 ); final FactHandle stiltonHandle = (FactHandle) wm.insert( stilton ); final Cheese cheddar = new Cheese( "cheddar", 7 ); final FactHandle cheddarHandle = (FactHandle) wm.insert( cheddar ); wm.fireAllRules(); assertEquals( 0, list.size() ); wm.retract( stiltonHandle ); wm.fireAllRules(); assertEquals( 4, list.size() ); assertTrue( list.contains( new Integer( 5 ) ) ); assertTrue( list.contains( new Integer( 6 ) ) ); assertTrue( list.contains( new Integer( 7 ) ) ); assertTrue( list.contains( new Integer( 8 ) ) ); } @Test public void testNotWithBindings() throws Exception { KieBase kbase = loadKnowledgeBase("not_with_bindings_rule_test.drl"); StatefulKnowledgeSession wm = createKnowledgeSession((KnowledgeBase) kbase); final List list = new ArrayList(); wm.setGlobal( "list", list ); final Cheese stilton = new Cheese( "stilton", 5 ); final FactHandle stiltonHandle = (FactHandle) wm.insert( stilton ); final Cheese cheddar = new Cheese( "cheddar", 7 ); final FactHandle cheddarHandle = (FactHandle) wm.insert( cheddar ); final PersonInterface paul = new Person( "paul", "stilton", 12 ); wm.insert( paul ); wm.fireAllRules(); assertEquals( 0, list.size() ); wm.retract( stiltonHandle ); wm.fireAllRules(); assertEquals( 1, list.size() ); } @Test public void testExists() throws Exception { KieBase kbase = loadKnowledgeBase("exists_rule_test.drl"); StatefulKnowledgeSession wm = createKnowledgeSession((KnowledgeBase) kbase); final List list = new ArrayList(); wm.setGlobal( "list", list ); final Cheese cheddar = new Cheese( "cheddar", 7 ); final FactHandle cheddarHandle = (FactHandle) wm.insert( cheddar ); wm.fireAllRules(); assertEquals( 0, list.size() ); final Cheese stilton = new Cheese( "stilton", 5 ); final FactHandle stiltonHandle = (FactHandle) wm.insert( stilton ); wm.fireAllRules(); assertEquals( 1, list.size() ); final Cheese brie = new Cheese( "brie", 5 ); final FactHandle brieHandle = (FactHandle) wm.insert( brie ); wm.fireAllRules(); assertEquals( 1, list.size() ); } @Test public void testExists2() throws Exception { KieBase kbase = loadKnowledgeBase("test_exists.drl"); StatefulKnowledgeSession workingMemory = createKnowledgeSession((KnowledgeBase) kbase); final List list = new ArrayList(); workingMemory.setGlobal( "list", list ); final Cheese cheddar = new Cheese( "cheddar", 7 ); final Cheese provolone = new Cheese( "provolone", 5 ); final Person edson = new Person( "Edson", "cheddar" ); final Person bob = new Person( "Bob", "muzzarela" ); workingMemory.insert( cheddar ); workingMemory.fireAllRules(); assertEquals( 0, list.size() ); workingMemory.insert( provolone ); workingMemory.fireAllRules(); assertEquals( 0, list.size() ); workingMemory.insert( edson ); workingMemory.fireAllRules(); assertEquals( 1, list.size() ); workingMemory.insert( bob ); workingMemory.fireAllRules(); assertEquals( 1, list.size() ); } @Test public void testExists3() throws Exception { KieBase kbase = loadKnowledgeBase("test_Exists_JBRULES_2810.drl"); StatefulKnowledgeSession ksession = createKnowledgeSession((KnowledgeBase) kbase); WorkingMemoryConsoleLogger logger = new WorkingMemoryConsoleLogger( ksession ); ksession.fireAllRules(); ksession.dispose(); } @Test public void testForall() throws Exception { KieBase kbase = loadKnowledgeBase("test_Forall.drl"); StatefulKnowledgeSession workingMemory = createKnowledgeSession((KnowledgeBase) kbase); final List list = new ArrayList(); workingMemory.setGlobal( "results", list ); final State state = new State( "SP" ); workingMemory.insert( state ); final Person bob = new Person( "Bob" ); bob.setStatus( state.getState() ); bob.setLikes( "stilton" ); workingMemory.insert( bob ); workingMemory.fireAllRules(); assertEquals( 0, list.size() ); workingMemory.insert( new Cheese( bob.getLikes(), 10 ) ); workingMemory.fireAllRules(); assertEquals( 1, list.size() ); } @Test public void testForall2() throws Exception { KieBase kbase = loadKnowledgeBase("test_Forall2.drl"); StatefulKnowledgeSession ksession = createKnowledgeSession((KnowledgeBase) kbase); final List<String> list = new ArrayList<String>(); ksession.setGlobal( "results", list ); final State state = new State( "SP" ); ksession.insert( state ); final Person bob = new Person( "Bob" ); bob.setStatus( state.getState() ); bob.setAlive( true ); ksession.insert( bob ); ksession.fireAllRules(); assertEquals( 0, list.size() ); final State qc = new State( "QC" ); ksession.insert( qc ); final Person john = new Person( "John" ); john.setStatus( qc.getState() ); john.setAlive( false ); ksession.fireAllRules(); assertEquals( 1, list.size() ); } @Test public void testRemoveIdentitiesSubNetwork() throws Exception { KieBaseConfiguration conf = KnowledgeBaseFactory.newKnowledgeBaseConfiguration(); conf.setOption(RemoveIdentitiesOption.YES); KieBase kbase = loadKnowledgeBase(conf, "test_removeIdentitiesSubNetwork.drl"); StatefulKnowledgeSession workingMemory = createKnowledgeSession((KnowledgeBase) kbase); final List list = new ArrayList(); workingMemory.setGlobal( "results", list ); final Person bob = new Person( "bob", "stilton" ); workingMemory.insert( bob ); final Person mark = new Person( "mark", "stilton" ); workingMemory.insert( mark ); final Cheese stilton1 = new Cheese( "stilton", 6 ); final FactHandle stilton1Handle = (FactHandle) workingMemory.insert( stilton1 ); final Cheese stilton2 = new Cheese( "stilton", 7 ); final FactHandle stilton2Handle = (FactHandle) workingMemory.insert( stilton2 ); workingMemory.fireAllRules(); assertEquals( 0, list.size() ); workingMemory.retract( stilton1Handle ); workingMemory.fireAllRules(); assertEquals( 1, list.size() ); assertEquals( mark, list.get( 0 ) ); workingMemory.retract( stilton2Handle ); workingMemory.fireAllRules(); assertEquals( 2, list.size() ); assertEquals( bob, list.get( 1 ) ); } @Test public void testCollectWithNestedFromWithParams() throws Exception { KieBase kbase = loadKnowledgeBase( "test_CollectWithNestedFrom.drl"); StatefulKnowledgeSession workingMemory = createKnowledgeSession((KnowledgeBase) kbase); final List results = new ArrayList(); workingMemory.setGlobal( "results", results ); final Person bob = new Person( "bob", "stilton" ); Cheesery cheesery = new Cheesery(); cheesery.addCheese( new Cheese( "stilton", 10 ) ); cheesery.addCheese( new Cheese( "brie", 20 ) ); cheesery.addCheese( new Cheese( "muzzarela", 8 ) ); cheesery.addCheese( new Cheese( "stilton", 5 ) ); cheesery.addCheese( new Cheese( "provolone", 1 ) ); workingMemory.insert( bob ); workingMemory.insert( cheesery ); workingMemory.fireAllRules(); assertEquals( 1, results.size() ); List cheeses = (List) results.get( 0 ); assertEquals( 2, cheeses.size() ); assertEquals( bob.getLikes(), ((Cheese) cheeses.get( 0 )).getType() ); assertEquals( bob.getLikes(), ((Cheese) cheeses.get( 1 )).getType() ); } @Test public void testCollectModifyAlphaRestriction() throws Exception { KieBase kbase = loadKnowledgeBase( "test_CollectAlphaRestriction.drl"); StatefulKnowledgeSession wm = createKnowledgeSession((KnowledgeBase) kbase); final List results = new ArrayList(); wm.setGlobal( "results", results ); final Cheese[] cheese = new Cheese[]{new Cheese( "stilton", 10 ), new Cheese( "stilton", 2 ), new Cheese( "stilton", 5 ), new Cheese( "brie", 15 ), new Cheese( "brie", 16 ), new Cheese( "provolone", 8 )}; final FactHandle[] cheeseHandles = new FactHandle[cheese.length]; for ( int i = 0; i < cheese.length; i++ ) { cheeseHandles[i] = (FactHandle) wm.insert( cheese[i] ); } // ---------------- 1st scenario int fireCount = 0; wm.fireAllRules(); assertEquals( ++fireCount, results.size() ); assertEquals( 3, ((Collection) results.get( fireCount - 1 )).size() ); assertEquals( ArrayList.class.getName(), results.get( fireCount - 1 ).getClass().getName() ); // ---------------- 2nd scenario final int index = 1; cheese[index].setType( "brie" ); wm.update( cheeseHandles[index], cheese[index] ); wm.fireAllRules(); assertEquals( ++fireCount, results.size() ); assertEquals( 2, ((Collection) results.get( fireCount - 1 )).size() ); assertEquals( ArrayList.class.getName(), results.get( fireCount - 1 ).getClass().getName() ); // ---------------- 3rd scenario wm.retract( cheeseHandles[2] ); wm.fireAllRules(); assertEquals( ++fireCount, results.size() ); assertEquals( 1, ((Collection) results.get( fireCount - 1 )).size() ); assertEquals( ArrayList.class.getName(), results.get( fireCount - 1 ).getClass().getName() ); } @Test public void testForallSinglePattern() throws Exception { KieBase kbase = loadKnowledgeBase( "test_ForallSinglePattern.drl"); StatefulKnowledgeSession workingMemory = createKnowledgeSession((KnowledgeBase) kbase); final List list = new ArrayList(); workingMemory.setGlobal( "results", list ); int fired = 0; // no cheeses, so should fire workingMemory.fireAllRules(); assertEquals( ++fired, list.size() ); // only stilton, so should not fire again FactHandle stilton1 = (FactHandle) workingMemory.insert( new Cheese( "stilton", 10 ) ); workingMemory.fireAllRules(); assertEquals( fired, list.size() ); // only stilton, so should not fire again FactHandle stilton2 = (FactHandle) workingMemory.insert( new Cheese( "stilton", 11 ) ); workingMemory.fireAllRules(); assertEquals( fired, list.size() ); // still only stilton, so should not fire workingMemory.retract( stilton1 ); workingMemory.fireAllRules(); assertEquals( fired, list.size() ); // there is a brie, so should not fire FactHandle brie = (FactHandle) workingMemory.insert( new Cheese( "brie", 10 ) ); workingMemory.fireAllRules(); assertEquals( fired, list.size() ); // no brie anymore, so should fire workingMemory.retract( brie ); workingMemory.fireAllRules(); assertEquals( ++fired, list.size() ); // no more cheese, but since it already fired, should not fire again workingMemory.retract( stilton2 ); workingMemory.fireAllRules(); assertEquals( fired, list.size() ); } @Test public void testForallSinglePattern2() throws Exception { final KnowledgeBase kbase = loadKnowledgeBase( "test_ForallSinglePattern2.drl" ); final StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); ksession.insert( new Triangle( 3, 3, 3 ) ); ksession.insert( new Triangle( 3, 3, 3 ) ); // no cheeses, so should fire int fired = ksession.fireAllRules(); assertEquals( 1, fired ); ksession.dispose(); } @Test public void testMVELCollect() throws Exception { KieBase kbase = loadKnowledgeBase( "test_MVELCollect.drl"); StatefulKnowledgeSession wm = createKnowledgeSession((KnowledgeBase) kbase); final List results = new ArrayList(); wm.setGlobal( "results", results ); wm.insert( new Cheese( "stilton", 10 ) ); wm.insert( new Cheese( "stilton", 7 ) ); wm.insert( new Cheese( "stilton", 8 ) ); wm.insert( new Cheese( "brie", 5 ) ); wm.insert( new Cheese( "provolone", 150 ) ); wm.insert( new Cheese( "provolone", 20 ) ); wm.insert( new Person( "Bob", "stilton" ) ); wm.insert( new Person( "Mark", "provolone" ) ); wm.fireAllRules(); assertEquals( 1, results.size() ); assertEquals( 6, ((List) results.get( 0 )).size() ); } @Test public void testNestedCorelatedRulesWithForall() throws Exception { KieBase kbase = loadKnowledgeBase( "test_NestedCorrelatedRulesWithForall.drl"); StatefulKnowledgeSession session = createKnowledgeSession((KnowledgeBase) kbase); List list1 = new ArrayList(); List list2 = new ArrayList(); List list3 = new ArrayList(); List list4 = new ArrayList(); session.setGlobal( "list1", list1 ); session.setGlobal( "list2", list2 ); session.setGlobal( "list3", list3 ); session.setGlobal( "list4", list4 ); SpecialString first42 = new SpecialString( "42" ); SpecialString second42 = new SpecialString( "42" ); SpecialString world = new SpecialString( "World" ); //System.out.println( "Inserting ..." ); session.insert( world ); session.insert( first42 ); session.insert( second42 ); //System.out.println( "Done." ); //System.out.println( "Firing rules ..." ); // check all lists are empty assertTrue( list1.isEmpty() ); assertTrue( list2.isEmpty() ); assertTrue( list3.isEmpty() ); assertTrue( list4.isEmpty() ); session.fireAllRules(); //System.out.println( "Done." ); // check first list is populated correctly assertEquals( 0, list1.size() ); // check second list is populated correctly assertEquals( 0, list2.size() ); // check third list is populated correctly assertEquals( 1, list3.size() ); // check fourth list is populated correctly assertEquals( 0, list4.size() ); } @Test public void testFromInsideNotAndExists() throws Exception { KieBase kbase = loadKnowledgeBase("test_FromInsideNotAndExists.drl"); StatefulKnowledgeSession workingMemory = createKnowledgeSession((KnowledgeBase) kbase); final List list = new ArrayList(); workingMemory.setGlobal( "results", list ); final Cheese cheddar = new Cheese( "cheddar", 7 ); final Cheese provolone = new Cheese( "provolone", 5 ); final Cheesery cheesery = new Cheesery(); cheesery.addCheese( cheddar ); cheesery.addCheese( provolone ); FactHandle handle = (FactHandle) workingMemory.insert( cheesery ); workingMemory.fireAllRules(); assertEquals( 0, list.size() ); cheesery.addCheese( new Cheese( "stilton", 10 ) ); cheesery.removeCheese( cheddar ); workingMemory.update( handle, cheesery ); workingMemory.fireAllRules(); assertEquals( 2, list.size() ); } @Test public void testOr() throws Exception { KieBase kbase = loadKnowledgeBase( "test_OrNesting.drl"); StatefulKnowledgeSession workingMemory = createKnowledgeSession((KnowledgeBase) kbase); final List list = new ArrayList(); workingMemory.setGlobal( "results", list ); final Cheese cheddar = new Cheese( "cheddar", 7 ); final Cheese provolone = new Cheese( "provolone", 5 ); final Cheese brie = new Cheese( "brie", 15 ); final Person mark = new Person( "mark", "stilton" ); FactHandle ch = (FactHandle) workingMemory.insert( cheddar ); FactHandle ph = (FactHandle) workingMemory.insert( provolone ); FactHandle bh = (FactHandle) workingMemory.insert( brie ); FactHandle markh = (FactHandle) workingMemory.insert( mark ); workingMemory.fireAllRules(); assertEquals( 1, list.size() ); } // JBRULES-2482 @Test public void testOrWithVariableResolution() throws Exception { // KieBase kbase = loadKnowledgeBase( "test_OrCEFollowedByMultipleEval.drl"); // StatefulKnowledgeSession workingMemory = createKnowledgeSession((KnowledgeBase) kbase); final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add( ResourceFactory.newClassPathResource( "test_OrCEFollowedByMultipleEval.drl", FirstOrderLogicTest.class ), ResourceType.DRL ); assertFalse( kbuilder.getErrors().toString(), kbuilder.hasErrors() ); final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() ); final StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); final AgendaEventListener al = mock( AgendaEventListener.class ); ksession.addEventListener( al ); ksession.insert( new FactA( "a" ) ); ksession.insert( new FactB( "b" ) ); ksession.insert( new FactC( "c" ) ); ksession.fireAllRules(); verify( al, times( 6 ) ).afterMatchFired(any(AfterMatchFiredEvent.class)); } // JBRULES-2526 @Test public void testOrWithVariableResolution2() throws Exception { // KieBase kbase = loadKnowledgeBase( "test_OrCEFollowedByMultipleEval.drl"); // StatefulKnowledgeSession workingMemory = createKnowledgeSession((KnowledgeBase) kbase); final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder(); kbuilder.add( ResourceFactory.newClassPathResource( "test_OrCEFollowedByMultipleEval2.drl", FirstOrderLogicTest.class ), ResourceType.DRL ); assertFalse( kbuilder.getErrors().toString(), kbuilder.hasErrors() ); final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() ); final StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); final AgendaEventListener al = mock( AgendaEventListener.class ); ksession.addEventListener( al ); ksession.insert( new FactA( "a" ) ); ksession.insert( new FactB( "b" ) ); ksession.insert( new FactC( "c" ) ); ksession.fireAllRules(); verify( al, times( 8 ) ).afterMatchFired(any(AfterMatchFiredEvent.class)); } @Test public void testCollectWithMemberOfOperators() throws Exception { KieBase kbase = loadKnowledgeBase( "test_CollectMemberOfOperator.drl"); StatefulKnowledgeSession workingMemory = createKnowledgeSession((KnowledgeBase) kbase); final List list = new ArrayList(); workingMemory.setGlobal( "results", list ); final Order order1 = new Order( 1, "bob" ); final OrderItem item11 = new OrderItem( order1, 1 ); final OrderItem item12 = new OrderItem( order1, 2 ); final Order order2 = new Order( 2, "mark" ); final OrderItem item21 = new OrderItem( order2, 1 ); final OrderItem item22 = new OrderItem( order2, 2 ); workingMemory.insert( order1 ); workingMemory.insert( item11 ); workingMemory.insert( item12 ); workingMemory.insert( order2 ); workingMemory.insert( item21 ); workingMemory.insert( item22 ); workingMemory.fireAllRules(); int index = 0; assertEquals( 8, list.size() ); assertSame( order1, list.get( index++ ) ); assertSame( item11, list.get( index++ ) ); assertSame( order2, list.get( index++ ) ); assertSame( item21, list.get( index++ ) ); assertSame( order1, list.get( index++ ) ); assertSame( item11, list.get( index++ ) ); assertSame( order2, list.get( index++ ) ); assertSame( item21, list.get( index++ ) ); } @Test public void testCollectWithContainsOperators() throws Exception { KieBase kbase = loadKnowledgeBase( "test_CollectContainsOperator.drl"); StatefulKnowledgeSession workingMemory = createKnowledgeSession((KnowledgeBase) kbase); final List list = new ArrayList(); workingMemory.setGlobal( "results", list ); final Order order1 = new Order( 1, "bob" ); final OrderItem item11 = new OrderItem( order1, 1 ); final OrderItem item12 = new OrderItem( order1, 2 ); final Order order2 = new Order( 2, "mark" ); final OrderItem item21 = new OrderItem( order2, 1 ); final OrderItem item22 = new OrderItem( order2, 2 ); workingMemory.insert( order1 ); workingMemory.insert( item11 ); workingMemory.insert( item12 ); workingMemory.insert( order2 ); workingMemory.insert( item21 ); workingMemory.insert( item22 ); workingMemory.fireAllRules(); int index = 0; assertEquals( 8, list.size() ); assertSame( order1, list.get( index++ ) ); assertSame( item11, list.get( index++ ) ); assertSame( order2, list.get( index++ ) ); assertSame( item21, list.get( index++ ) ); assertSame( order1, list.get( index++ ) ); assertSame( item11, list.get( index++ ) ); assertSame( order2, list.get( index++ ) ); assertSame( item21, list.get( index++ ) ); } @Test public void testForallSinglePatternWithExists() throws Exception { KieBase kbase = loadKnowledgeBase( "test_ForallSinglePatternWithExists.drl"); StatefulKnowledgeSession workingMemory = createKnowledgeSession((KnowledgeBase) kbase); final List list = new ArrayList(); workingMemory.setGlobal( "results", list ); workingMemory.insert( new Cheese( "stilton", 10 ) ); workingMemory.insert( new Cheese( "brie", 10 ) ); workingMemory.insert( new Cheese( "brie", 10 ) ); workingMemory.insert( new Order( 1, "bob" ) ); workingMemory.insert( new Person( "bob", "stilton", 10 ) ); workingMemory.insert( new Person( "mark", "stilton" ) ); workingMemory.fireAllRules(); assertEquals( 1, list.size() ); } @Test public void testCollectResultBetaConstraint() throws Exception { KieBase kbase = loadKnowledgeBase( "test_CollectResultsBetaConstraint.drl"); StatefulKnowledgeSession wm = createKnowledgeSession((KnowledgeBase) kbase); List results = new ArrayList(); wm.setGlobal( "results", results ); wm.insert( new Double( 10 ) ); wm.insert( new Integer( 2 ) ); wm.fireAllRules(); assertEquals( 0, results.size() ); wm.insert( new Double( 15 ) ); wm.fireAllRules(); assertEquals( 2, results.size() ); assertEquals( "collect", results.get( 0 ) ); assertEquals( "accumulate", results.get( 1 ) ); } @Test public void testFromWithOr() throws Exception { KieBase kbase = loadKnowledgeBase( "test_FromWithOr.drl"); StatefulKnowledgeSession session = createKnowledgeSession((KnowledgeBase) kbase); final List<Address> results = new ArrayList<Address>(); session.setGlobal( "results", results ); Address a1 = new Address(); a1.setZipCode( "12345" ); Address a2 = new Address(); a2.setZipCode( "54321" ); Address a3 = new Address(); a3.setZipCode( "99999" ); Person p = new Person(); p.addAddress( a1 ); p.addAddress( a2 ); p.addAddress( a3 ); session.insert( p ); session.fireAllRules(); assertEquals( 2, results.size() ); assertTrue( results.contains( a1 ) ); assertTrue( results.contains( a2 ) ); } @Test public void testForallWithSlidingWindow() throws Exception { final KieSessionConfiguration conf = KnowledgeBaseFactory.newKnowledgeSessionConfiguration(); conf.setOption( ClockTypeOption.get( ClockType.PSEUDO_CLOCK.getId() ) ); KieBase kbase = loadKnowledgeBase( "test_ForallSlidingWindow.drl"); StatefulKnowledgeSession ksession = createKnowledgeSession((KnowledgeBase) kbase, conf); final SessionPseudoClock clock = (SessionPseudoClock) ksession.<SessionClock>getSessionClock(); List<String> results = new ArrayList<String>(); ksession.setGlobal( "results", results ); // advance time... no events, so forall should fire clock.advanceTime( 60, TimeUnit.SECONDS ); ksession.fireAllRules(); assertEquals( 1, results.size() ); int seq = 1; // advance time... there are matching events now, but forall still not fire ksession.insert( new StockTick( seq++, "RHT", 10, clock.getCurrentTime() ) ); // 60 clock.advanceTime( 5, TimeUnit.SECONDS ); ksession.fireAllRules(); assertEquals( 1, results.size() ); ksession.insert( new StockTick( seq++, "RHT", 10, clock.getCurrentTime() ) ); // 65 clock.advanceTime( 5, TimeUnit.SECONDS ); ksession.fireAllRules(); assertEquals( 1, results.size() ); // advance time... there are non-matching events now, so forall de-activates ksession.insert( new StockTick( seq++, "IBM", 10, clock.getCurrentTime() ) ); // 70 clock.advanceTime( 10, TimeUnit.SECONDS ); ksession.fireAllRules(); assertEquals( 1, results.size() ); // advance time... there are non-matching events now, so forall is still deactivated ksession.insert( new StockTick( seq++, "RHT", 10, clock.getCurrentTime() ) ); // 80 clock.advanceTime( 10, TimeUnit.SECONDS ); ksession.fireAllRules(); assertEquals( 1, results.size() ); // advance time... non-matching event expires now, so forall should fire ksession.insert( new StockTick( seq++, "RHT", 10, clock.getCurrentTime() ) ); // 90 clock.advanceTime( 10, TimeUnit.SECONDS ); ksession.fireAllRules(); assertEquals( 2, results.size() ); // advance time... forall still matches and should not fire ksession.insert( new StockTick( seq++, "RHT", 10, clock.getCurrentTime() ) ); // 100 clock.advanceTime( 10, TimeUnit.SECONDS ); ksession.fireAllRules(); assertEquals( 2, results.size() ); // advance time... forall still matches and should not fire clock.advanceTime( 60, TimeUnit.SECONDS ); ksession.fireAllRules(); assertEquals( 2, results.size() ); } @Test public void testCollectFromMVELAfterOr() throws Exception { KieBase kbase = loadKnowledgeBase( "test_CollectFromMVELAfterOr.drl"); StatefulKnowledgeSession wm = createKnowledgeSession((KnowledgeBase) kbase); List results = new ArrayList(); wm.setGlobal( "results", results ); Person jill = new Person( "jill" ); Person bob = new Person( "bob" ); List addresses = new ArrayList(); addresses.add( new Address( "a" ) ); addresses.add( new Address( "b" ) ); addresses.add( new Address( "c" ) ); bob.setAddresses( addresses ); wm.insert( jill ); wm.insert( bob ); wm = SerializationHelper.getSerialisedStatefulKnowledgeSession(wm, true); results = (List) wm.getGlobal( "results" ); wm.fireAllRules(); assertEquals( 2, results.size() ); assertEquals( 3, ((Collection) results.get( 0 )).size() ); } @Test public void testCollectAfterOrCE() throws Exception { Collection<KnowledgePackage> pkgs = loadKnowledgePackages("test_OrCEFollowedByCollect.drl"); KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages(pkgs); StatefulKnowledgeSession session = createKnowledgeSession((KnowledgeBase) kbase); //Set up facts final Cheesery bonFromage = new Cheesery(); bonFromage.addCheese( new Cheese( "cheddar" ) ); bonFromage.addCheese( new Cheese( "cheddar" ) ); session.insert( bonFromage ); int rules = session.fireAllRules(); assertEquals( 2, rules ); //Serialize and test again pkgs = SerializationHelper.serializeObject(pkgs); kbase = KnowledgeBaseFactory.newKnowledgeBase(); kbase.addKnowledgePackages( pkgs ); session = createKnowledgeSession(kbase); session.insert( bonFromage ); rules = session.fireAllRules(); assertEquals( 2, rules ); } @Test public void testLotsOfOrs() throws Exception { // Decomposed this test down to just two rules, while still exhibiting the problem // Uncomment rest of rule as those are fixed, to complicate it again. String str = "package org.drools.compiler.test\n" + "\n" + "import " + FirstOrderLogicTest.class.getCanonicalName() + ".Field;\n" + " \n" + "rule \"test\"\n" + " when\n" + " (\n" + " ( \n" + " a : Field( name == \"a\") and\n" + " eval( !a.getValue().equals(\"a\") ) and\n" + " b : Field( name == \"b\" ) and\n" + " eval( b.intValue()>10 )\n" + " )\n" + " or\n" + " (\n" + " b2 : Field( name == \"b\" ) and\n" + " eval( b2.intValue()<10 )\n" + " )\n" + " )\n" + " and \n" + " (\n" + " t : Field( name == \"t\" ) and\n" + " eval( t.getValue().equals(\"Y\") )\n" + " )\n" + " and (\n" + " (\n" + " c : Field( name == \"c\" ) and\n" + " eval( c.getValue().equals(\"c\") ) and\n" + " d : Field( name == \"d\" ) and\n" + " eval( d.intValue()<5 )\n" + " ) \n" + " or \n" + " (\n" + " c : Field( name == \"c\" ) and\n" + " eval( c.getValue().equals(\"c\") ) and\n" + " d : Field( name == \"d\" ) and\n" + " eval( d.intValue()<20 )\n" + " ) \n" + " or \n" + " ( \n" + " c : Field( name == \"c\") and\n" + " eval( c.getValue().equals(\"d\") ) and\n" + " d : Field( name == \"d\" ) and\n" + " eval( d.intValue()<20 )\n" + " )\n" + " )\n" + " then\n" + " System.out.println( \"Worked!\" ); \n" + "end"; logger.info( str ); KnowledgeBase kbase = loadKnowledgeBaseFromString( str ); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); ksession.insert(new Field("t", "Y")); ksession.insert(new Field("a", "b")); ksession.insert(new Field("b", "15")); ksession.insert(new Field("c", "d")); ksession.insert(new Field("d", "15")); ksession.fireAllRules(); ksession.dispose(); } @Test public void testOrs() throws Exception { String str = "package org.drools.compiler.integrationtests\n" + "import " + Message.class.getName() + "\n" + "rule X\n" + " when\n" + " Message( message == 'test' )\n" + " Message( !fired ) or eval( !false )\n" + " then\n" + "end\n"; KnowledgeBase kbase = loadKnowledgeBaseFromString( str ); StatefulKnowledgeSession ksession = createKnowledgeSession(kbase); ksession.insert( new Message( "test" ) ); int rules = ksession.fireAllRules(); assertEquals( 2, rules ); ksession.dispose(); } public class Field { public Field(String name, String value) { super(); this.name = name; this.value = value; } private String name; private String value; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public int intValue() { Integer intValue = Integer.valueOf(value); return intValue; } } }
package org.oxtrust.qa.steps; import org.oxtrust.qa.pages.login.HomePage; import org.oxtrust.qa.pages.openidconnect.ClientAddPage; import org.oxtrust.qa.pages.openidconnect.OpenIdConnectClientManagePage; import org.oxtrust.qa.pages.openidconnect.OpenIdConnectScopeAddPage; import org.oxtrust.qa.pages.openidconnect.OpenIdConnectScopeManagePage; import org.oxtrust.qa.pages.openidconnect.OpenIdConnectScopeUpdatePage; import org.oxtrust.qa.pages.openidconnect.SectorAddPage; import org.oxtrust.qa.pages.openidconnect.SectorManagePage; import cucumber.api.Scenario; import cucumber.api.java.After; import cucumber.api.java.Before; import cucumber.api.java.en.And; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class OpenIdConnectSteps extends BaseSteps { private HomePage homePage = new HomePage(); private OpenIdConnectScopeManagePage opConnectScopeManagePage = new OpenIdConnectScopeManagePage(); private OpenIdConnectClientManagePage openIdConnectClientManagePage = new OpenIdConnectClientManagePage(); private OpenIdConnectScopeAddPage openIdConnectScopeAddPage = new OpenIdConnectScopeAddPage(); private OpenIdConnectScopeUpdatePage openIdConnectScopeUpdatePage = new OpenIdConnectScopeUpdatePage(); private ClientAddPage clientAddPage = new ClientAddPage(); private SectorAddPage sectorAddPage = new SectorAddPage(); private SectorManagePage sectorManagePage = new SectorManagePage(); @Before public void setup(Scenario scenario) { startRecorder(scenario); } @When("^I go to openid connect scopes list page$") public void goToOpenIdScopesListPage() { homePage.goToOpenIDScopePage(); } @When("^I go to sectors list page$") public void goToSectorListPage() { homePage.goToSectorListPage(); } @When("^I search for openid scopes with pattern '(.+)'$") public void searchOpenIDScopes(String pattern) { opConnectScopeManagePage.searchFor(pattern); } @Then("^I should see an openid scope named '(.+)'$") public void searchScopeInList(String scope) { opConnectScopeManagePage.assertScopeExist(scope); } @Then("^I should not see an openid scope named '(.+)'$") public void searchForScopeInList(String scope) { opConnectScopeManagePage.assertScopeDontExist(scope); } @When("^I go to openid connect clients list page$") public void goToOpenIdClientListPage() { homePage.goToOpenIDClientsListPage(); } @When("^I search for openid clients with pattern '(.+)'$") public void searchOpenIDClients(String pattern) { openIdConnectClientManagePage.searchFor(pattern); } @Then("^I should see an openid client named '(.+)'$") public void searchClientInList(String client) { openIdConnectClientManagePage.assertClientExist(client); } @Then("^I should not see an openid client named '(.+)'$") public void searchClientNotInList(String client) { openIdConnectClientManagePage.assertClientDontExist(client); } @And("^I start the process to add new client$") public void clickAddClientButton() { openIdConnectClientManagePage.goToClientAddPage(); } @And("^I start the process to add new scope$") public void clickAddScopeButton() { opConnectScopeManagePage.goToScopeAddPage(); } @And("^I start the process to add new sector$") public void clickAddSectorButton() { sectorManagePage.goToSectorAddPage(); } @And("^I set the display name '(.+)'$") public void setDisplayName(String dn) { openIdConnectScopeAddPage.setDisplayName(dn); } @And("^I edit the display name value to '(.+)'$") public void editDisplayName(String dn) { openIdConnectScopeAddPage.setDisplayName(dn); } @And("^I set the description '(.+)'$") public void setDescription(String des) { openIdConnectScopeAddPage.setDescription(des); } @And("^I edit the description value to '(.+)'$") public void editDescription(String des) { openIdConnectScopeAddPage.setDescription(des); } @And("^I set the scope type to '(.+)'$") public void setScopeType(String type) { openIdConnectScopeAddPage.setType(type); } @And("^I set dynamic registration to '(.+)'$") public void setRegistrationType(String rType) { openIdConnectScopeAddPage.setRegistrationType(rType); } @And("^I save the scope registration$") public void perfomSave() { openIdConnectScopeAddPage.save(); } @And("^I save the scope edition$") public void perfomEdition() { openIdConnectScopeUpdatePage.edit(); } @And("^I save the client edition$") public void perfomClientEdition() { openIdConnectClientManagePage.edit(); } @And("^I start the process to edit the scope named '(.+)'$") public void editCurrentScope(String scope) { opConnectScopeManagePage.editScope(scope); } @And("^I start the process to edit the client named '(.+)'$") public void editCurrentClient(String scope) { openIdConnectClientManagePage.editClient(scope); } @When("^I delete that scope$") public void deleteScope() { openIdConnectScopeUpdatePage.delete(); } @When("^I delete that client$") public void deleteClient() { openIdConnectClientManagePage.delete(); } @And("^I set the client name to '(.+)'$") public void setClientName(String name) { clientAddPage.setClientName(name); } @And("^I edit the client name to '(.+)'$") public void editClientName(String name) { clientAddPage.setClientName(name); } @And("^I set the client description to '(.+)'$") public void setClientDes(String des) { clientAddPage.setDescription(des); } @And("^I edit the client description to '(.+)'$") public void editClientDes(String des) { clientAddPage.setDescription(des); } @And("^I set the client secret to '(.+)'$") public void setClientSecret(String secret) { clientAddPage.setSecret(secret); } @And("^I change the client password to '(.+)'$") public void changeClientPassword(String pwd) { clientAddPage.changePassword(pwd); } @And("^I edit the client secret to '(.+)'$") public void editClientSecret(String secret) { clientAddPage.setSecret(secret); } @And("^I set application type to '(.+)'$") public void setType(String type) { clientAddPage.setType(type); } @And("^I set preauthorization to '(.+)'$") public void setPreAuth(String value) { clientAddPage.setPreAutho(value); } @And("^I set persist authorization to '(.+)'$") public void setPersistAuth(String value) { clientAddPage.setPersistAutho(value); } @And("^I set subject type to '(.+)'$") public void setSubjectType(String value) { clientAddPage.setSubjectType(value); } @And("^I set authentication method to '(.+)'$") public void setAuthendMethod(String value) { clientAddPage.setAuthendMethod(value); } @And("^I add the scope named '(.+)'$") public void addScope(String scope) { clientAddPage.addScope(scope); } @And("^I add the response type named '(.+)'$") public void addResponseType(String type) { clientAddPage.responseType(type); } @And("^I add the grant type named '(.+)'$") public void addGrantType(String type) { clientAddPage.grantType(type); } @And("^I add the login redirect named '(.+)'$") public void addLoginRedirect(String url) { clientAddPage.loginRedirect(url); } @And("^I save the client registration") public void saveClient() { clientAddPage.save(); } @And("^I set '(.+)' as login redirect$") public void setLoginRedirect(String url) { sectorAddPage.addLoginRedirect(url); } @And("^I pick '(.+)' as client$") public void chooseClient(String client) { sectorAddPage.addClient(client); } @And("^I save the sector$") public void save() { sectorAddPage.save(); } @Then("^I should see that the list is not empty$") public void checkListIsNotEmpty() { sectorManagePage.assertListIsNotEmpty(); } @When("^I delete that sector$") public void deleteSector() { sectorManagePage.deleteFirstSector(); } @Then("^I should see that the list is empty$") public void checkListIsEmpty() { sectorManagePage.assertListIsEmpty(); } @And("^I select the OIDC '(.+)' tab$") public void selectTab(String tabName) { clientAddPage.selectTab(tabName); } @After public void clear(Scenario scenario) { homePage.takeScreenShot(scenario); stopRecorder(); homePage.clear(); } }
/* ******************************************************************************* * Copyright (C) 2007-2014, International Business Machines Corporation and * others. All Rights Reserved. ******************************************************************************* */ package androidx.core.i18n.messageformat_icu.simple; import android.annotation.SuppressLint; import java.io.IOException; import java.io.NotSerializableException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.text.ParseException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; import androidx.annotation.RestrictTo; import androidx.core.i18n.messageformat_icu.util.Output; /** * <p> * Defines rules for mapping non-negative numeric values onto a small set of keywords. * </p> * <p> * Rules are constructed from a text description, consisting of a series of keywords and conditions. The {@link #select} * method examines each condition in order and returns the keyword for the first condition that matches the number. If * none match, {@link #KEYWORD_OTHER} is returned. * </p> * <p> * A PluralRules object is immutable. It contains caches for sample values, but those are synchronized. * <p> * PluralRules is Serializable so that it can be used in formatters, which are serializable. * </p> * <p> * For more information, details, and tips for writing rules, see the <a * href="http://www.unicode.org/draft/reports/tr35/tr35.html#Language_Plural_Rules">LDML spec, C.11 Language Plural * Rules</a> * </p> * <p> * Examples: * </p> * * <pre> * &quot;one: n is 1; few: n in 2..4&quot; * </pre> * <p> * This defines two rules, for 'one' and 'few'. The condition for 'one' is "n is 1" which means that the number must be * equal to 1 for this condition to pass. The condition for 'few' is "n in 2..4" which means that the number must be * between 2 and 4 inclusive - and be an integer - for this condition to pass. All other numbers are assigned the * keyword "other" by the default rule. * </p> * * <pre> * &quot;zero: n is 0; one: n is 1; zero: n mod 100 in 1..19&quot; * </pre> * <p> * This illustrates that the same keyword can be defined multiple times. Each rule is examined in order, and the first * keyword whose condition passes is the one returned. Also notes that a modulus is applied to n in the last rule. Thus * its condition holds for 119, 219, 319... * </p> * * <pre> * &quot;one: n is 1; few: n mod 10 in 2..4 and n mod 100 not in 12..14&quot; * </pre> * <p> * This illustrates conjunction and negation. The condition for 'few' has two parts, both of which must be met: * "n mod 10 in 2..4" and "n mod 100 not in 12..14". The first part applies a modulus to n before the test as in the * previous example. The second part applies a different modulus and also uses negation, thus it matches all numbers * _not_ in 12, 13, 14, 112, 113, 114, 212, 213, 214... * </p> * <p> * Syntax: * </p> * <pre> * rules = rule (';' rule)* * rule = keyword ':' condition * keyword = &lt;identifier&gt; * condition = and_condition ('or' and_condition)* * and_condition = relation ('and' relation)* * relation = not? expr not? rel not? range_list * expr = ('n' | 'i' | 'f' | 'v' | 't') (mod value)? * not = 'not' | '!' * rel = 'in' | 'is' | '=' | '≠' | 'within' * mod = 'mod' | '%' * range_list = (range | value) (',' range_list)* * value = digit+ * digit = 0|1|2|3|4|5|6|7|8|9 * range = value'..'value * </pre> * <p>Each <b>not</b> term inverts the meaning; however, there should not be more than one of them.</p> * <p> * The i, f, t, and v values are defined as follows: * </p> * <ul> * <li>i to be the integer digits.</li> * <li>f to be the visible decimal digits, as an integer.</li> * <li>t to be the visible decimal digits—without trailing zeros—as an integer.</li> * <li>v to be the number of visible fraction digits.</li> * <li>j is defined to only match integers. That is j is 3 fails if v != 0 (eg for 3.1 or 3.0).</li> * </ul> * <p> * Examples are in the following table: * </p> * <table border='1' style="border-collapse:collapse"> * <tbody> * <tr> * <th>n</th> * <th>i</th> * <th>f</th> * <th>v</th> * </tr> * <tr> * <td>1.0</td> * <td>1</td> * <td align="right">0</td> * <td>1</td> * </tr> * <tr> * <td>1.00</td> * <td>1</td> * <td align="right">0</td> * <td>2</td> * </tr> * <tr> * <td>1.3</td> * <td>1</td> * <td align="right">3</td> * <td>1</td> * </tr> * <tr> * <td>1.03</td> * <td>1</td> * <td align="right">3</td> * <td>2</td> * </tr> * <tr> * <td>1.23</td> * <td>1</td> * <td align="right">23</td> * <td>2</td> * </tr> * </tbody> * </table> * <p> * An "identifier" is a sequence of characters that do not have the Unicode Pattern_Syntax or Pattern_White_Space * properties. * <p> * The difference between 'in' and 'within' is that 'in' only includes integers in the specified range, while 'within' * includes all values. Using 'within' with a range_list consisting entirely of values is the same as using 'in' (it's * not an error). * </p> * * icu_annot::stable ICU 3.8 * @hide */ @RestrictTo(RestrictTo.Scope.LIBRARY) public class PluralRules implements Serializable { // static final UnicodeSet ALLOWED_ID = new UnicodeSet("[a-z]").freeze(); // TODO Remove RulesList by moving its API and fields into PluralRules. /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public static final String CATEGORY_SEPARATOR = "; "; /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public static final String KEYWORD_RULE_SEPARATOR = ": "; private static final long serialVersionUID = 1; private final RuleList rules; private final transient Set<String> keywords; /** * Provides a factory for returning plural rules * * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public static abstract class Factory { /** * Provides access to the predefined <code>PluralRules</code> for a given locale and the plural type. * * <p> * ICU defines plural rules for many locales based on CLDR <i>Language Plural Rules</i>. For these predefined * rules, see CLDR page at http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * * @param locale * The locale for which a <code>PluralRules</code> object is returned. * @param type * The plural type (e.g., cardinal or ordinal). * @return The predefined <code>PluralRules</code> object for this locale. If there's no predefined rules for * this locale, the rules for the closest parent in the locale hierarchy that has one will be returned. * The final fallback always returns the default rules. * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public abstract PluralRules forLocale(Locale locale, PluralType type); /** * Utility for getting CARDINAL rules. * @param locale the locale * @return plural rules. * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public final PluralRules forLocale(Locale locale) { return forLocale(locale, PluralType.CARDINAL); } /** * Returns the locales for which there is plurals data. * * icu_annot::internal * This API is ICU internal only. @Deprecated public abstract ULocale[] getAvailableULocales(); */ /** * Returns the 'functionally equivalent' locale with respect to plural rules. Calling PluralRules.forLocale with * the functionally equivalent locale, and with the provided locale, returns rules that behave the same. <br/> * All locales with the same functionally equivalent locale have plural rules that behave the same. This is not * exhaustive; there may be other locales whose plural rules behave the same that do not have the same equivalent * locale. * * @param locale * the locale to check * @param isAvailable * if not null and of length > 0, this will hold 'true' at index 0 if locale is directly defined * (without fallback) as having plural rules * @return the functionally-equivalent locale * icu_annot::internal * This API is ICU internal only. @Deprecated public abstract ULocale getFunctionalEquivalent(ULocale locale, boolean[] isAvailable); */ /** * Returns the default factory. * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public static PluralRulesLoader getDefaultFactory() { return PluralRulesLoader.loader; } /** * Returns whether or not there are overrides. * icu_annot::internal * This API is ICU internal only. @Deprecated public abstract boolean hasOverride(ULocale locale); */ } // Standard keywords. /** * Common name for the 'zero' plural form. * icu_annot::stable ICU 3.8 */ public static final String KEYWORD_ZERO = "zero"; /** * Common name for the 'singular' plural form. * icu_annot::stable ICU 3.8 */ public static final String KEYWORD_ONE = "one"; /** * Common name for the 'dual' plural form. * icu_annot::stable ICU 3.8 */ public static final String KEYWORD_TWO = "two"; /** * Common name for the 'paucal' or other special plural form. * icu_annot::stable ICU 3.8 */ public static final String KEYWORD_FEW = "few"; /** * Common name for the arabic (11 to 99) plural form. * icu_annot::stable ICU 3.8 */ public static final String KEYWORD_MANY = "many"; /** * Common name for the default plural form. This name is returned * for values to which no other form in the rule applies. It * can additionally be assigned rules of its own. * icu_annot::stable ICU 3.8 */ public static final String KEYWORD_OTHER = "other"; /** * Value returned by {@link #getUniqueKeywordValue} when there is no * unique value to return. * icu_annot::stable ICU 4.8 */ public static final double NO_UNIQUE_VALUE = -0.00123456777; /** * Type of plurals and PluralRules. * icu_annot::stable ICU 50 */ public enum PluralType { /** * Plural rules for cardinal numbers: 1 file vs. 2 files. * icu_annot::stable ICU 50 */ CARDINAL, /** * Plural rules for ordinal numbers: 1st file, 2nd file, 3rd file, 4th file, etc. * icu_annot::stable ICU 50 */ ORDINAL }; /* * The default constraint that is always satisfied. */ private static final Constraint NO_CONSTRAINT = new Constraint() { private static final long serialVersionUID = 9163464945387899416L; @Override public boolean isFulfilled(FixedDecimal n) { return true; } @Override public boolean isLimited(SampleType sampleType) { return false; } @Override public String toString() { return ""; } }; /** * */ private static final Rule DEFAULT_RULE = new Rule("other", NO_CONSTRAINT, null, null); /** * Parses a plural rules description and returns a PluralRules. * @param description the rule description. * @throws ParseException if the description cannot be parsed. * The exception index is typically not set, it will be -1. * icu_annot::stable ICU 3.8 */ public static PluralRules parseDescription(String description) throws ParseException { description = description.trim(); return description.length() == 0 ? DEFAULT : new PluralRules(parseRuleChain(description)); } /** * Creates a PluralRules from a description if it is parsable, * otherwise returns null. * @param description the rule description. * @return the PluralRules * icu_annot::stable ICU 3.8 */ public static PluralRules createRules(String description) { try { return parseDescription(description); } catch(Exception e) { return null; } } /** * The default rules that accept any number and return * {@link #KEYWORD_OTHER}. * icu_annot::stable ICU 3.8 */ public static final PluralRules DEFAULT = new PluralRules(new RuleList().addRule(DEFAULT_RULE)); private enum Operand { n, i, f, t, v, w, /* deprecated */ j; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public static class FixedDecimal extends Number implements Comparable<FixedDecimal> { private static final long serialVersionUID = -4756200506571685661L; /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public final double source; /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public final int visibleDecimalDigitCount; /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public final int visibleDecimalDigitCountWithoutTrailingZeros; /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public final long decimalDigits; /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public final long decimalDigitsWithoutTrailingZeros; /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public final long integerValue; /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public final boolean hasIntegerValue; /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public final boolean isNegative; private final int baseFactor; /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public double getSource() { return source; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public int getVisibleDecimalDigitCount() { return visibleDecimalDigitCount; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public int getVisibleDecimalDigitCountWithoutTrailingZeros() { return visibleDecimalDigitCountWithoutTrailingZeros; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public long getDecimalDigits() { return decimalDigits; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public long getDecimalDigitsWithoutTrailingZeros() { return decimalDigitsWithoutTrailingZeros; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public long getIntegerValue() { return integerValue; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public boolean isHasIntegerValue() { return hasIntegerValue; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public boolean isNegative() { return isNegative; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public int getBaseFactor() { return baseFactor; } static final long MAX = (long)1E18; /** * icu_annot::internal * This API is ICU internal only. * @param n is the original number * @param v number of digits to the right of the decimal place. e.g. 1.00 = 2 25. = 0 * @param f Corresponds to f in the plural rules grammar. * The digits to the right of the decimal place as an integer. e.g. 1.10 = 10 */ // @Deprecated: in fact internal ICU public FixedDecimal(double n, int v, long f) { isNegative = n < 0; source = isNegative ? -n : n; visibleDecimalDigitCount = v; decimalDigits = f; integerValue = n > MAX ? MAX : (long)n; hasIntegerValue = source == integerValue; // check values. TODO make into unit test. // // long visiblePower = (int) Math.pow(10, v); // if (fractionalDigits > visiblePower) { // throw new IllegalArgumentException(); // } // double fraction = intValue + (fractionalDigits / (double) visiblePower); // if (fraction != source) { // double diff = Math.abs(fraction - source)/(Math.abs(fraction) + Math.abs(source)); // if (diff > 0.00000001d) { // throw new IllegalArgumentException(); // } // } if (f == 0) { decimalDigitsWithoutTrailingZeros = 0; visibleDecimalDigitCountWithoutTrailingZeros = 0; } else { long fdwtz = f; int trimmedCount = v; while ((fdwtz%10) == 0) { fdwtz /= 10; --trimmedCount; } decimalDigitsWithoutTrailingZeros = fdwtz; visibleDecimalDigitCountWithoutTrailingZeros = trimmedCount; } baseFactor = (int) Math.pow(10, v); } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public FixedDecimal(double n, int v) { this(n,v,getFractionalDigits(n, v)); } private static int getFractionalDigits(double n, int v) { if (v == 0) { return 0; } else { if (n < 0) { n = -n; } int baseFactor = (int) Math.pow(10, v); long scaled = Math.round(n * baseFactor); return (int) (scaled % baseFactor); } } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public FixedDecimal(double n) { this(n, decimals(n)); } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public FixedDecimal(long n) { this(n,0); } private static final long MAX_INTEGER_PART = 1000000000; /** * Return a guess as to the number of decimals that would be displayed. This is only a guess; callers should * always supply the decimals explicitly if possible. Currently, it is up to 6 decimals (without trailing zeros). * Returns 0 for infinities and nans. * icu_annot::internal * This API is ICU internal only. * */ // @Deprecated: in fact internal ICU public static int decimals(double n) { // Ugly... if (Double.isInfinite(n) || Double.isNaN(n)) { return 0; } if (n < 0) { n = -n; } if (n < MAX_INTEGER_PART) { long temp = (long)(n * 1000000) % 1000000; // get 6 decimals for (int mask = 10, digits = 6; digits > 0; mask *= 10, --digits) { if ((temp % mask) != 0) { return digits; } } return 0; } else { String buf = String.format(Locale.ENGLISH, "%1.15e", n); int ePos = buf.lastIndexOf('e'); int expNumPos = ePos + 1; if (buf.charAt(expNumPos) == '+') { expNumPos++; } String exponentStr = buf.substring(expNumPos); int exponent = Integer.parseInt(exponentStr); int numFractionDigits = ePos - 2 - exponent; if (numFractionDigits < 0) { return 0; } for (int i=ePos-1; numFractionDigits > 0; --i) { if (buf.charAt(i) != '0') { break; } --numFractionDigits; } return numFractionDigits; } } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public FixedDecimal (String n) { // Ugly, but for samples we don't care. this(Double.parseDouble(n), getVisibleFractionCount(n)); } private static int getVisibleFractionCount(String value) { value = value.trim(); int decimalPos = value.indexOf('.') + 1; if (decimalPos == 0) { return 0; } else { return value.length() - decimalPos; } } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public double get(@SuppressLint("HiddenTypeParameter") Operand operand) { switch(operand) { default: return source; case i: return integerValue; case f: return decimalDigits; case t: return decimalDigitsWithoutTrailingZeros; case v: return visibleDecimalDigitCount; case w: return visibleDecimalDigitCountWithoutTrailingZeros; } } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU @SuppressLint("HiddenTypeParameter") public static Operand getOperand(String t) { return Operand.valueOf(t); } /** * We're not going to care about NaN. * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU @Override public int compareTo(FixedDecimal other) { if (integerValue != other.integerValue) { return integerValue < other.integerValue ? -1 : 1; } if (source != other.source) { return source < other.source ? -1 : 1; } if (visibleDecimalDigitCount != other.visibleDecimalDigitCount) { return visibleDecimalDigitCount < other.visibleDecimalDigitCount ? -1 : 1; } long diff = decimalDigits - other.decimalDigits; if (diff != 0) { return diff < 0 ? -1 : 1; } return 0; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU @Override public boolean equals(Object arg0) { if (arg0 == null) { return false; } if (arg0 == this) { return true; } if (!(arg0 instanceof FixedDecimal)) { return false; } FixedDecimal other = (FixedDecimal)arg0; return source == other.source && visibleDecimalDigitCount == other.visibleDecimalDigitCount && decimalDigits == other.decimalDigits; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU @Override public int hashCode() { // TODO Auto-generated method stub return (int)(decimalDigits + 37 * (visibleDecimalDigitCount + (int)(37 * source))); } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU @Override public String toString() { return String.format("%." + visibleDecimalDigitCount + "f", source); } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public boolean hasIntegerValue() { return hasIntegerValue; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU @Override public int intValue() { // TODO Auto-generated method stub return (int)integerValue; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU @Override public long longValue() { return integerValue; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU @Override public float floatValue() { return (float) source; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU @Override public double doubleValue() { return isNegative ? -source : source; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public long getShiftedValue() { return integerValue * baseFactor + decimalDigits; } private void writeObject( ObjectOutputStream out) throws IOException { throw new NotSerializableException(); } private void readObject(ObjectInputStream in ) throws IOException, ClassNotFoundException { throw new NotSerializableException(); } } /** * Selection parameter for either integer-only or decimal-only. * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public enum SampleType { /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU INTEGER, /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU DECIMAL } /** * A range of NumberInfo that includes all values with the same visibleFractionDigitCount. * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public static class FixedDecimalRange { /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public final FixedDecimal start; /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public final FixedDecimal end; /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public FixedDecimalRange(FixedDecimal start, FixedDecimal end) { if (start.visibleDecimalDigitCount != end.visibleDecimalDigitCount) { throw new IllegalArgumentException("Ranges must have the same number of visible decimals: " + start + "~" + end); } this.start = start; this.end = end; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU @Override public String toString() { return start + (end.equals(start) ? "" : "~" + end); } } /** * A list of NumberInfo that includes all values with the same visibleFractionDigitCount. * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public static class FixedDecimalSamples { /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public final SampleType sampleType; /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public final Set<FixedDecimalRange> samples; /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public final boolean bounded; /** * The samples must be immutable. * @param sampleType * @param samples */ private FixedDecimalSamples(SampleType sampleType, Set<FixedDecimalRange> samples, boolean bounded) { super(); this.sampleType = sampleType; this.samples = samples; this.bounded = bounded; } /* * Parse a list of the form described in CLDR. The source must be trimmed. */ static FixedDecimalSamples parse(String source) { SampleType sampleType2; boolean bounded2 = true; boolean haveBound = false; Set<FixedDecimalRange> samples2 = new LinkedHashSet<FixedDecimalRange>(); if (source.startsWith("integer")) { sampleType2 = SampleType.INTEGER; } else if (source.startsWith("decimal")) { sampleType2 = SampleType.DECIMAL; } else { throw new IllegalArgumentException("Samples must start with 'integer' or 'decimal'"); } source = source.substring(7).trim(); // remove both for (String range : COMMA_SEPARATED.split(source)) { if (range.equals("…") || range.equals("...")) { bounded2 = false; haveBound = true; continue; } if (haveBound) { throw new IllegalArgumentException("Can only have … at the end of samples: " + range); } String[] rangeParts = TILDE_SEPARATED.split(range); switch (rangeParts.length) { case 1: FixedDecimal sample = new FixedDecimal(rangeParts[0]); checkDecimal(sampleType2, sample); samples2.add(new FixedDecimalRange(sample, sample)); break; case 2: FixedDecimal start = new FixedDecimal(rangeParts[0]); FixedDecimal end = new FixedDecimal(rangeParts[1]); checkDecimal(sampleType2, start); checkDecimal(sampleType2, end); samples2.add(new FixedDecimalRange(start, end)); break; default: throw new IllegalArgumentException("Ill-formed number range: " + range); } } return new FixedDecimalSamples(sampleType2, Collections.unmodifiableSet(samples2), bounded2); } private static void checkDecimal(SampleType sampleType2, FixedDecimal sample) { if ((sampleType2 == SampleType.INTEGER) != (sample.getVisibleDecimalDigitCount() == 0)) { throw new IllegalArgumentException("Ill-formed number range: " + sample); } } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public Set<Double> addSamples(Set<Double> result) { for (FixedDecimalRange item : samples) { // we have to convert to longs so we don't get strange double issues long startDouble = item.start.getShiftedValue(); long endDouble = item.end.getShiftedValue(); for (long d = startDouble; d <= endDouble; d += 1) { result.add(d/(double)item.start.baseFactor); } } return result; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU @Override public String toString() { StringBuilder b = new StringBuilder("@").append(sampleType.toString().toLowerCase(Locale.ENGLISH)); boolean first = true; for (FixedDecimalRange item : samples) { if (first) { first = false; } else { b.append(","); } b.append(' ').append(item); } if (!bounded) { b.append(", …"); } return b.toString(); } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public Set<FixedDecimalRange> getSamples() { return samples; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public void getStartEndSamples(Set<FixedDecimal> target) { for (FixedDecimalRange item : samples) { target.add(item.start); target.add(item.end); } } } /* * A constraint on a number. */ private interface Constraint extends Serializable { /* * Returns true if the number fulfills the constraint. * @param n the number to test, >= 0. */ boolean isFulfilled(FixedDecimal n); /* * Returns false if an unlimited number of values fulfills the * constraint. */ boolean isLimited(SampleType sampleType); } private static final boolean isBreakAndIgnore(char c) { return c <= 0x20 && (c == 0x20 || c == 9 || c == 0xa || c == 0xc || c == 0xd); } private static final boolean isBreakAndKeep(char c) { return c <= '=' && c >= '!' && (c == '!' || c == '%' || c == ',' || c == '.' || c == '='); } static class SimpleTokenizer { // static final UnicodeSet BREAK_AND_IGNORE = new UnicodeSet(0x09, 0x0a, 0x0c, 0x0d, 0x20, 0x20).freeze(); // static final UnicodeSet BREAK_AND_KEEP = new UnicodeSet('!', '!', '%', '%', ',', ',', '.', '.', '=', '=').freeze(); static String[] split(String source) { int last = -1; List<String> result = new ArrayList<String>(); for (int i = 0; i < source.length(); ++i) { char ch = source.charAt(i); if (isBreakAndIgnore(ch) /* BREAK_AND_IGNORE.contains(ch) */) { if (last >= 0) { result.add(source.substring(last,i)); last = -1; } } else if (isBreakAndKeep(ch) /* BREAK_AND_KEEP.contains(ch) */) { if (last >= 0) { result.add(source.substring(last,i)); } result.add(source.substring(i,i+1)); last = -1; } else if (last < 0) { last = i; } } if (last >= 0) { result.add(source.substring(last)); } return result.toArray(new String[result.size()]); } } /* * syntax: * condition : or_condition * and_condition * or_condition : and_condition 'or' condition * and_condition : relation * relation 'and' relation * relation : in_relation * within_relation * in_relation : not? expr not? in not? range * within_relation : not? expr not? 'within' not? range * not : 'not' * '!' * expr : 'n' * 'n' mod value * mod : 'mod' * '%' * in : 'in' * 'is' * '=' * '≠' * value : digit+ * digit : 0|1|2|3|4|5|6|7|8|9 * range : value'..'value */ private static Constraint parseConstraint(String description) throws ParseException { Constraint result = null; String[] or_together = OR_SEPARATED.split(description); for (int i = 0; i < or_together.length; ++i) { Constraint andConstraint = null; String[] and_together = AND_SEPARATED.split(or_together[i]); for (int j = 0; j < and_together.length; ++j) { Constraint newConstraint = NO_CONSTRAINT; String condition = and_together[j].trim(); String[] tokens = SimpleTokenizer.split(condition); int mod = 0; boolean inRange = true; boolean integersOnly = true; double lowBound = Long.MAX_VALUE; double highBound = Long.MIN_VALUE; long[] vals = null; int x = 0; String t = tokens[x++]; boolean hackForCompatibility = false; Operand operand; try { operand = FixedDecimal.getOperand(t); } catch (Exception e) { throw unexpected(t, condition); } if (x < tokens.length) { t = tokens[x++]; if ("mod".equals(t) || "%".equals(t)) { mod = Integer.parseInt(tokens[x++]); t = nextToken(tokens, x++, condition); } if ("not".equals(t)) { inRange = !inRange; t = nextToken(tokens, x++, condition); if ("=".equals(t)) { throw unexpected(t, condition); } } else if ("!".equals(t)) { inRange = !inRange; t = nextToken(tokens, x++, condition); if (!"=".equals(t)) { throw unexpected(t, condition); } } if ("is".equals(t) || "in".equals(t) || "=".equals(t)) { hackForCompatibility = "is".equals(t); if (hackForCompatibility && !inRange) { throw unexpected(t, condition); } t = nextToken(tokens, x++, condition); } else if ("within".equals(t)) { integersOnly = false; t = nextToken(tokens, x++, condition); } else { throw unexpected(t, condition); } if ("not".equals(t)) { if (!hackForCompatibility && !inRange) { throw unexpected(t, condition); } inRange = !inRange; t = nextToken(tokens, x++, condition); } List<Long> valueList = new ArrayList<Long>(); // the token t is always one item ahead while (true) { long low = Long.parseLong(t); long high = low; if (x < tokens.length) { t = nextToken(tokens, x++, condition); if (t.equals(".")) { t = nextToken(tokens, x++, condition); if (!t.equals(".")) { throw unexpected(t, condition); } t = nextToken(tokens, x++, condition); high = Long.parseLong(t); if (x < tokens.length) { t = nextToken(tokens, x++, condition); if (!t.equals(",")) { // adjacent number: 1 2 // no separator, fail throw unexpected(t, condition); } } } else if (!t.equals(",")) { // adjacent number: 1 2 // no separator, fail throw unexpected(t, condition); } } // at this point, either we are out of tokens, or t is ',' if (low > high) { throw unexpected(low + "~" + high, condition); } else if (mod != 0 && high >= mod) { throw unexpected(high + ">mod=" + mod, condition); } valueList.add(low); valueList.add(high); lowBound = Math.min(lowBound, low); highBound = Math.max(highBound, high); if (x >= tokens.length) { break; } t = nextToken(tokens, x++, condition); } if (t.equals(",")) { throw unexpected(t, condition); } if (valueList.size() == 2) { vals = null; } else { vals = new long[valueList.size()]; for (int k = 0; k < vals.length; ++k) { vals[k] = valueList.get(k); } } // Hack to exclude "is not 1,2" if (lowBound != highBound && hackForCompatibility && !inRange) { throw unexpected("is not <range>", condition); } newConstraint = new RangeConstraint(mod, inRange, operand, integersOnly, lowBound, highBound, vals); } if (andConstraint == null) { andConstraint = newConstraint; } else { andConstraint = new AndConstraint(andConstraint, newConstraint); } } if (result == null) { result = andConstraint; } else { result = new OrConstraint(result, andConstraint); } } return result; } static final Pattern AT_SEPARATED = Pattern.compile("\\s*\\Q\\E@\\s*"); static final Pattern OR_SEPARATED = Pattern.compile("\\s*or\\s*"); static final Pattern AND_SEPARATED = Pattern.compile("\\s*and\\s*"); static final Pattern COMMA_SEPARATED = Pattern.compile("\\s*,\\s*"); static final Pattern DOTDOT_SEPARATED = Pattern.compile("\\s*\\Q..\\E\\s*"); static final Pattern TILDE_SEPARATED = Pattern.compile("\\s*~\\s*"); static final Pattern SEMI_SEPARATED = Pattern.compile("\\s*;\\s*"); /* Returns a parse exception wrapping the token and context strings. */ private static ParseException unexpected(String token, String context) { return new ParseException("unexpected token '" + token + "' in '" + context + "'", -1); } /* * Returns the token at x if available, else throws a parse exception. */ private static String nextToken(String[] tokens, int x, String context) throws ParseException { if (x < tokens.length) { return tokens[x]; } throw new ParseException("missing token at end of '" + context + "'", -1); } /* * Syntax: * rule : keyword ':' condition * keyword: <identifier> */ private static Rule parseRule(String description) throws ParseException { if (description.length() == 0) { return DEFAULT_RULE; } description = description.toLowerCase(Locale.ENGLISH); int x = description.indexOf(':'); if (x == -1) { throw new ParseException("missing ':' in rule description '" + description + "'", 0); } String keyword = description.substring(0, x).trim(); if (!isValidKeyword(keyword)) { throw new ParseException("keyword '" + keyword + " is not valid", 0); } description = description.substring(x+1).trim(); String[] constraintOrSamples = AT_SEPARATED.split(description); boolean sampleFailure = false; FixedDecimalSamples integerSamples = null, decimalSamples = null; switch (constraintOrSamples.length) { case 1: break; case 2: integerSamples = FixedDecimalSamples.parse(constraintOrSamples[1]); if (integerSamples.sampleType == SampleType.DECIMAL) { decimalSamples = integerSamples; integerSamples = null; } break; case 3: integerSamples = FixedDecimalSamples.parse(constraintOrSamples[1]); decimalSamples = FixedDecimalSamples.parse(constraintOrSamples[2]); if (integerSamples.sampleType != SampleType.INTEGER || decimalSamples.sampleType != SampleType.DECIMAL) { throw new IllegalArgumentException("Must have @integer then @decimal in " + description); } break; default: throw new IllegalArgumentException("Too many samples in " + description); } if (sampleFailure) { throw new IllegalArgumentException("Ill-formed samples—'@' characters."); } // 'other' is special, and must have no rules; all other keywords must have rules. boolean isOther = keyword.equals("other"); if (isOther != (constraintOrSamples[0].length() == 0)) { throw new IllegalArgumentException("The keyword 'other' must have no constraints, just samples."); } Constraint constraint; if (isOther) { constraint = NO_CONSTRAINT; } else { constraint = parseConstraint(constraintOrSamples[0]); } return new Rule(keyword, constraint, integerSamples, decimalSamples); } /* * Syntax: * rules : rule * rule ';' rules */ private static RuleList parseRuleChain(String description) throws ParseException { RuleList result = new RuleList(); // remove trailing ; if (description.endsWith(";")) { description = description.substring(0,description.length()-1); } String[] rules = SEMI_SEPARATED.split(description); for (int i = 0; i < rules.length; ++i) { Rule rule = parseRule(rules[i].trim()); result.hasExplicitBoundingInfo |= rule.integerSamples != null || rule.decimalSamples != null; result.addRule(rule); } return result.finish(); } /* * An implementation of Constraint representing a modulus, * a range of values, and include/exclude. Provides lots of * convenience factory methods. */ private static class RangeConstraint implements Constraint, Serializable { private static final long serialVersionUID = 1; private final int mod; private final boolean inRange; private final boolean integersOnly; private final double lowerBound; private final double upperBound; private final long[] range_list; private final Operand operand; RangeConstraint(int mod, boolean inRange, Operand operand, boolean integersOnly, double lowBound, double highBound, long[] vals) { this.mod = mod; this.inRange = inRange; this.integersOnly = integersOnly; this.lowerBound = lowBound; this.upperBound = highBound; this.range_list = vals; this.operand = operand; } @Override public boolean isFulfilled(FixedDecimal number) { double n = number.get(operand); if ((integersOnly && (n - (long)n) != 0.0) || (operand == Operand.j && number.visibleDecimalDigitCount != 0)) { return !inRange; } if (mod != 0) { n = n % mod; // java % handles double numerator the way we want } boolean test = n >= lowerBound && n <= upperBound; if (test && range_list != null) { test = false; for (int i = 0; !test && i < range_list.length; i += 2) { test = n >= range_list[i] && n <= range_list[i+1]; } } return inRange == test; } @Override public boolean isLimited(SampleType sampleType) { boolean valueIsZero = lowerBound == upperBound && lowerBound == 0d; boolean hasDecimals = (operand == Operand.v || operand == Operand.w || operand == Operand.f || operand == Operand.t) && inRange != valueIsZero; // either NOT f = zero or f = non-zero switch (sampleType) { case INTEGER: return hasDecimals // will be empty || ((operand == Operand.n || operand == Operand.i || operand == Operand.j) && mod == 0 && inRange); case DECIMAL: return (!hasDecimals || operand == Operand.n || operand == Operand.j) && (integersOnly || lowerBound == upperBound) && mod == 0 && inRange; } return false; } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append(operand); if (mod != 0) { result.append(" % ").append(mod); } boolean isList = lowerBound != upperBound; result.append( !isList ? (inRange ? " = " : " != ") : integersOnly ? (inRange ? " = " : " != ") : (inRange ? " within " : " not within ") ); if (range_list != null) { for (int i = 0; i < range_list.length; i += 2) { addRange(result, range_list[i], range_list[i+1], i != 0); } } else { addRange(result, lowerBound, upperBound, false); } return result.toString(); } } private static void addRange(StringBuilder result, double lb, double ub, boolean addSeparator) { if (addSeparator) { result.append(","); } if (lb == ub) { result.append(format(lb)); } else { result.append(format(lb) + ".." + format(ub)); } } private static String format(double lb) { long lbi = (long) lb; return lb == lbi ? String.valueOf(lbi) : String.valueOf(lb); } /* Convenience base class for and/or constraints. */ private static abstract class BinaryConstraint implements Constraint, Serializable { private static final long serialVersionUID = 1; protected final Constraint a; protected final Constraint b; protected BinaryConstraint(Constraint a, Constraint b) { this.a = a; this.b = b; } } /* A constraint representing the logical and of two constraints. */ private static class AndConstraint extends BinaryConstraint { private static final long serialVersionUID = 7766999779862263523L; AndConstraint(Constraint a, Constraint b) { super(a, b); } @Override public boolean isFulfilled(FixedDecimal n) { return a.isFulfilled(n) && b.isFulfilled(n); } @Override public boolean isLimited(SampleType sampleType) { // we ignore the case where both a and b are unlimited but no values // satisfy both-- we still consider this 'unlimited' return a.isLimited(sampleType) || b.isLimited(sampleType); } @Override public String toString() { return a.toString() + " and " + b.toString(); } } /* A constraint representing the logical or of two constraints. */ private static class OrConstraint extends BinaryConstraint { private static final long serialVersionUID = 1405488568664762222L; OrConstraint(Constraint a, Constraint b) { super(a, b); } @Override public boolean isFulfilled(FixedDecimal n) { return a.isFulfilled(n) || b.isFulfilled(n); } @Override public boolean isLimited(SampleType sampleType) { return a.isLimited(sampleType) && b.isLimited(sampleType); } @Override public String toString() { return a.toString() + " or " + b.toString(); } } /* * Implementation of Rule that uses a constraint. * Provides 'and' and 'or' to combine constraints. Immutable. */ private static class Rule implements Serializable { private static final long serialVersionUID = 1; private final String keyword; private final Constraint constraint; private final FixedDecimalSamples integerSamples; private final FixedDecimalSamples decimalSamples; public Rule(String keyword, Constraint constraint, FixedDecimalSamples integerSamples, FixedDecimalSamples decimalSamples) { this.keyword = keyword; this.constraint = constraint; this.integerSamples = integerSamples; this.decimalSamples = decimalSamples; } @SuppressWarnings("unused") public Rule and(Constraint c) { return new Rule(keyword, new AndConstraint(constraint, c), integerSamples, decimalSamples); } @SuppressWarnings("unused") public Rule or(Constraint c) { return new Rule(keyword, new OrConstraint(constraint, c), integerSamples, decimalSamples); } public String getKeyword() { return keyword; } public boolean appliesTo(FixedDecimal n) { return constraint.isFulfilled(n); } public boolean isLimited(SampleType sampleType) { return constraint.isLimited(sampleType); } @Override public String toString() { return keyword + ": " + constraint.toString() + (integerSamples == null ? "" : " " + integerSamples.toString()) + (decimalSamples == null ? "" : " " + decimalSamples.toString()); } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU @Override public int hashCode() { return keyword.hashCode() ^ constraint.hashCode(); } public String getConstraint() { return constraint.toString(); } } private static class RuleList implements Serializable { private boolean hasExplicitBoundingInfo = false; private static final long serialVersionUID = 1; private final List<Rule> rules = new ArrayList<Rule>(); public RuleList addRule(Rule nextRule) { String keyword = nextRule.getKeyword(); for (Rule rule : rules) { if (keyword.equals(rule.getKeyword())) { throw new IllegalArgumentException("Duplicate keyword: " + keyword); } } rules.add(nextRule); return this; } public RuleList finish() throws ParseException { // make sure that 'other' is present, and at the end. Rule otherRule = null; for (Iterator<Rule> it = rules.iterator(); it.hasNext();) { Rule rule = it.next(); if ("other".equals(rule.getKeyword())) { otherRule = rule; it.remove(); } } if (otherRule == null) { otherRule = parseRule("other:"); // make sure we have always have an 'other' a rule } rules.add(otherRule); return this; } private Rule selectRule(FixedDecimal n) { for (Rule rule : rules) { if (rule.appliesTo(n)) { return rule; } } return null; } public String select(FixedDecimal n) { if (Double.isInfinite(n.source) || Double.isNaN(n.source)) { return KEYWORD_OTHER; } Rule r = selectRule(n); return r.getKeyword(); } public Set<String> getKeywords() { Set<String> result = new LinkedHashSet<String>(); for (Rule rule : rules) { result.add(rule.getKeyword()); } // since we have explicit 'other', we don't need this. //result.add(KEYWORD_OTHER); return result; } public boolean isLimited(String keyword, SampleType sampleType) { if (hasExplicitBoundingInfo) { FixedDecimalSamples mySamples = getDecimalSamples(keyword, sampleType); return mySamples == null ? true : mySamples.bounded; } return computeLimited(keyword, sampleType); } public boolean computeLimited(String keyword, SampleType sampleType) { // if all rules with this keyword are limited, it's limited, // and if there's no rule with this keyword, it's unlimited boolean result = false; for (Rule rule : rules) { if (keyword.equals(rule.getKeyword())) { if (!rule.isLimited(sampleType)) { return false; } result = true; } } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (Rule rule : rules) { if (builder.length() != 0) { builder.append(CATEGORY_SEPARATOR); } builder.append(rule); } return builder.toString(); } public String getRules(String keyword) { for (Rule rule : rules) { if (rule.getKeyword().equals(keyword)) { return rule.getConstraint(); } } return null; } public boolean select(FixedDecimal sample, String keyword) { for (Rule rule : rules) { if (rule.getKeyword().equals(keyword) && rule.appliesTo(sample)) { return true; } } return false; } public FixedDecimalSamples getDecimalSamples(String keyword, SampleType sampleType) { for (Rule rule : rules) { if (rule.getKeyword().equals(keyword)) { return sampleType == SampleType.INTEGER ? rule.integerSamples : rule.decimalSamples; } } return null; } } /** * This API is ICU internal only. * icu_annot::internal */ // @Deprecated: in fact internal ICU public enum StandardPluralCategories { /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU zero, /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU one, /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU two, /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU few, /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU many, /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU other; static StandardPluralCategories forString(String s) { StandardPluralCategories a; try { a = valueOf(s); } catch (Exception e) { return null; } return a; } } @SuppressWarnings("unused") private boolean addConditional(Set<FixedDecimal> toAddTo, Set<FixedDecimal> others, double trial) { boolean added; FixedDecimal toAdd = new FixedDecimal(trial); if (!toAddTo.contains(toAdd) && !others.contains(toAdd)) { others.add(toAdd); added = true; } else { added = false; } return added; } // ------------------------------------------------------------------------- // Static class methods. // ------------------------------------------------------------------------- /** * Provides access to the predefined cardinal-number <code>PluralRules</code> for a given * locale. * Same as forLocale(locale, PluralType.CARDINAL). * * <p>ICU defines plural rules for many locales based on CLDR <i>Language Plural Rules</i>. * For these predefined rules, see CLDR page at * http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * * @param locale The locale for which a <code>PluralRules</code> object is * returned. * @return The predefined <code>PluralRules</code> object for this locale. * If there's no predefined rules for this locale, the rules * for the closest parent in the locale hierarchy that has one will * be returned. The final fallback always returns the default * rules. * icu_annot::stable ICU 3.8 */ public static PluralRules forLocale(Locale locale) { return forLocale(locale, PluralType.CARDINAL); } /** * Provides access to the predefined <code>PluralRules</code> for a given * locale and the plural type. * * <p>ICU defines plural rules for many locales based on CLDR <i>Language Plural Rules</i>. * For these predefined rules, see CLDR page at * http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * * @param locale The locale for which a <code>PluralRules</code> object is * returned. * @param type The plural type (e.g., cardinal or ordinal). * @return The predefined <code>PluralRules</code> object for this locale. * If there's no predefined rules for this locale, the rules * for the closest parent in the locale hierarchy that has one will * be returned. The final fallback always returns the default * rules. * icu_annot::stable ICU 50 */ public static PluralRules forLocale(Locale locale, PluralType type) { return Factory.getDefaultFactory().forLocale(locale, type); } /* * Checks whether a token is a valid keyword. * * @param token the token to be checked * @return true if the token is a valid keyword. */ private static boolean isValidKeyword(String token) { // return ALLOWED_ID.containsAll(token); for (int i = 0; i < token.length(); ++i) { char c = token.charAt(i); if (!('a' <= c && c <= 'z')) { return false; } } return true; } /* * Creates a new <code>PluralRules</code> object. Immutable. */ private PluralRules(RuleList rules) { this.rules = rules; this.keywords = Collections.unmodifiableSet(rules.getKeywords()); } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU @Override public int hashCode() { return rules.hashCode(); } /** * Given a number, returns the keyword of the first rule that applies to * the number. * * @param number The number for which the rule has to be determined. * @return The keyword of the selected rule. * icu_annot::stable ICU 4.0 */ public String select(double number) { return rules.select(new FixedDecimal(number)); } /** * Given a number, returns the keyword of the first rule that applies to * the number. * * @param number The number for which the rule has to be determined. * @return The keyword of the selected rule. * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public String select(double number, int countVisibleFractionDigits, long fractionaldigits) { return rules.select(new FixedDecimal(number, countVisibleFractionDigits, fractionaldigits)); } /** * Given a number information, returns the keyword of the first rule that applies to * the number. * * @param sample The number information for which the rule has to be determined. * @return The keyword of the selected rule. * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public String select(FixedDecimal sample) { return rules.select(sample); } /** * Given a number information, and keyword, return whether the keyword would match the number. * * @param sample The number information for which the rule has to be determined. * @param keyword The keyword to filter on * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public boolean matches(FixedDecimal sample, String keyword) { return rules.select(sample, keyword); } /** * Returns a set of all rule keywords used in this <code>PluralRules</code> * object. The rule "other" is always present by default. * * @return The set of keywords. * icu_annot::stable ICU 3.8 */ public Set<String> getKeywords() { return keywords; } /** * Returns the unique value that this keyword matches, or {@link #NO_UNIQUE_VALUE} * if the keyword matches multiple values or is not defined for this PluralRules. * * @param keyword the keyword to check for a unique value * @return The unique value for the keyword, or NO_UNIQUE_VALUE. * icu_annot::stable ICU 4.8 */ public double getUniqueKeywordValue(String keyword) { Collection<Double> values = getAllKeywordValues(keyword); if (values != null && values.size() == 1) { return values.iterator().next(); } return NO_UNIQUE_VALUE; } /** * Returns all the values that trigger this keyword, or null if the number of such * values is unlimited. * * @param keyword the keyword * @return the values that trigger this keyword, or null. The returned collection * is immutable. It will be empty if the keyword is not defined. * icu_annot::stable ICU 4.8 */ public Collection<Double> getAllKeywordValues(String keyword) { return getAllKeywordValues(keyword, SampleType.INTEGER); } /** * Returns all the values that trigger this keyword, or null if the number of such * values is unlimited. * * @param keyword the keyword * @param type the type of samples requested, INTEGER or DECIMAL * @return the values that trigger this keyword, or null. The returned collection * is immutable. It will be empty if the keyword is not defined. * * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public Collection<Double> getAllKeywordValues(String keyword, SampleType type) { if (!isLimited(keyword, type)) { return null; } Collection<Double> samples = getSamples(keyword, type); return samples == null ? null : Collections.unmodifiableCollection(samples); } /** * Returns a list of integer values for which select() would return that keyword, * or null if the keyword is not defined. The returned collection is unmodifiable. * The returned list is not complete, and there might be additional values that * would return the keyword. * * @param keyword the keyword to test * @return a list of values matching the keyword. * icu_annot::stable ICU 4.8 */ public Collection<Double> getSamples(String keyword) { return getSamples(keyword, SampleType.INTEGER); } /** * Returns a list of values for which select() would return that keyword, * or null if the keyword is not defined. * The returned collection is unmodifiable. * The returned list is not complete, and there might be additional values that * would return the keyword. The keyword might be defined, and yet have an empty set of samples, * IF there are samples for the other sampleType. * * @param keyword the keyword to test * @param sampleType the type of samples requested, INTEGER or DECIMAL * @return a list of values matching the keyword. * icu_annot::internal * @deprecated ICU internal only */ // @Deprecated: in fact internal ICU public Collection<Double> getSamples(String keyword, SampleType sampleType) { if (!keywords.contains(keyword)) { return null; } Set<Double> result = new TreeSet<Double>(); if (rules.hasExplicitBoundingInfo) { FixedDecimalSamples samples = rules.getDecimalSamples(keyword, sampleType); return samples == null ? Collections.unmodifiableSet(result) : Collections.unmodifiableSet(samples.addSamples(result)); } // hack in case the rule is created without explicit samples int maxCount = isLimited(keyword, sampleType) ? Integer.MAX_VALUE : 20; switch (sampleType) { case INTEGER: for (int i = 0; i < 200; ++i) { if (!addSample(keyword, i, maxCount, result)) { break; } } addSample(keyword, 1000000, maxCount, result); // hack for Welsh break; case DECIMAL: for (int i = 0; i < 2000; ++i) { if (!addSample(keyword, new FixedDecimal(i/10d, 1), maxCount, result)) { break; } } addSample(keyword, new FixedDecimal(1000000d, 1), maxCount, result); // hack for Welsh break; } return result.size() == 0 ? null : Collections.unmodifiableSet(result); } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public boolean addSample(String keyword, Number sample, int maxCount, Set<Double> result) { String selectedKeyword = sample instanceof FixedDecimal ? select((FixedDecimal)sample) : select(sample.doubleValue()); if (selectedKeyword.equals(keyword)) { result.add(sample.doubleValue()); if (--maxCount < 0) { return false; } } return true; } /** * Returns a list of values for which select() would return that keyword, * or null if the keyword is not defined or no samples are available. * The returned collection is unmodifiable. * The returned list is not complete, and there might be additional values that * would return the keyword. * * @param keyword the keyword to test * @param sampleType the type of samples requested, INTEGER or DECIMAL * @return a list of values matching the keyword. * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public FixedDecimalSamples getDecimalSamples(String keyword, SampleType sampleType) { return rules.getDecimalSamples(keyword, sampleType); } /** * Returns the set of locales for which PluralRules are known. * @return the set of locales for which PluralRules are known, as a list * icu_annot::draft ICU 4.2 * icu_annot::provisional This API might change or be removed in a future release. public static ULocale[] getAvailableULocales() { return Factory.getDefaultFactory().getAvailableULocales(); } */ /** * Returns the 'functionally equivalent' locale with respect to * plural rules. Calling PluralRules.forLocale with the functionally equivalent * locale, and with the provided locale, returns rules that behave the same. * <br/> * All locales with the same functionally equivalent locale have * plural rules that behave the same. This is not exhaustive; * there may be other locales whose plural rules behave the same * that do not have the same equivalent locale. * * @param locale the locale to check * @param isAvailable if not null and of length > 0, this will hold 'true' at * index 0 if locale is directly defined (without fallback) as having plural rules * @return the functionally-equivalent locale * icu_annot::draft ICU 4.2 * icu_annot::provisional This API might change or be removed in a future release. public static ULocale getFunctionalEquivalent(ULocale locale, boolean[] isAvailable) { return Factory.getDefaultFactory().getFunctionalEquivalent(locale, isAvailable); } */ /** * {@inheritDoc} * icu_annot::stable ICU 3.8 */ @Override public String toString() { return rules.toString(); } /** * {@inheritDoc} * icu_annot::stable ICU 3.8 */ @Override public boolean equals(Object rhs) { // return rhs instanceof PluralRules && equals((PluralRules)rhs); return rhs instanceof PluralRules && toString().equals(rhs.toString()); } /** * Returns true if rhs is equal to this. * @param rhs the PluralRules to compare to. * @return true if this and rhs are equal. * icu_annot::stable ICU 3.8 */ // TODO Optimize this // public boolean equals(PluralRules rhs) { // return rhs != null && toString().equals(rhs.toString()); // } /** * Status of the keyword for the rules, given a set of explicit values. * * icu_annot::draft ICU 50 * icu_annot::provisional This API might change or be removed in a future release. */ public enum KeywordStatus { /** * The keyword is not valid for the rules. * * icu_annot::draft ICU 50 * icu_annot::provisional This API might change or be removed in a future release. */ INVALID, /** * The keyword is valid, but unused (it is covered by the explicit values, OR has no values for the given {@link SampleType}). * * icu_annot::draft ICU 50 * icu_annot::provisional This API might change or be removed in a future release. */ SUPPRESSED, /** * The keyword is valid, used, and has a single possible value (before considering explicit values). * * icu_annot::draft ICU 50 * icu_annot::provisional This API might change or be removed in a future release. */ UNIQUE, /** * The keyword is valid, used, not unique, and has a finite set of values. * * icu_annot::draft ICU 50 * icu_annot::provisional This API might change or be removed in a future release. */ BOUNDED, /** * The keyword is valid but not bounded; there indefinitely many matching values. * * icu_annot::draft ICU 50 * icu_annot::provisional This API might change or be removed in a future release. */ UNBOUNDED } /** * Find the status for the keyword, given a certain set of explicit values. * * @param keyword * the particular keyword (call rules.getKeywords() to get the valid ones) * @param offset * the offset used, or 0.0d if not. Internally, the offset is subtracted from each explicit value before * checking against the keyword values. * @param explicits * a set of Doubles that are used explicitly (eg [=0], "[=1]"). May be empty or null. * @param uniqueValue * If non null, set to the unique value. * @return the KeywordStatus * icu_annot::draft ICU 50 * icu_annot::provisional This API might change or be removed in a future release. */ public KeywordStatus getKeywordStatus(String keyword, int offset, Set<Double> explicits, Output<Double> uniqueValue) { return getKeywordStatus(keyword, offset, explicits, uniqueValue, SampleType.INTEGER); } /** * Find the status for the keyword, given a certain set of explicit values. * * @param keyword * the particular keyword (call rules.getKeywords() to get the valid ones) * @param offset * the offset used, or 0.0d if not. Internally, the offset is subtracted from each explicit value before * checking against the keyword values. * @param explicits * a set of Doubles that are used explicitly (eg [=0], "[=1]"). May be empty or null. * @param sampleType * request KeywordStatus relative to INTEGER or DECIMAL values * @param uniqueValue * If non null, set to the unique value. * @return the KeywordStatus * icu_annot::internal * icu_annot::provisional This API might change or be removed in a future release. */ public KeywordStatus getKeywordStatus(String keyword, int offset, Set<Double> explicits, Output<Double> uniqueValue, SampleType sampleType) { if (uniqueValue != null) { uniqueValue.value = null; } if (!keywords.contains(keyword)) { return KeywordStatus.INVALID; } if (!isLimited(keyword, sampleType)) { return KeywordStatus.UNBOUNDED; } Collection<Double> values = getSamples(keyword, sampleType); int originalSize = values.size(); if (explicits == null) { explicits = Collections.emptySet(); } // Quick check on whether there are multiple elements if (originalSize > explicits.size()) { if (originalSize == 1) { if (uniqueValue != null) { uniqueValue.value = values.iterator().next(); } return KeywordStatus.UNIQUE; } return KeywordStatus.BOUNDED; } // Compute if the quick test is insufficient. HashSet<Double> subtractedSet = new HashSet<Double>(values); for (Double explicit : explicits) { subtractedSet.remove(explicit - offset); } if (subtractedSet.size() == 0) { return KeywordStatus.SUPPRESSED; } if (uniqueValue != null && subtractedSet.size() == 1) { uniqueValue.value = subtractedSet.iterator().next(); } return originalSize == 1 ? KeywordStatus.UNIQUE : KeywordStatus.BOUNDED; } /** * icu_annot::internal * This API is ICU internal only. */ // @Deprecated: in fact internal ICU public String getRules(String keyword) { return rules.getRules(keyword); } /* private void writeObject( ObjectOutputStream out) throws IOException { throw new NotSerializableException(); } private void readObject(ObjectInputStream in ) throws IOException, ClassNotFoundException { throw new NotSerializableException(); } private Object writeReplace() throws ObjectStreamException { return new PluralRulesSerialProxy(toString()); } */ /** * icu_annot::internal * @deprecated internal */ // @Deprecated: in fact internal ICU public int compareTo(PluralRules other) { return toString().compareTo(other.toString()); } /** * icu_annot::internal * @deprecated internal */ // @Deprecated: in fact internal ICU public Boolean isLimited(String keyword) { return rules.isLimited(keyword, SampleType.INTEGER); } /** * icu_annot::internal * @deprecated internal */ // @Deprecated: in fact internal ICU public boolean isLimited(String keyword, SampleType sampleType) { return rules.isLimited(keyword, sampleType); } /** * icu_annot::internal * @deprecated internal */ // @Deprecated: in fact internal ICU public boolean computeLimited(String keyword, SampleType sampleType) { return rules.computeLimited(keyword, sampleType); } }
/** * Utility classes for evaluating policies and requests */ package com.raytheon.uf.edex.registry.acp.xacml.util;
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.sql.parser.sql.statement.dal.dialect.mysql; import org.apache.shardingsphere.sql.parser.sql.statement.dal.DALStatement; /** * Show databases statement. * * @author zhangliang */ public final class ShowDatabasesStatement extends DALStatement { }
/* * Copyright 2002-2018 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.beans.factory.support; import java.security.AccessControlContext; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCurrentlyInCreationException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.FactoryBeanNotInitializedException; import org.springframework.lang.Nullable; /** * Support base class for singleton registries which need to handle * {@link org.springframework.beans.factory.FactoryBean} instances, * integrated with {@link DefaultSingletonBeanRegistry}'s singleton management. * * <p>Serves as base class for {@link AbstractBeanFactory}. * * @author Juergen Hoeller * @since 2.5.1 */ public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry { /** Cache of singleton objects created by FactoryBeans: FactoryBean name to object. */ private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>(16); /** * Determine the type for the given FactoryBean. * @param factoryBean the FactoryBean instance to check * @return the FactoryBean's object type, * or {@code null} if the type cannot be determined yet */ @Nullable protected Class<?> getTypeForFactoryBean(final FactoryBean<?> factoryBean) { try { if (System.getSecurityManager() != null) { return AccessController.doPrivileged((PrivilegedAction<Class<?>>) factoryBean::getObjectType, getAccessControlContext()); } else { return factoryBean.getObjectType(); } } catch (Throwable ex) { // Thrown from the FactoryBean's getObjectType implementation. logger.info("FactoryBean threw exception from getObjectType, despite the contract saying " + "that it should return null if the type of its object cannot be determined yet", ex); return null; } } /** * Obtain an object to expose from the given FactoryBean, if available * in cached form. Quick check for minimal synchronization. * @param beanName the name of the bean * @return the object obtained from the FactoryBean, * or {@code null} if not available */ @Nullable protected Object getCachedObjectForFactoryBean(String beanName) { return this.factoryBeanObjectCache.get(beanName); } /** * Obtain an object to expose from the given FactoryBean. * @param factory the FactoryBean instance * @param beanName the name of the bean * @param shouldPostProcess whether the bean is subject to post-processing * @return the object obtained from the FactoryBean * @throws BeanCreationException if FactoryBean object creation failed * @see org.springframework.beans.factory.FactoryBean#getObject() */ protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) { /* * FactoryBean 也有单例和非单例之分,针对不同类型的 FactoryBean,这里有两种处理方式: * 1. 单例 FactoryBean 生成的 bean 实例也认为是单例类型。需放入缓存中,供后续重复使用 * 2. 非单例 FactoryBean 生成的 bean 实例则不会被放入缓存中,每次都会创建新的实例 */ if (factory.isSingleton() && containsSingleton(beanName)) { synchronized (getSingletonMutex()) { Object object = this.factoryBeanObjectCache.get(beanName); if (object == null) { //这里调用 FactoryBean.getObject() object = doGetObjectFromFactoryBean(factory, beanName); // Only post-process and store if not put there already during getObject() call above // (e.g. because of circular reference processing triggered by custom getBean calls) Object alreadyThere = this.factoryBeanObjectCache.get(beanName); if (alreadyThere != null) { object = alreadyThere; } else { if (shouldPostProcess) { // shouldPostProcess 等价于上一个方法中的 !synthetic,用于表示是否应用后置处理 if (isSingletonCurrentlyInCreation(beanName)) { // Temporarily return non-post-processed object, not storing it yet.. return object; } //加入singletonsCurrentlyInCreation 中(保存当前正在创建的类) beforeSingletonCreation(beanName); try { object = postProcessObjectFromFactoryBean(object, beanName); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Post-processing of FactoryBean's singleton object failed", ex); } finally { //移除singletonsCurrentlyInCreation中的beanName afterSingletonCreation(beanName); } } if (containsSingleton(beanName)) {//放入缓存 this.factoryBeanObjectCache.put(beanName, object); } } } return object; } } else { Object object = doGetObjectFromFactoryBean(factory, beanName); if (shouldPostProcess) { try { object = postProcessObjectFromFactoryBean(object, beanName); } catch (Throwable ex) { throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex); } } return object; } } /** * Obtain an object to expose from the given FactoryBean. * @param factory the FactoryBean instance * @param beanName the name of the bean * @return the object obtained from the FactoryBean * @throws BeanCreationException if FactoryBean object creation failed * @see org.springframework.beans.factory.FactoryBean#getObject() */ private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, final String beanName) throws BeanCreationException { Object object; try { if (System.getSecurityManager() != null) { AccessControlContext acc = getAccessControlContext(); try { object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { //调用接口方法创建bean object = factory.getObject(); } } catch (FactoryBeanNotInitializedException ex) { throw new BeanCurrentlyInCreationException(beanName, ex.toString()); } catch (Throwable ex) { throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex); } // Do not accept a null value for a FactoryBean that's not fully // initialized yet: Many FactoryBeans just return null then. if (object == null) { if (isSingletonCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException( beanName, "FactoryBean which is currently in creation returned null from getObject"); } object = new NullBean(); } return object; } /** * Post-process the given object that has been obtained from the FactoryBean. * The resulting object will get exposed for bean references. * <p>The default implementation simply returns the given object as-is. * Subclasses may override this, for example, to apply post-processors. * @param object the object obtained from the FactoryBean. * @param beanName the name of the bean * @return the object to expose * @throws org.springframework.beans.BeansException if any post-processing failed */ protected Object postProcessObjectFromFactoryBean(Object object, String beanName) throws BeansException { return object; } /** * Get a FactoryBean for the given bean if possible. * @param beanName the name of the bean * @param beanInstance the corresponding bean instance * @return the bean instance as FactoryBean * @throws BeansException if the given bean cannot be exposed as a FactoryBean */ protected FactoryBean<?> getFactoryBean(String beanName, Object beanInstance) throws BeansException { if (!(beanInstance instanceof FactoryBean)) { throw new BeanCreationException(beanName, "Bean instance of type [" + beanInstance.getClass() + "] is not a FactoryBean"); } return (FactoryBean<?>) beanInstance; } /** * Overridden to clear the FactoryBean object cache as well. */ @Override protected void removeSingleton(String beanName) { synchronized (getSingletonMutex()) { super.removeSingleton(beanName); this.factoryBeanObjectCache.remove(beanName); } } /** * Overridden to clear the FactoryBean object cache as well. */ @Override protected void clearSingletonCache() { synchronized (getSingletonMutex()) { super.clearSingletonCache(); this.factoryBeanObjectCache.clear(); } } /** * Return the security context for this bean factory. If a security manager * is set, interaction with the user code will be executed using the privileged * of the security context returned by this method. * @see AccessController#getContext() */ protected AccessControlContext getAccessControlContext() { return AccessController.getContext(); } }
package rocks.juergen.maven.jythonplugin; /* * Copyright 2016 Juergen Edelbluth * * 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. */ import org.apache.maven.plugin.AbstractMojo; import org.junit.Test; import java.io.File; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public abstract class AbstractMojoPomTest extends AbstractMojoTest { private final File pom; private final String expectation; private final String goal; AbstractMojoPomTest(final String pom, final String expectation, final String goal) { this.pom = new File(TestInlineScriptExecutionMojo.class.getResource(String.format("poms/%s", pom)).getFile()); this.expectation = expectation; this.goal = goal; } @Test public void test() throws Exception { final AbstractMojo mojo = (AbstractMojo) rule.lookupMojo(goal, pom); assertNotNull(mojo); mojo.execute(); assertEquals(expectation, getStdOutErr().getLocalStdOut().toString().trim()); assertEquals("", getStdOutErr().getLocalStdErr().toString()); } }
/* Licensed to Diennea S.r.l. under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Diennea S.r.l. 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 herddb.cluster; import herddb.log.CommitLog; import herddb.log.CommitLogManager; import herddb.log.LogNotAvailableException; import herddb.server.ServerConfiguration; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.zookeeper.KeeperException; /** * CommitLog on Apache BookKeeper * * @author enrico.olivelli */ public class BookkeeperCommitLogManager extends CommitLogManager { private final ZookeeperMetadataStorageManager metadataStorageManager; private int ensemble = 1; private int writeQuorumSize = 1; private int ackQuorumSize = 1; private BookKeeper bookKeeper; private final ClientConfiguration config; private long ledgersRetentionPeriod = 1000 * 60 * 60 * 24; public BookkeeperCommitLogManager(ZookeeperMetadataStorageManager metadataStorageManager, ServerConfiguration serverConfiguration) { config = new ClientConfiguration(); config.setThrottleValue(0); config.setEnsemblePlacementPolicy(PreferLocalBookiePlacementPolicy.class); for (String key : serverConfiguration.keys()) { if (key.startsWith("bookie.")) { String _key = key.substring("bookie.".length()); String value = serverConfiguration.getString(key, null); LOG.log(Level.SEVERE, "Setting BookKeeper client configuration: {0}={1}", new Object[]{_key, value}); config.setProperty(_key, value); } } this.metadataStorageManager = metadataStorageManager; } @Override public void start() throws LogNotAvailableException { try { this.bookKeeper = BookKeeper .forConfig(config) .setZookeeper(metadataStorageManager.getZooKeeper()) .build(); } catch (IOException | InterruptedException | KeeperException t) { close(); throw new LogNotAvailableException(t); } } @Override public void close() { if (bookKeeper != null) { try { bookKeeper.close(); } catch (InterruptedException | BKException ex) { LOG.log(Level.SEVERE, null, ex); } } } private static final Logger LOG = Logger.getLogger(BookkeeperCommitLogManager.class.getName()); public int getEnsemble() { return ensemble; } public void setEnsemble(int ensemble) { this.ensemble = ensemble; } public int getWriteQuorumSize() { return writeQuorumSize; } public void setWriteQuorumSize(int writeQuorumSize) { this.writeQuorumSize = writeQuorumSize; } public int getAckQuorumSize() { return ackQuorumSize; } public void setAckQuorumSize(int ackQuorumSize) { this.ackQuorumSize = ackQuorumSize; } public long getLedgersRetentionPeriod() { return ledgersRetentionPeriod; } public void setLedgersRetentionPeriod(long ledgersRetentionPeriod) { this.ledgersRetentionPeriod = ledgersRetentionPeriod; } @Override public CommitLog createCommitLog(String tableSpace) throws LogNotAvailableException { BookkeeperCommitLog res = new BookkeeperCommitLog(tableSpace, metadataStorageManager, bookKeeper); res.setAckQuorumSize(ackQuorumSize); res.setEnsemble(ensemble); res.setLedgersRetentionPeriod(ledgersRetentionPeriod); res.setWriteQuorumSize(writeQuorumSize); return res; } }
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * 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.spongepowered.common.mixin.plugin; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.common.SpongeImpl; import java.util.List; import java.util.Set; public class ConcurrentChecksPlugin implements IMixinConfigPlugin { @Override public void onLoad(String mixinPackage) { } @Override public String getRefMapperConfig() { return null; } @Override public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { if (mixinClassName.equals("org.spongepowered.common.mixin.concurrentchecks.MixinClassInheritanceMultiMap")) { return SpongeImpl.getGlobalConfig().getConfig().getDebug().doConcurrentEntityChecks(); } else if (mixinClassName.equals("org.spongepowered.common.mixin.concurrentchecks.MixinPlayerChunkMap_ConcurrentChecks")) { return SpongeImpl.getGlobalConfig().getConfig().getDebug().doConcurrentChunkMapChecks(); } return true; } @Override public void acceptTargets(Set<String> myTargets, Set<String> otherTargets) { } @Override public List<String> getMixins() { return null; } @Override public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { } @Override public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { } }
package org.starfishrespect.myconsumption.server.business.sensors.flukso; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.ArrayList; /** * Simple storage class used to get informations about a sensor on the * Flukso API * S23Y (2015). Licensed under the Apache License, Version 2.0. */ @JsonIgnoreProperties(ignoreUnknown = true) public class FluksoParams { String type; @JsonProperty("function") String name; @JsonProperty("class") String sensorClass; int voltage, current, phase, enabled; @JsonProperty("lastupdate") ArrayList<Integer> lastUpdate; public String getType() { return type; } public String getName() { return name; } public String getSensorClass() { return sensorClass; } public int getVoltage() { return voltage; } public int getCurrent() { return current; } public int getPhase() { return phase; } public int getEnabled() { return enabled; } public ArrayList<Integer> getLastUpdate() { return lastUpdate; } @Override public String toString() { return "FluksoParams{" + "type='" + type + '\'' + ", name='" + name + '\'' + ", sensorClass='" + sensorClass + '\'' + ", voltage=" + voltage + ", current=" + current + ", phase=" + phase + ", enabled=" + enabled + ", lastUpdate=" + lastUpdate + '}'; } }
package net.minecraft.world; import net.minecraft.entity.player.PlayerCapabilities; import net.minecraft.world.storage.WorldInfo; public final class WorldSettings { /** * The seed for the map. */ private final long seed; /** * The EnumGameType. */ private final WorldSettings.GameType theGameType; /** * Switch for the map features. 'true' for enabled, 'false' for disabled. */ private final boolean mapFeaturesEnabled; /** * True if hardcore mode is enabled */ private final boolean hardcoreEnabled; private final WorldType terrainType; /** * True if Commands (cheats) are allowed. */ private boolean commandsAllowed; /** * True if the Bonus Chest is enabled. */ private boolean bonusChestEnabled; private String worldName; private static final String __OBFID = "CL_00000147"; public WorldSettings(long seedIn, WorldSettings.GameType gameType, boolean enableMapFeatures, boolean hardcoreMode, WorldType worldTypeIn) { worldName = ""; seed = seedIn; theGameType = gameType; mapFeaturesEnabled = enableMapFeatures; hardcoreEnabled = hardcoreMode; terrainType = worldTypeIn; } public WorldSettings(WorldInfo info) { this(info.getSeed(), info.getGameType(), info.isMapFeaturesEnabled(), info.isHardcoreModeEnabled(), info.getTerrainType()); } /** * Enables the bonus chest. */ public WorldSettings enableBonusChest() { bonusChestEnabled = true; return this; } /** * Enables Commands (cheats). */ public WorldSettings enableCommands() { commandsAllowed = true; return this; } public WorldSettings setWorldName(String name) { worldName = name; return this; } /** * Returns true if the Bonus Chest is enabled. */ public boolean isBonusChestEnabled() { return bonusChestEnabled; } /** * Returns the seed for the world. */ public long getSeed() { return seed; } /** * Gets the game type. */ public WorldSettings.GameType getGameType() { return theGameType; } /** * Returns true if hardcore mode is enabled, otherwise false */ public boolean getHardcoreEnabled() { return hardcoreEnabled; } /** * Get whether the map features (e.g. strongholds) generation is enabled or * disabled. */ public boolean isMapFeaturesEnabled() { return mapFeaturesEnabled; } public WorldType getTerrainType() { return terrainType; } /** * Returns true if Commands (cheats) are allowed. */ public boolean areCommandsAllowed() { return commandsAllowed; } /** * Gets the GameType by ID */ public static WorldSettings.GameType getGameTypeById(int id) { return WorldSettings.GameType.getByID(id); } public String getWorldName() { return worldName; } public static enum GameType { NOT_SET("NOT_SET", 0, -1, ""), SURVIVAL("SURVIVAL", 1, 0, "survival"), CREATIVE("CREATIVE", 2, 1, "creative"), ADVENTURE("ADVENTURE", 3, 2, "adventure"), SPECTATOR("SPECTATOR", 4, 3, "spectator"); int id; String name; private static final WorldSettings.GameType[] $VALUES = new WorldSettings.GameType[]{NOT_SET, SURVIVAL, CREATIVE, ADVENTURE, SPECTATOR}; private static final String __OBFID = "CL_00000148"; private GameType(String p_i1956_1_, int p_i1956_2_, int typeId, String nameIn) { id = typeId; name = nameIn; } public int getID() { return id; } public String getName() { return name; } public void configurePlayerCapabilities(PlayerCapabilities capabilities) { if (this == CREATIVE) { capabilities.allowFlying = true; capabilities.isCreativeMode = true; capabilities.disableDamage = true; } else if (this == SPECTATOR) { capabilities.allowFlying = true; capabilities.isCreativeMode = false; capabilities.disableDamage = true; capabilities.isFlying = true; } else { capabilities.allowFlying = false; capabilities.isCreativeMode = false; capabilities.disableDamage = false; capabilities.isFlying = false; } capabilities.allowEdit = !isAdventure(); } public boolean isAdventure() { return this == ADVENTURE || this == SPECTATOR; } public boolean isCreative() { return this == CREATIVE; } public boolean isSurvivalOrAdventure() { return this == SURVIVAL || this == ADVENTURE; } public static WorldSettings.GameType getByID(int idIn) { WorldSettings.GameType[] var1 = GameType.values(); int var2 = var1.length; for (int var3 = 0; var3 < var2; ++var3) { WorldSettings.GameType var4 = var1[var3]; if (var4.id == idIn) { return var4; } } return SURVIVAL; } public static WorldSettings.GameType getByName(String p_77142_0_) { WorldSettings.GameType[] var1 = GameType.values(); int var2 = var1.length; for (int var3 = 0; var3 < var2; ++var3) { WorldSettings.GameType var4 = var1[var3]; if (var4.name.equals(p_77142_0_)) { return var4; } } return SURVIVAL; } } }
/* * Copyright 2015-2020 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.cloudfront.model.transform; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.cloudfront.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * CreateRealtimeLogConfigResult StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateRealtimeLogConfigResultStaxUnmarshaller implements Unmarshaller<CreateRealtimeLogConfigResult, StaxUnmarshallerContext> { public CreateRealtimeLogConfigResult unmarshall(StaxUnmarshallerContext context) throws Exception { CreateRealtimeLogConfigResult createRealtimeLogConfigResult = new CreateRealtimeLogConfigResult(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return createRealtimeLogConfigResult; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("RealtimeLogConfig", targetDepth)) { createRealtimeLogConfigResult.setRealtimeLogConfig(RealtimeLogConfigStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return createRealtimeLogConfigResult; } } } } private static CreateRealtimeLogConfigResultStaxUnmarshaller instance; public static CreateRealtimeLogConfigResultStaxUnmarshaller getInstance() { if (instance == null) instance = new CreateRealtimeLogConfigResultStaxUnmarshaller(); return instance; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pig.test; import java.io.File; import java.io.FileFilter; import java.io.FileOutputStream; import java.io.IOException; import java.util.Map.Entry; import org.apache.commons.io.filefilter.RegexFileFilter; import org.apache.commons.lang.ArrayUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.mapreduce.v2.MiniMRYarnCluster; import org.apache.hadoop.yarn.conf.YarnConfiguration; import org.apache.pig.ExecType; import org.apache.pig.PigConfiguration; import org.apache.pig.backend.hadoop.executionengine.Launcher; import org.apache.pig.backend.hadoop.executionengine.tez.TezExecType; import org.apache.pig.backend.hadoop.executionengine.tez.TezLauncher; import org.apache.pig.backend.hadoop.executionengine.tez.TezSessionManager; import org.apache.tez.dag.api.TezConfiguration; import org.apache.tez.mapreduce.hadoop.MRJobConfig; import org.apache.tez.runtime.library.api.TezRuntimeConfiguration; public class TezMiniCluster extends MiniGenericCluster { private static final File CONF_DIR = new File("build/classes"); private static final File TEZ_LIB_DIR = new File("build/ivy/lib/Pig"); private static final File TEZ_CONF_FILE = new File(CONF_DIR, "tez-site.xml"); private static final File CORE_CONF_FILE = new File(CONF_DIR, "core-site.xml"); private static final File HDFS_CONF_FILE = new File(CONF_DIR, "hdfs-site.xml"); private static final File MAPRED_CONF_FILE = new File(CONF_DIR, "mapred-site.xml"); private static final File YARN_CONF_FILE = new File(CONF_DIR, "yarn-site.xml"); private static final ExecType TEZ = new TezExecType(); protected MiniMRYarnCluster m_mr = null; private Configuration m_dfs_conf = null; private Configuration m_mr_conf = null; @Override public ExecType getExecType() { return TEZ; } @Override public void setupMiniDfsAndMrClusters() { try { deleteConfFiles(); CONF_DIR.mkdirs(); // Build mini DFS cluster Configuration hdfsConf = new Configuration(); m_dfs = new MiniDFSCluster.Builder(hdfsConf) .numDataNodes(2) .format(true) .racks(null) .build(); m_fileSys = m_dfs.getFileSystem(); m_dfs_conf = m_dfs.getConfiguration(0); //Create user home directory m_fileSys.mkdirs(m_fileSys.getWorkingDirectory()); // Write core-site.xml Configuration core_site = new Configuration(false); core_site.set(FileSystem.FS_DEFAULT_NAME_KEY, m_dfs_conf.get(FileSystem.FS_DEFAULT_NAME_KEY)); core_site.writeXml(new FileOutputStream(CORE_CONF_FILE)); Configuration hdfs_site = new Configuration(false); for (Entry<String, String> conf : m_dfs_conf) { if (ArrayUtils.contains(m_dfs_conf.getPropertySources(conf.getKey()), "programatically")) { hdfs_site.set(conf.getKey(), m_dfs_conf.getRaw(conf.getKey())); } } hdfs_site.writeXml(new FileOutputStream(HDFS_CONF_FILE)); // Build mini YARN cluster m_mr = new MiniMRYarnCluster("PigMiniCluster", 2); m_mr.init(m_dfs_conf); m_mr.start(); m_mr_conf = m_mr.getConfig(); m_mr_conf.set(YarnConfiguration.YARN_APPLICATION_CLASSPATH, System.getProperty("java.class.path")); m_mr_conf.set(MRJobConfig.MAP_JAVA_OPTS, "-Xmx512m"); m_mr_conf.set(MRJobConfig.REDUCE_JAVA_OPTS, "-Xmx512m"); Configuration mapred_site = new Configuration(false); Configuration yarn_site = new Configuration(false); for (Entry<String, String> conf : m_mr_conf) { if (ArrayUtils.contains(m_mr_conf.getPropertySources(conf.getKey()), "programatically")) { if (conf.getKey().contains("yarn")) { yarn_site.set(conf.getKey(), m_mr_conf.getRaw(conf.getKey())); } else if (!conf.getKey().startsWith("dfs")){ mapred_site.set(conf.getKey(), m_mr_conf.getRaw(conf.getKey())); } } } mapred_site.writeXml(new FileOutputStream(MAPRED_CONF_FILE)); yarn_site.writeXml(new FileOutputStream(YARN_CONF_FILE)); // Write tez-site.xml Configuration tez_conf = new Configuration(false); // TODO PIG-3659 - Remove this once memory management is fixed tez_conf.set(TezRuntimeConfiguration.TEZ_RUNTIME_IO_SORT_MB, "20"); tez_conf.set(TezRuntimeConfiguration.TEZ_RUNTIME_OPTIMIZE_LOCAL_FETCH, "false"); tez_conf.set("tez.lib.uris", "hdfs:///tez,hdfs:///tez/lib"); // Set to a lower value so that tests don't get stuck for long because of 1 AM running at a time tez_conf.set(TezConfiguration.TEZ_SESSION_AM_DAG_SUBMIT_TIMEOUT_SECS, "20"); // Lower the max task attempts to 2 so that negative tests fail // faster. By default, tasks retry 4 times tez_conf.set(TezConfiguration.TEZ_AM_TASK_MAX_FAILED_ATTEMPTS, "2"); tez_conf.writeXml(new FileOutputStream(TEZ_CONF_FILE)); // Copy tez jars to hdfs m_fileSys.mkdirs(new Path("/tez/lib")); FileFilter fileFilter = new RegexFileFilter("tez-.+\\.jar$"); File[] tezJars = TEZ_LIB_DIR.listFiles(fileFilter); for (int i = 0; i < tezJars.length; i++) { if (tezJars[i].getName().startsWith("tez-api")) { m_fileSys.copyFromLocalFile( new Path(tezJars[i].getAbsoluteFile().toString()), new Path("/tez")); } else { m_fileSys.copyFromLocalFile( new Path(tezJars[i].getAbsoluteFile().toString()), new Path("/tez/lib")); } } m_conf = m_mr_conf; // Turn FetchOptimizer off so that we can actually test Tez m_conf.set(PigConfiguration.PIG_OPT_FETCH, System.getProperty("test.opt.fetch", "false")); System.setProperty("junit.hadoop.conf", CONF_DIR.getPath()); System.setProperty("hadoop.log.dir", "build/test/logs"); } catch (IOException e) { throw new RuntimeException(e); } } @Override protected void shutdownMiniDfsAndMrClusters() { TezSessionManager.shutdown(); super.shutdownMiniDfsAndMrClusters(); } @Override protected void shutdownMiniMrClusters() { deleteConfFiles(); if (m_mr != null) { m_mr.stop(); m_mr = null; } } private void deleteConfFiles() { if(TEZ_CONF_FILE.exists()) { TEZ_CONF_FILE.delete(); } if(CORE_CONF_FILE.exists()) { CORE_CONF_FILE.delete(); } if(HDFS_CONF_FILE.exists()) { HDFS_CONF_FILE.delete(); } if(MAPRED_CONF_FILE.exists()) { MAPRED_CONF_FILE.delete(); } if(YARN_CONF_FILE.exists()) { YARN_CONF_FILE.delete(); } } static public Launcher getLauncher() { return new TezLauncher(); } }
/* * Copyright 2014 - 2020 Blazebit. * * 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.blazebit.persistence.testsuite.entity; import javax.persistence.Column; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.Table; import java.io.Serializable; /** * * @author Christian Beikov * @since 1.4.0 */ @Entity @Table(name = "PARENT_TBL") @DiscriminatorColumn(name = "DTYPE", discriminatorType = DiscriminatorType.INTEGER) @DiscriminatorValue("0") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) public class Parent implements Serializable { private static final long serialVersionUID = 1L; private Long id; private Integer number; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name = "order_nr") public Integer getNumber() { return number; } public void setNumber(Integer number) { this.number = number; } }
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.flowable.task.service; import java.util.List; import java.util.Map; import org.flowable.common.engine.api.delegate.event.FlowableEventDispatcher; import org.flowable.common.engine.api.delegate.event.FlowableEventListener; import org.flowable.common.engine.impl.AbstractServiceConfiguration; import org.flowable.idm.api.IdmIdentityService; import org.flowable.task.api.TaskQueryInterceptor; import org.flowable.task.api.history.HistoricTaskQueryInterceptor; import org.flowable.task.service.history.InternalHistoryTaskManager; import org.flowable.task.service.impl.HistoricTaskServiceImpl; import org.flowable.task.service.impl.TaskServiceImpl; import org.flowable.task.service.impl.persistence.entity.HistoricTaskInstanceEntityManager; import org.flowable.task.service.impl.persistence.entity.HistoricTaskInstanceEntityManagerImpl; import org.flowable.task.service.impl.persistence.entity.TaskEntityManager; import org.flowable.task.service.impl.persistence.entity.TaskEntityManagerImpl; import org.flowable.task.service.impl.persistence.entity.data.HistoricTaskInstanceDataManager; import org.flowable.task.service.impl.persistence.entity.data.TaskDataManager; import org.flowable.task.service.impl.persistence.entity.data.impl.MybatisHistoricTaskInstanceDataManager; import org.flowable.task.service.impl.persistence.entity.data.impl.MybatisTaskDataManager; public class TaskServiceConfiguration extends AbstractServiceConfiguration { public static final String DEFAULT_MYBATIS_MAPPING_FILE = "org/flowable/task/service/db/mapping/mappings.xml"; // SERVICES // ///////////////////////////////////////////////////////////////// protected TaskService taskService = new TaskServiceImpl(this); protected HistoricTaskService historicTaskService = new HistoricTaskServiceImpl(this); protected IdmIdentityService idmIdentityService; // DATA MANAGERS /////////////////////////////////////////////////// protected TaskDataManager taskDataManager; protected HistoricTaskInstanceDataManager historicTaskInstanceDataManager; // ENTITY MANAGERS ///////////////////////////////////////////////// protected TaskEntityManager taskEntityManager; protected HistoricTaskInstanceEntityManager historicTaskInstanceEntityManager; protected InternalTaskVariableScopeResolver internalTaskVariableScopeResolver; protected InternalHistoryTaskManager internalHistoryTaskManager; protected InternalTaskLocalizationManager internalTaskLocalizationManager; protected InternalTaskAssignmentManager internalTaskAssignmentManager; protected boolean enableTaskRelationshipCounts; protected boolean enableLocalization; protected TaskQueryInterceptor taskQueryInterceptor; protected HistoricTaskQueryInterceptor historicTaskQueryInterceptor; protected int taskQueryLimit; protected int historicTaskQueryLimit; protected TaskPostProcessor taskPostProcessor; // init // ///////////////////////////////////////////////////////////////////// public void init() { initDataManagers(); initEntityManagers(); initTaskPostProcessor(); } // Data managers /////////////////////////////////////////////////////////// public void initDataManagers() { if (taskDataManager == null) { taskDataManager = new MybatisTaskDataManager(); } if (historicTaskInstanceDataManager == null) { historicTaskInstanceDataManager = new MybatisHistoricTaskInstanceDataManager(); } } public void initEntityManagers() { if (taskEntityManager == null) { taskEntityManager = new TaskEntityManagerImpl(this, taskDataManager); } if (historicTaskInstanceEntityManager == null) { historicTaskInstanceEntityManager = new HistoricTaskInstanceEntityManagerImpl(this, historicTaskInstanceDataManager); } } public void initTaskPostProcessor() { if (taskPostProcessor == null) { taskPostProcessor = taskBuilder -> taskBuilder; } } public TaskService getTaskService() { return taskService; } public TaskServiceConfiguration setTaskService(TaskService taskService) { this.taskService = taskService; return this; } public HistoricTaskService getHistoricTaskService() { return historicTaskService; } public TaskServiceConfiguration setHistoricTaskService(HistoricTaskService historicTaskService) { this.historicTaskService = historicTaskService; return this; } public IdmIdentityService getIdmIdentityService() { return idmIdentityService; } public void setIdmIdentityService(IdmIdentityService idmIdentityService) { this.idmIdentityService = idmIdentityService; } public TaskServiceConfiguration getTaskServiceConfiguration() { return this; } public TaskDataManager getTaskDataManager() { return taskDataManager; } public TaskServiceConfiguration setTaskDataManager(TaskDataManager taskDataManager) { this.taskDataManager = taskDataManager; return this; } public HistoricTaskInstanceDataManager getHistoricTaskInstanceDataManager() { return historicTaskInstanceDataManager; } public TaskServiceConfiguration setHistoricTaskInstanceDataManager(HistoricTaskInstanceDataManager historicTaskInstanceDataManager) { this.historicTaskInstanceDataManager = historicTaskInstanceDataManager; return this; } public TaskEntityManager getTaskEntityManager() { return taskEntityManager; } public TaskServiceConfiguration setTaskEntityManager(TaskEntityManager taskEntityManager) { this.taskEntityManager = taskEntityManager; return this; } public HistoricTaskInstanceEntityManager getHistoricTaskInstanceEntityManager() { return historicTaskInstanceEntityManager; } public TaskServiceConfiguration setHistoricTaskInstanceEntityManager(HistoricTaskInstanceEntityManager historicTaskInstanceEntityManager) { this.historicTaskInstanceEntityManager = historicTaskInstanceEntityManager; return this; } public InternalTaskVariableScopeResolver getInternalTaskVariableScopeResolver() { return internalTaskVariableScopeResolver; } public void setInternalTaskVariableScopeResolver(InternalTaskVariableScopeResolver internalTaskVariableScopeResolver) { this.internalTaskVariableScopeResolver = internalTaskVariableScopeResolver; } public InternalHistoryTaskManager getInternalHistoryTaskManager() { return internalHistoryTaskManager; } public void setInternalHistoryTaskManager(InternalHistoryTaskManager internalHistoryTaskManager) { this.internalHistoryTaskManager = internalHistoryTaskManager; } public InternalTaskLocalizationManager getInternalTaskLocalizationManager() { return internalTaskLocalizationManager; } public void setInternalTaskLocalizationManager(InternalTaskLocalizationManager internalTaskLocalizationManager) { this.internalTaskLocalizationManager = internalTaskLocalizationManager; } public InternalTaskAssignmentManager getInternalTaskAssignmentManager() { return internalTaskAssignmentManager; } public void setInternalTaskAssignmentManager(InternalTaskAssignmentManager internalTaskAssignmentManager) { this.internalTaskAssignmentManager = internalTaskAssignmentManager; } public boolean isEnableTaskRelationshipCounts() { return enableTaskRelationshipCounts; } public TaskServiceConfiguration setEnableTaskRelationshipCounts(boolean enableTaskRelationshipCounts) { this.enableTaskRelationshipCounts = enableTaskRelationshipCounts; return this; } public boolean isEnableLocalization() { return enableLocalization; } public TaskServiceConfiguration setEnableLocalization(boolean enableLocalization) { this.enableLocalization = enableLocalization; return this; } public TaskQueryInterceptor getTaskQueryInterceptor() { return taskQueryInterceptor; } public TaskServiceConfiguration setTaskQueryInterceptor(TaskQueryInterceptor taskQueryInterceptor) { this.taskQueryInterceptor = taskQueryInterceptor; return this; } public HistoricTaskQueryInterceptor getHistoricTaskQueryInterceptor() { return historicTaskQueryInterceptor; } public TaskServiceConfiguration setHistoricTaskQueryInterceptor(HistoricTaskQueryInterceptor historicTaskQueryInterceptor) { this.historicTaskQueryInterceptor = historicTaskQueryInterceptor; return this; } public int getTaskQueryLimit() { return taskQueryLimit; } public TaskServiceConfiguration setTaskQueryLimit(int taskQueryLimit) { this.taskQueryLimit = taskQueryLimit; return this; } public int getHistoricTaskQueryLimit() { return historicTaskQueryLimit; } public TaskServiceConfiguration setHistoricTaskQueryLimit(int historicTaskQueryLimit) { this.historicTaskQueryLimit = historicTaskQueryLimit; return this; } @Override public TaskServiceConfiguration setEnableEventDispatcher(boolean enableEventDispatcher) { this.enableEventDispatcher = enableEventDispatcher; return this; } @Override public TaskServiceConfiguration setEventDispatcher(FlowableEventDispatcher eventDispatcher) { this.eventDispatcher = eventDispatcher; return this; } @Override public TaskServiceConfiguration setEventListeners(List<FlowableEventListener> eventListeners) { this.eventListeners = eventListeners; return this; } @Override public TaskServiceConfiguration setTypedEventListeners(Map<String, List<FlowableEventListener>> typedEventListeners) { this.typedEventListeners = typedEventListeners; return this; } public TaskPostProcessor getTaskPostProcessor() { return taskPostProcessor; } public TaskServiceConfiguration setTaskPostProcessor(TaskPostProcessor processor) { this.taskPostProcessor = processor; return this; } }
package com.djs.learn.javalang.io; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Arrays; public class TestObjectIo { String fileName = "target/data/SampleObject.txt"; public static byte[] getBytesFromObject(Object obj) throws IOException{ if (obj != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); oos.close(); return baos.toByteArray(); } else { return null; } } public static Object getObjectFromBytes(byte[] data) throws IOException, ClassNotFoundException{ if (data != null) { ByteArrayInputStream bais = new ByteArrayInputStream(data); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } else { return null; } } public void testObjectOutputStream(){ System.out.println("Test = ObjectOutputStream(FileOutputStream)"); System.out.println("--------------------"); File file = new File(fileName); System.out.println("File name = " + file.getPath()); Person person = new Person(18); Person.total = 1; System.out.println("Person = " + person); try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))) { oos.writeObject(person); } catch (Exception e) { System.err.println("Exception = " + e); } } public void testObjectInputStream(){ System.out.println("Test = ObjectInputStream(FileInputStream)"); System.out.println("--------------------"); File file = new File(fileName); System.out.println("File name = " + file.getPath()); Person person = null; try (ObjectInputStream oos = new ObjectInputStream(new FileInputStream(file))) { // Person constructor and init codes will not be invoked. person = (Person)oos.readObject(); Person.total++; System.out.println("Person = " + person); // There will be "java.io.EOFException". person = (Person)oos.readObject(); } catch (Exception e) { System.err.println("Exception = " + e); } } public void testByteArrayStream(){ System.out.println("Test = ObjectOutputStream(ByteArrayOutputStream)"); System.out.println("Test = ObjectInputStream(ByteArrayInputStream)"); System.out.println("--------------------"); Person person = new Person(29); Person.total++; System.out.println("Person = " + person); try { byte[] data = getBytesFromObject(person); System.out.println("Object data (" + data.length + ") = " + Arrays.toString(data)); Object obj = getObjectFromBytes(data); System.out.println("Object is Person = " + (obj instanceof Person)); System.out.println("Person = " + obj); } catch (Exception e) { System.err.println("Exception = " + e); } } public static void main(String[] args){ TestObjectIo test = new TestObjectIo(); System.out.println("========================================"); test.testObjectOutputStream(); System.out.println("========================================"); test.testObjectInputStream(); System.out.println("========================================"); test.testByteArrayStream(); System.out.println("========================================"); } } class Person implements Serializable { public int age = -1; private int age2 = -1; public transient String pet = "Cat"; public transient int petCount = 1; public static int total = -1; public Student student = new Student(7); { Student.total = 1; System.out.println("Person: Some init code."); } public Person(){ System.out.println("Person()"); } public Person(int age){ System.out.println("Person(age)"); this.age = age; this.age2 = age; } @Override public String toString(){ return "Person [age=" + age + ", age2=" + age2 + ", pet=" + pet + ", petCount=" + petCount + ", student=" + student + ", total=" + total + "]"; } } class Student implements Serializable { public int age = -1; private int age2 = -1; public transient String pet = "Cat"; public transient int petCount = 1; public static int total = -1; { System.out.println("Student: Some init code."); } public Student(){ System.out.println("Student()"); } public Student(int age){ System.out.println("Student(age)"); this.age = age; this.age2 = age; } @Override public String toString(){ return "Student [age=" + age + ", age2=" + age2 + ", pet=" + pet + ", petCount=" + petCount + ", total=" + total + "]"; } }
package controllers; import com.google.common.collect.ImmutableMap; import org.joda.time.DateTimeUtils; import org.junit.Before; import play.inject.guice.GuiceApplicationBuilder; import play.mvc.Result; import play.test.Helpers; import play.test.WithApplication; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; public class BaseControllerTest extends WithApplication { protected GuiceApplicationBuilder builder; protected BaseControllerTest() { this.builder = new GuiceApplicationBuilder().configure(ImmutableMap.<String, Object>builder() .put("play.filters.csrf.token.sign", "false") .build() ); } @Override protected play.Application provideApplication() { return builder.build(); } @Before public void init() { DateTimeUtils.setCurrentMillisSystem(); } protected void makeRequest(Request request, Consumer<Result> function) { function.accept( Helpers.route( Helpers.fakeRequest(request.method, request.path) .header("Accept-Language", request.language) .bodyForm(request.body) .tags(request.tags) ) ); } protected static class Request { private final String method; private final String path; private final Map<String, String> body = new HashMap<>(); private final Map<String, String> tags = new HashMap<>(); private String language = "en"; protected Request(String method, String path) { this.method = method; this.path = path; } protected Request withFormParameter(String name, String value) { body.put(name, value); return this; } protected Request withCSRFToken(String token) { tags.put("CSRF_TOKEN", token); return this; } protected Request withLanguage(String language) { this.language = language; return this; } } protected static class HTTP { protected static Request get(String path) { return new Request("GET", path); } protected static Request post(String path) { return new Request("POST", path); } protected static Request head(String path) { return new Request("HEAD", path); } } }
package visualization.module.jfreechart; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.XYPlot; import data.ChartData; /** * @author Daniel J. Rivers * 2014 * * Created: Feb 5, 2014, 2:01:26 PM */ public class ChartUtils { public static void setFixedAutoRange( JFreeChart chart, ChartData data ) { XYPlot plot = chart.getXYPlot(); ValueAxis axis = plot.getDomainAxis(); axis.setAutoRange( true ); axis.setFixedAutoRange( data.getViewableRange() ); } }
package com.meowu.support.portal.service; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.transaction.annotation.EnableTransactionManagement; @EnableTransactionManagement @EnableDiscoveryClient @SpringBootApplication public class SupportServiceApplication{ public static void main(String[] args){ SpringApplication.run(SupportServiceApplication.class, args); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.packages.management.core.impl; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import java.util.concurrent.CompletableFuture; import org.apache.pulsar.packages.management.core.PackagesManagement; import org.apache.pulsar.packages.management.core.PackagesStorage; import org.apache.pulsar.packages.management.core.common.PackageMetadata; import org.apache.pulsar.packages.management.core.common.PackageMetadataUtil; import org.apache.pulsar.packages.management.core.common.PackageName; import org.apache.pulsar.packages.management.core.common.PackageType; import org.apache.pulsar.packages.management.core.exceptions.PackagesManagementException; import org.apache.pulsar.packages.management.core.exceptions.PackagesManagementException.NotFoundException; /** * Packages management implementation. */ public class PackagesManagementImpl implements PackagesManagement { private PackagesStorage storage; @Override public void initialize(PackagesStorage storage) { this.storage = storage; } @Override public CompletableFuture<PackageMetadata> getMeta(PackageName packageName) { CompletableFuture<PackageMetadata> future = new CompletableFuture<>(); String metadataPath = metadataPath(packageName); checkMetadataNotExistsAndThrowException(packageName) .whenComplete((ignore, throwable) -> { if (throwable != null) { future.completeExceptionally(throwable); return; } try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { storage.readAsync(metadataPath, outputStream) .thenCompose(aVoid -> metadataReadFromStream(outputStream)) .whenComplete((metadata, t) -> { if (t != null) { future.completeExceptionally(t); } else { future.complete(metadata); } }); } catch (IOException e) { future.completeExceptionally(new PackagesManagementException( String.format("Read package '%s' metadata failed", packageName.toString()), e)); } }); return future; } @Override public CompletableFuture<Void> updateMeta(PackageName packageName, PackageMetadata metadata) { CompletableFuture<Void> future = new CompletableFuture<>(); String metadataPath = metadataPath(packageName); checkMetadataNotExistsAndThrowException(packageName) .whenComplete((ignore, throwable) -> { if (throwable != null) { future.completeExceptionally(throwable); return; } try (ByteArrayInputStream inputStream = new ByteArrayInputStream(PackageMetadataUtil.toBytes(metadata))) { storage.deleteAsync(metadataPath) .thenCompose(aVoid -> storage.writeAsync(metadataPath, inputStream)) .whenComplete((aVoid, t) -> { if (t != null) { future.completeExceptionally(new PackagesManagementException( String.format("Update package '%s' metadata failed", packageName.toString()), t)); } else { future.complete(null); } }); } catch (IOException e) { future.completeExceptionally(new PackagesManagementException( String.format("Read package '%s' metadata failed", packageName.toString()), e)); } }); return future; } private CompletableFuture<Void> writeMeta(PackageName packageName, PackageMetadata metadata) { CompletableFuture<Void> future = new CompletableFuture<>(); String metadataPath = metadataPath(packageName); try (ByteArrayInputStream inputStream = new ByteArrayInputStream(PackageMetadataUtil.toBytes(metadata))) { storage.writeAsync(metadataPath, inputStream) .whenComplete((aVoid, t) -> { if (t != null) { future.completeExceptionally(new PackagesManagementException( String.format("Update package '%s' metadata failed", packageName.toString()), t)); } else { future.complete(null); } }); } catch (IOException e) { future.completeExceptionally(new PackagesManagementException( String.format("Read package '%s' metadata failed", packageName.toString()), e)); } return future; } @Override public CompletableFuture<Void> download(PackageName packageName, OutputStream outputStream) { String packagePath = packagePath(packageName); return checkPackageNotExistsAndThrowException(packageName) .thenCompose(ignore -> storage.readAsync(packagePath, outputStream)); } @Override public CompletableFuture<Void> upload(PackageName packageName, PackageMetadata metadata, InputStream inputStream) { return CompletableFuture.allOf( checkMetadataExistsAndThrowException(packageName), checkPackageExistsAndThrowException(packageName) ).thenCompose(ignore -> writeMeta(packageName, metadata)) .thenCompose(ignore -> storage.writeAsync(packagePath(packageName), inputStream)); } @Override public CompletableFuture<Void> delete(PackageName packageName) { return CompletableFuture.allOf( storage.deleteAsync(metadataPath(packageName)), storage.deleteAsync(packagePath(packageName))); } @Override public CompletableFuture<List<String>> list(PackageName packageName) { return storage.listAsync(packageWithoutVersionPath(packageName)); } @Override public CompletableFuture<List<String>> list(PackageType type, String tenant, String namespace) { return storage.listAsync(String.format("%s/%s/%s", type, tenant, namespace)); } private CompletableFuture<Void> checkMetadataNotExistsAndThrowException(PackageName packageName) { String path = metadataPath(packageName); CompletableFuture<Void> future = new CompletableFuture<>(); storage.existAsync(path) .whenComplete((exist, throwable) -> { if (throwable != null) { future.completeExceptionally(throwable); return; } if (exist) { future.complete(null); } else { future.completeExceptionally( new NotFoundException(String.format("Package '%s' metadata does not exist", packageName))); } }); return future; } private CompletableFuture<Void> checkMetadataExistsAndThrowException(PackageName packageName) { String path = metadataPath(packageName); CompletableFuture<Void> future = new CompletableFuture<>(); storage.existAsync(path) .whenComplete((exist, throwable) -> { if (throwable != null) { future.completeExceptionally(throwable); return; } if (!exist) { future.complete(null); } else { future.completeExceptionally( new NotFoundException(String.format("Package '%s' metadata already exists", packageName))); } }); return future; } private CompletableFuture<Void> checkPackageNotExistsAndThrowException(PackageName packageName) { String path = packagePath(packageName); CompletableFuture<Void> future = new CompletableFuture<>(); storage.existAsync(path) .whenComplete((exist, throwable) -> { if (throwable != null) { future.completeExceptionally(throwable); return; } if (exist) { future.complete(null); } else { future.completeExceptionally( new NotFoundException(String.format("Package '%s' does not exist", packageName.toString()))); } }); return future; } private CompletableFuture<Void> checkPackageExistsAndThrowException(PackageName packageName) { String path = packagePath(packageName); CompletableFuture<Void> future = new CompletableFuture<>(); storage.existAsync(path) .whenComplete((exist, throwable) -> { if (throwable != null) { future.completeExceptionally(throwable); return; } if (!exist) { future.complete(null); } else { future.completeExceptionally( new NotFoundException(String.format("Package '%s' already exists", packageName.toString()))); } }); return future; } private CompletableFuture<PackageMetadata> metadataReadFromStream(ByteArrayOutputStream outputStream) { CompletableFuture<PackageMetadata> future = new CompletableFuture<>(); try { PackageMetadata metadata = PackageMetadataUtil.fromBytes(outputStream.toByteArray()); future.complete(metadata); } catch (PackagesManagementException.MetadataFormatException e) { future.completeExceptionally(e); } return future; } protected String metadataPath(PackageName packageName) { return packageName.toRestPath() + "/meta"; } protected String packagePath(PackageName packageName) { return packageName.toRestPath() + storage.dataPath(); } private String packageWithoutVersionPath(PackageName packageName) { return String.format("%s/%s/%s/%s", packageName.getPkgType().toString(), packageName.getTenant(), packageName.getNamespace(), packageName.getName()); } }
/* * Copyright 1999-2011 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.druid.bvt.filter.wall; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.druid.wall.WallUtils; /** * SQLServerWallTest * * @author RaymondXiu * @version 1.0, 2012-3-18 * @see */ public class TAEWallTest extends TestCase { public void test_true() throws Exception { Assert.assertTrue(WallUtils.isValidateMySql(// "select * from t where 1=1 AND status = 1")); // } public void test_false() throws Exception { Assert.assertFalse(WallUtils.isValidateMySql(// "select * from t where status = 1 AND 1=1")); // } }
/* * Copyright (C) 2019 xuexiangjys(xuexiangjys@163.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.github.guqt178.gui.widget.imageview.crop; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.Rect; import android.graphics.RectF; import android.media.ExifInterface; import android.os.Bundle; import android.os.Parcelable; import android.support.annotation.NonNull; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import com.github.guqt178.gui.R; /** * 自定义图片裁剪控件 * * @author xuexiang * @since 2019-10-15 11:53 */ public class CropImageView extends FrameLayout { // Private Constants /////////////////////////////////////////////////////// private static final Rect EMPTY_RECT = new Rect(); // Member Variables //////////////////////////////////////////////////////// // Sets the default image guidelines to show when resizing public static final int DEFAULT_GUIDELINES = 1; public static final boolean DEFAULT_FIXED_ASPECT_RATIO = false; public static final int DEFAULT_ASPECT_RATIO_X = 1; public static final int DEFAULT_ASPECT_RATIO_Y = 1; private static final int DEFAULT_IMAGE_RESOURCE = 0; private static final String DEGREES_ROTATED = "DEGREES_ROTATED"; private ImageView mImageView; private CropOverlayView mCropOverlayView; private Bitmap mBitmap; private int mDegreesRotated = 0; private int mLayoutWidth; private int mLayoutHeight; // Instance variables for customizable attributes private int mGuidelines = DEFAULT_GUIDELINES; private boolean mFixAspectRatio = DEFAULT_FIXED_ASPECT_RATIO; private int mAspectRatioX = DEFAULT_ASPECT_RATIO_X; private int mAspectRatioY = DEFAULT_ASPECT_RATIO_Y; private int mImageResource = DEFAULT_IMAGE_RESOURCE; // Constructors //////////////////////////////////////////////////////////// public CropImageView(Context context) { super(context); init(context); } public CropImageView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CropImageView, 0, 0); try { mGuidelines = ta.getInteger(R.styleable.CropImageView_civ_guidelines, DEFAULT_GUIDELINES); mFixAspectRatio = ta.getBoolean(R.styleable.CropImageView_civ_fixAspectRatio, DEFAULT_FIXED_ASPECT_RATIO); mAspectRatioX = ta.getInteger(R.styleable.CropImageView_civ_aspectRatioX, DEFAULT_ASPECT_RATIO_X); mAspectRatioY = ta.getInteger(R.styleable.CropImageView_civ_aspectRatioY, DEFAULT_ASPECT_RATIO_Y); mImageResource = ta.getResourceId(R.styleable.CropImageView_civ_imageResource, DEFAULT_IMAGE_RESOURCE); } finally { ta.recycle(); } init(context); } // View Methods //////////////////////////////////////////////////////////// @Override public Parcelable onSaveInstanceState() { final Bundle bundle = new Bundle(); bundle.putParcelable("instanceState", super.onSaveInstanceState()); bundle.putInt(DEGREES_ROTATED, mDegreesRotated); return bundle; } @Override public void onRestoreInstanceState(Parcelable state) { if (state instanceof Bundle) { final Bundle bundle = (Bundle) state; if (mBitmap != null) { // Fixes the rotation of the image when orientation changes. mDegreesRotated = bundle.getInt(DEGREES_ROTATED); int tempDegrees = mDegreesRotated; rotateImage(mDegreesRotated); mDegreesRotated = tempDegrees; } super.onRestoreInstanceState(bundle.getParcelable("instanceState")); } else { super.onRestoreInstanceState(state); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { if (mBitmap != null) { final Rect bitmapRect = ImageViewUtil.getBitmapRectCenterInside(mBitmap, this); mCropOverlayView.setBitmapRect(bitmapRect); } else { mCropOverlayView.setBitmapRect(EMPTY_RECT); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); if (mBitmap != null) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // Bypasses a baffling bug when used within a ScrollView, where // heightSize is set to 0. if (heightSize == 0) { heightSize = mBitmap.getHeight(); } int desiredWidth; int desiredHeight; double viewToBitmapWidthRatio = Double.POSITIVE_INFINITY; double viewToBitmapHeightRatio = Double.POSITIVE_INFINITY; // Checks if either width or height needs to be fixed if (widthSize < mBitmap.getWidth()) { viewToBitmapWidthRatio = (double) widthSize / (double) mBitmap.getWidth(); } if (heightSize < mBitmap.getHeight()) { viewToBitmapHeightRatio = (double) heightSize / (double) mBitmap.getHeight(); } // If either needs to be fixed, choose smallest ratio and calculate // from there if (viewToBitmapWidthRatio != Double.POSITIVE_INFINITY || viewToBitmapHeightRatio != Double.POSITIVE_INFINITY) { if (viewToBitmapWidthRatio <= viewToBitmapHeightRatio) { desiredWidth = widthSize; desiredHeight = (int) (mBitmap.getHeight() * viewToBitmapWidthRatio); } else { desiredHeight = heightSize; desiredWidth = (int) (mBitmap.getWidth() * viewToBitmapHeightRatio); } } // Otherwise, the picture is within frame layout bounds. Desired // width is // simply picture size else { desiredWidth = mBitmap.getWidth(); desiredHeight = mBitmap.getHeight(); } int width = getOnMeasureSpec(widthMode, widthSize, desiredWidth); int height = getOnMeasureSpec(heightMode, heightSize, desiredHeight); mLayoutWidth = width; mLayoutHeight = height; final Rect bitmapRect = ImageViewUtil.getBitmapRectCenterInside(mBitmap.getWidth(), mBitmap.getHeight(), mLayoutWidth, mLayoutHeight); mCropOverlayView.setBitmapRect(bitmapRect); //jarlen mCropOverlayView.setBitmapSize(mBitmap.getWidth(), mBitmap.getHeight()); // MUST CALL THIS setMeasuredDimension(mLayoutWidth, mLayoutHeight); } else { mCropOverlayView.setBitmapRect(EMPTY_RECT); setMeasuredDimension(widthSize, heightSize); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); if (mLayoutWidth > 0 && mLayoutHeight > 0) { // Gets original parameters, and creates the new parameters final ViewGroup.LayoutParams origparams = this.getLayoutParams(); origparams.width = mLayoutWidth; origparams.height = mLayoutHeight; setLayoutParams(origparams); } } // Public Methods ////////////////////////////////////////////////////////// /** * Returns the integer of the imageResource * the image resource id * * @param */ public int getImageResource() { return mImageResource; } /** * Sets a Bitmap as the content of the CropImageView. * 设置剪切资源图 * * @param imagePath 图片的资源路径 */ public void setImagePath(@NonNull String imagePath) { setImageBitmap(BitmapFactory.decodeFile(imagePath)); } /** * Sets a Bitmap as the content of the CropImageView. * 设置剪切资源图 * * @param bitmap 剪切资源图 */ public void setImageBitmap(Bitmap bitmap) { mBitmap = bitmap; mImageView.setImageBitmap(mBitmap); if (mCropOverlayView != null) { mCropOverlayView.resetCropOverlayView(); mCropOverlayView.setVisibility(VISIBLE); } } public CropImageView switchCropOverlayViewVisibility(boolean visibility) { return setCropOverlayViewVisibility(visibility ? VISIBLE : GONE); } public CropImageView setCropOverlayViewVisibility(int visibility) { if (mCropOverlayView != null) { mCropOverlayView.setVisibility(visibility); } return this; } public CropOverlayView getCropOverlayView() { return mCropOverlayView; } public ImageView getImageView() { return mImageView; } /** * Sets a Bitmap and initializes the image rotation according to the EXIT data. * <p> * The EXIF can be retrieved by doing the following: * <code>ExifInterface exif = new ExifInterface(path);</code> * * @param bitmap the original bitmap to set; if null, this * @param exif the EXIF information about this bitmap; may be null */ public void setImageBitmap(Bitmap bitmap, ExifInterface exif) { if (bitmap == null) { return; } if (exif == null) { setImageBitmap(bitmap); return; } final Matrix matrix = new Matrix(); final int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1); int rotate = -1; switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_270: rotate = 270; break; case ExifInterface.ORIENTATION_ROTATE_180: rotate = 180; break; case ExifInterface.ORIENTATION_ROTATE_90: rotate = 90; break; default: break; } if (rotate == -1) { setImageBitmap(bitmap); } else { matrix.postRotate(rotate); final Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); setImageBitmap(rotatedBitmap); bitmap.recycle(); } } /** * Sets a Drawable as the content of the CropImageView. * 设置剪切资源图 * * @param resId 剪切资源图ID */ public void setImageResource(int resId) { if (resId != 0) { Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId); setImageBitmap(bitmap); } } /** * 裁剪图片 */ public Bitmap cropImage() { return cropImage(false); } /** * 裁剪图片 * * @param isContinueCrop 是否继续裁剪 */ public Bitmap cropImage(boolean isContinueCrop) { Bitmap bitmap = getCroppedImage(); setImageBitmap(bitmap); if (!isContinueCrop) { setCropOverlayViewVisibility(GONE); } return bitmap; } /** * Gets the cropped image based on the current crop window. * 获取剪切区图 * * @return 剪切区域图 */ public Bitmap getCroppedImage() { final Rect displayedImageRect = ImageViewUtil.getBitmapRectCenterInside(mBitmap, mImageView); // Get the scale factor between the actual Bitmap dimensions and the // displayed dimensions for width. final float actualImageWidth = mBitmap.getWidth(); final float displayedImageWidth = displayedImageRect.width(); final float scaleFactorWidth = actualImageWidth / displayedImageWidth; // Get the scale factor between the actual Bitmap dimensions and the // displayed dimensions for height. final float actualImageHeight = mBitmap.getHeight(); final float displayedImageHeight = displayedImageRect.height(); final float scaleFactorHeight = actualImageHeight / displayedImageHeight; // Get crop window position relative to the displayed image. final float cropWindowX = Edge.LEFT.getCoordinate() - displayedImageRect.left; final float cropWindowY = Edge.TOP.getCoordinate() - displayedImageRect.top; final float cropWindowWidth = Edge.getWidth(); final float cropWindowHeight = Edge.getHeight(); // Scale the crop window position to the actual size of the Bitmap. final float actualCropX = cropWindowX * scaleFactorWidth; final float actualCropY = cropWindowY * scaleFactorHeight; final float actualCropWidth = cropWindowWidth * scaleFactorWidth; final float actualCropHeight = cropWindowHeight * scaleFactorHeight; // Crop the subset from the original Bitmap. return Bitmap.createBitmap(mBitmap, (int) actualCropX, (int) actualCropY, (int) actualCropWidth, (int) actualCropHeight); } /** * Gets the crop window's position relative to the source Bitmap (not the image * displayed in the CropImageView). * * @return a RectF instance containing cropped area boundaries of the source Bitmap */ public RectF getActualCropRect() { final Rect displayedImageRect = ImageViewUtil.getBitmapRectCenterInside(mBitmap, mImageView); // Get the scale factor between the actual Bitmap dimensions and the // displayed dimensions for width. final float actualImageWidth = mBitmap.getWidth(); final float displayedImageWidth = displayedImageRect.width(); final float scaleFactorWidth = actualImageWidth / displayedImageWidth; // Get the scale factor between the actual Bitmap dimensions and the // displayed dimensions for height. final float actualImageHeight = mBitmap.getHeight(); final float displayedImageHeight = displayedImageRect.height(); final float scaleFactorHeight = actualImageHeight / displayedImageHeight; // Get crop window position relative to the displayed image. final float displayedCropLeft = Edge.LEFT.getCoordinate() - displayedImageRect.left; final float displayedCropTop = Edge.TOP.getCoordinate() - displayedImageRect.top; final float displayedCropWidth = Edge.getWidth(); final float displayedCropHeight = Edge.getHeight(); // Scale the crop window position to the actual size of the Bitmap. float actualCropLeft = displayedCropLeft * scaleFactorWidth; float actualCropTop = displayedCropTop * scaleFactorHeight; float actualCropRight = actualCropLeft + displayedCropWidth * scaleFactorWidth; float actualCropBottom = actualCropTop + displayedCropHeight * scaleFactorHeight; // Correct for floating point errors. Crop rect boundaries should not // exceed the source Bitmap bounds. actualCropLeft = Math.max(0f, actualCropLeft); actualCropTop = Math.max(0f, actualCropTop); actualCropRight = Math.min(mBitmap.getWidth(), actualCropRight); actualCropBottom = Math.min(mBitmap.getHeight(), actualCropBottom); return new RectF(actualCropLeft, actualCropTop, actualCropRight, actualCropBottom); } /** * 设置剪切类型 * <p> * false: 自由剪切 * true : 固定大小比例剪切 * * @param fixAspectRatio */ public void setFixedAspectRatio(boolean fixAspectRatio) { mCropOverlayView.setFixedAspectRatio(fixAspectRatio); } /** * Sets the guidelines for the CropOverlayView to be either on, off, or to show when * resizing the application. * * @param guidelines Integer that signals whether the guidelines should be on, off, or * only showing when resizing. */ public void setGuidelines(int guidelines) { mCropOverlayView.setGuidelines(guidelines); } /** * Sets the both the X and Y values of the aspectRatio. * 设置固定比例剪切的比例 * 现将setFixedAspectRatio(true)设置 * <p> * 例如:cropImage.setAspectRatio(40, 30);是以40:30的宽高比例剪切 * * @param aspectRatioX int that specifies the new X value of the aspect ratio * 宽度比例 * @param aspectRatioY int that specifies the new Y value of the aspect ratio * 高度比例 */ public void setAspectRatio(int aspectRatioX, int aspectRatioY) { mAspectRatioX = aspectRatioX; mCropOverlayView.setAspectRatioX(mAspectRatioX); mAspectRatioY = aspectRatioY; mCropOverlayView.setAspectRatioY(mAspectRatioY); } /** * Rotates image by the specified number of degrees clockwise. Cycles from 0 to 360 * degrees. * 顺时针度数旋转图片 * <p> * 0 --- 360 * * @param degrees Integer specifying the number of degrees to rotate. * <p> * 旋转度数 */ public void rotateImage(int degrees) { Matrix matrix = new Matrix(); matrix.postRotate(degrees); mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), matrix, true); setImageBitmap(mBitmap); mDegreesRotated += degrees; mDegreesRotated = mDegreesRotated % 360; } /** * 图片翻转 * * @param type 翻转类型 * CropImageType.REVERSE_TYPE.UP_DOWN * CropImageType.REVERSE_TYPE.LEFT_RIGHT * @author jarlen */ public void reverseImage(CropImageType.REVERSE_TYPE type) { Matrix matrix = new Matrix(); if (type == CropImageType.REVERSE_TYPE.UP_DOWN) { //上下翻转 matrix.postScale(1, -1); } else if (type == CropImageType.REVERSE_TYPE.LEFT_RIGHT) { //左右翻转 matrix.postScale(-1, 1); } mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), matrix, true); setImageBitmap(mBitmap); } /** * 更改剪切框四角的样式 * * @param bit 样式图片 * bit = null 时,默认为白色角边线 */ public void setCropOverlayCornerBitmap(Bitmap bit) { mCropOverlayView.setCropOverlayCornerBitmap(bit); } // Private Methods ///////////////////////////////////////////////////////// private void init(Context context) { final LayoutInflater inflater = LayoutInflater.from(context); final View v = inflater.inflate(R.layout.xui_layout_crop_image_view, this, true); mImageView = v.findViewById(R.id.iv_content); setImageResource(mImageResource); mCropOverlayView = v.findViewById(R.id.crop_overlay_view); mCropOverlayView.setInitialAttributeValues(mGuidelines, mFixAspectRatio, mAspectRatioX, mAspectRatioY); } /** * Determines the specs for the onMeasure function. Calculates the width or height * depending on the mode. * * @param measureSpecMode The mode of the measured width or height. * @param measureSpecSize The size of the measured width or height. * @param desiredSize The desired size of the measured width or height. * @return The final size of the width or height. */ private static int getOnMeasureSpec(int measureSpecMode, int measureSpecSize, int desiredSize) { // Measure Width int spec; if (measureSpecMode == MeasureSpec.EXACTLY) { // Must be this size spec = measureSpecSize; } else if (measureSpecMode == MeasureSpec.AT_MOST) { // Can't be bigger than...; match_parent value spec = Math.min(desiredSize, measureSpecSize); } else { // Be whatever you want; wrap_content spec = desiredSize; } return spec; } }
/* * Copyright (c) 2006, Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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. * * $Id: MoteInterfaceViewer.java,v 1.10 2010/05/09 22:50:34 nifi Exp $ */ package se.sics.cooja.plugins; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Collection; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import org.jdom.Element; import se.sics.cooja.ClassDescription; import se.sics.cooja.GUI; import se.sics.cooja.HasQuickHelp; import se.sics.cooja.Mote; import se.sics.cooja.MoteInterface; import se.sics.cooja.MotePlugin; import se.sics.cooja.PluginType; import se.sics.cooja.Simulation; import se.sics.cooja.VisPlugin; /** * Mote Interface Viewer views information about a specific mote interface. * * @author Fredrik Osterlind */ @ClassDescription("Mote Interface Viewer") @PluginType(PluginType.MOTE_PLUGIN) public class MoteInterfaceViewer extends VisPlugin implements HasQuickHelp, MotePlugin { private static final long serialVersionUID = 1L; private Mote mote; private MoteInterface selectedMoteInterface = null; private JPanel currentInterfaceVisualizer = null; private JComboBox selectInterfaceComboBox = null; private JScrollPane mainScrollPane; /** * Create a new mote interface viewer. * * @param moteToView Mote to view */ public MoteInterfaceViewer(Mote moteToView, Simulation simulation, GUI gui) { super("Mote Interface Viewer (" + moteToView + ")", gui); mote = moteToView; JLabel label; JPanel mainPane = new JPanel(new BorderLayout()); JPanel smallPane; // Select interface combo box smallPane = new JPanel(new BorderLayout()); smallPane.add(new JSeparator(), BorderLayout.SOUTH); label = new JLabel("Select interface:"); selectInterfaceComboBox = new JComboBox(); final JPanel interfacePanel = new JPanel(new BorderLayout()); Collection<MoteInterface> intfs = mote.getInterfaces().getInterfaces(); for (MoteInterface intf : intfs) { selectInterfaceComboBox.addItem(GUI.getDescriptionOf(intf)); } selectInterfaceComboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Release old interface visualizer if any if (selectedMoteInterface != null && currentInterfaceVisualizer != null) { selectedMoteInterface.releaseInterfaceVisualizer(currentInterfaceVisualizer); } // View selected interface if any interfacePanel.removeAll(); String interfaceDescription = (String) selectInterfaceComboBox.getSelectedItem(); selectedMoteInterface = null; Collection<MoteInterface> intfs = mote.getInterfaces().getInterfaces(); for (MoteInterface intf : intfs) { if (GUI.getDescriptionOf(intf).equals(interfaceDescription)) { selectedMoteInterface = intf; mote.getSimulation().getGUI().loadQuickHelp(MoteInterfaceViewer.this); break; } } currentInterfaceVisualizer = selectedMoteInterface.getInterfaceVisualizer(); if (currentInterfaceVisualizer != null) { interfacePanel.add(BorderLayout.CENTER, currentInterfaceVisualizer); currentInterfaceVisualizer.setVisible(true); } else { interfacePanel.add(new JLabel("No interface visualizer", JLabel.CENTER)); currentInterfaceVisualizer = null; } setSize(getSize()); } }); selectInterfaceComboBox.setSelectedIndex(0); smallPane.add(BorderLayout.WEST, label); smallPane.add(BorderLayout.EAST, selectInterfaceComboBox); mainPane.add(BorderLayout.NORTH, smallPane); // Add selected interface if (selectInterfaceComboBox.getItemCount() > 0) { selectInterfaceComboBox.setSelectedIndex(0); selectInterfaceComboBox.dispatchEvent(new ActionEvent(selectInterfaceComboBox, ActionEvent.ACTION_PERFORMED, "")); } mainPane.add(BorderLayout.CENTER, interfacePanel); mainScrollPane = new JScrollPane(mainPane, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); mainScrollPane.setBorder(BorderFactory.createEmptyBorder(0,2,0,2)); this.setContentPane(mainScrollPane); pack(); setPreferredSize(new Dimension(350,300)); setSize(new Dimension(350,300)); try { setSelected(true); } catch (java.beans.PropertyVetoException e) { // Could not select } } /** * Tries to select the interface with the given class name. * @param description Interface description * @return True if selected, false otherwise */ public boolean setSelectedInterface(String description) { for (int i=0; i < selectInterfaceComboBox.getItemCount(); i++) { if (selectInterfaceComboBox.getItemAt(i).equals(description)) { selectInterfaceComboBox.setSelectedIndex(i); return true; } } return false; } public void closePlugin() { // Release old interface visualizer if any if (selectedMoteInterface != null && currentInterfaceVisualizer != null) { selectedMoteInterface.releaseInterfaceVisualizer(currentInterfaceVisualizer); } } public Collection<Element> getConfigXML() { Vector<Element> config = new Vector<Element>(); Element element; // Selected variable name element = new Element("interface"); element.setText((String) selectInterfaceComboBox.getSelectedItem()); config.add(element); Point pos = mainScrollPane.getViewport().getViewPosition(); element = new Element("scrollpos"); element.setText(pos.x + "," + pos.y); config.add(element); return config; } public boolean setConfigXML(Collection<Element> configXML, boolean visAvailable) { for (Element element : configXML) { if (element.getName().equals("interface")) { setSelectedInterface(element.getText()); } else if (element.getName().equals("scrollpos")) { String[] scrollPos = element.getText().split(","); final Point pos = new Point(Integer.parseInt(scrollPos[0]), Integer.parseInt(scrollPos[1])); EventQueue.invokeLater(new Runnable() { public void run() { mainScrollPane.getViewport().setViewPosition(pos); } }); } } return true; } public String getQuickHelp() { String help = "<b>" + GUI.getDescriptionOf(this) + "</b>"; help += "<p>Lists mote interfaces, and allows mote inspection and interaction via mote interface visualizers."; MoteInterface intf = selectedMoteInterface; if (intf != null) { if (intf instanceof HasQuickHelp) { help += "<p>" + ((HasQuickHelp)intf).getQuickHelp(); } else { help += "<p><b>" + GUI.getDescriptionOf(intf) + "</b>"; help += "<p>No help available"; } } return help; } public Mote getMote() { return mote; } }
/* DetectCycle in directed graph*/ { import java.util.*; import java.io.*; import java.lang.*; class DriverClass { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0) { ArrayList<ArrayList<Integer>> list = new ArrayList<>(); int nov = sc.nextInt(); int edg = sc.nextInt(); for(int i = 0; i < nov+1; i++) list.add(i, new ArrayList<Integer>()); for(int i = 1; i <= edg; i++) { int u = sc.nextInt(); int v = sc.nextInt(); list.get(u).add(v); } if(new DetectCycle().isCyclic(list, nov) == true) System.out.println("1"); else System.out.println("0"); } } } } /*This is a function problem.You only need to complete the function given below*/ /*Complete the function below*/ /* ArrayList<ArrayList<Integer>> list: to represent graph containing 'v' vertices and edges between them V: represent number of vertices */ class DetectCycle { static boolean isCyclic(ArrayList<ArrayList<Integer>> list, int V) { // add your code here //int n = list.size(); boolean vis[] = new boolean[V]; boolean cyc[] = new boolean[V]; int i = 0; for(i=0;i<V; i++){ vis[i] = false; cyc[i] = false; } for(i=0; i<V; i++){ if(isCyclicUtil(list,vis,cyc,i)) return true; } return false; } static boolean isCyclicUtil(ArrayList<ArrayList<Integer>> list, boolean vis[], boolean cyc[], int i){ if(cyc[i]) return true; if(vis[i]) return false; vis[i] = true; cyc[i] = true; Iterator it = list.get(i).listIterator(); while(it.hasNext()){ int k = (int) it.next(); if( isCyclicUtil(list,vis,cyc,k)){ return true; } } cyc[i] = false; return false; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.distributed.internal.membership.gms.fd; import org.apache.geode.distributed.internal.*; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; import org.apache.geode.distributed.internal.membership.NetView; import org.apache.geode.distributed.internal.membership.gms.GMSMember; import org.apache.geode.distributed.internal.membership.gms.ServiceConfig; import org.apache.geode.distributed.internal.membership.gms.Services; import org.apache.geode.distributed.internal.membership.gms.Services.Stopper; import org.apache.geode.distributed.internal.membership.gms.fd.GMSHealthMonitor.ClientSocketHandler; import org.apache.geode.distributed.internal.membership.gms.interfaces.JoinLeave; import org.apache.geode.distributed.internal.membership.gms.interfaces.Manager; import org.apache.geode.distributed.internal.membership.gms.interfaces.Messenger; import org.apache.geode.distributed.internal.membership.gms.messages.HeartbeatMessage; import org.apache.geode.distributed.internal.membership.gms.messages.HeartbeatRequestMessage; import org.apache.geode.distributed.internal.membership.gms.messages.SuspectMembersMessage; import org.apache.geode.distributed.internal.membership.gms.messages.SuspectRequest; import org.apache.geode.internal.net.SocketCreator; import org.apache.geode.internal.Version; import org.apache.geode.internal.net.SocketCreatorFactory; import org.apache.geode.test.junit.categories.FlakyTest; import org.apache.geode.test.junit.categories.IntegrationTest; import org.apache.geode.test.junit.categories.MembershipTest; import org.jgroups.util.UUID; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.io.*; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.TimeUnit; import static org.apache.geode.distributed.ConfigurationProperties.*; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.*; import com.jayway.awaitility.Awaitility; @Category({IntegrationTest.class, MembershipTest.class}) public class GMSHealthMonitorJUnitTest { private Services services; private ServiceConfig mockConfig; private DistributionConfig mockDistConfig; private List<InternalDistributedMember> mockMembers; private Messenger messenger; private JoinLeave joinLeave; private GMSHealthMonitor gmsHealthMonitor; private Manager manager; private long statsId = 123; final long memberTimeout = 1000l; private int[] portRange = new int[] {0, 65535}; private boolean useGMSHealthMonitorTestClass = false; private final int myAddressIndex = 3; @Before public void initMocks() throws UnknownHostException { // System.setProperty("gemfire.bind-address", "localhost"); mockDistConfig = mock(DistributionConfig.class); mockConfig = mock(ServiceConfig.class); messenger = mock(Messenger.class); joinLeave = mock(JoinLeave.class); manager = mock(Manager.class); services = mock(Services.class); Stopper stopper = mock(Stopper.class); Properties nonDefault = new Properties(); nonDefault.put(ACK_WAIT_THRESHOLD, "1"); nonDefault.put(ACK_SEVERE_ALERT_THRESHOLD, "10"); nonDefault.put(DISABLE_TCP, "true"); nonDefault.put(MCAST_PORT, "0"); nonDefault.put(MCAST_TTL, "0"); nonDefault.put(LOG_FILE, ""); nonDefault.put(LOG_LEVEL, "fine"); nonDefault.put(MEMBER_TIMEOUT, "2000"); nonDefault.put(LOCATORS, "localhost[10344]"); DM dm = mock(DM.class); SocketCreatorFactory.setDistributionConfig(new DistributionConfigImpl(new Properties())); InternalDistributedSystem system = InternalDistributedSystem.newInstanceForTesting(dm, nonDefault); when(mockConfig.getDistributionConfig()).thenReturn(mockDistConfig); when(mockConfig.getMemberTimeout()).thenReturn(memberTimeout); when(mockConfig.getMembershipPortRange()).thenReturn(portRange); when(services.getConfig()).thenReturn(mockConfig); when(services.getMessenger()).thenReturn(messenger); when(services.getJoinLeave()).thenReturn(joinLeave); when(services.getCancelCriterion()).thenReturn(stopper); when(services.getManager()).thenReturn(manager); when(services.getStatistics()).thenReturn(new DistributionStats(system, statsId)); when(stopper.isCancelInProgress()).thenReturn(false); if (mockMembers == null) { mockMembers = new ArrayList<InternalDistributedMember>(); for (int i = 0; i < 7; i++) { InternalDistributedMember mbr = new InternalDistributedMember("localhost", 8888 + i); if (i == 0 || i == 1) { mbr.setVmKind(DistributionManager.LOCATOR_DM_TYPE); mbr.getNetMember().setPreferredForCoordinator(true); } mockMembers.add(mbr); } } when(joinLeave.getMemberID()).thenReturn(mockMembers.get(myAddressIndex)); when(messenger.getMemberID()).thenReturn(mockMembers.get(myAddressIndex)); gmsHealthMonitor = new GMSHealthMonitorTest(); gmsHealthMonitor.init(services); gmsHealthMonitor.start(); } @After public void tearDown() { gmsHealthMonitor.stop(); SocketCreatorFactory.close(); // System.getProperties().remove("gemfire.bind-address"); } @Test public void testHMServiceStarted() throws IOException { InternalDistributedMember mbr = new InternalDistributedMember(SocketCreator.getLocalHost(), 12345); mbr.setVmViewId(1); when(messenger.getMemberID()).thenReturn(mbr); gmsHealthMonitor.started(); NetView v = new NetView(mbr, 1, mockMembers); gmsHealthMonitor.processMessage(new HeartbeatRequestMessage(mbr, 1)); verify(messenger, atLeastOnce()).send(any(HeartbeatMessage.class)); Assert.assertEquals(1, gmsHealthMonitor.getStats().getHeartbeatRequestsReceived()); Assert.assertEquals(1, gmsHealthMonitor.getStats().getHeartbeatsSent()); } /** * checks who is next neighbor */ @Test public void testHMNextNeighborVerify() throws IOException { installAView(); Assert.assertEquals(mockMembers.get(myAddressIndex + 1), gmsHealthMonitor.getNextNeighbor()); } // @Category(FlakyTest.class) // GEODE-2073 @Test public void testHMNextNeighborAfterTimeout() throws Exception { System.out.println("testHMNextNeighborAfterTimeout starting"); installAView(); InternalDistributedMember initialNeighbor = mockMembers.get(myAddressIndex + 1); // allow the monitor to give up on the initial "next neighbor" and // move on to the one after it long giveup = System.currentTimeMillis() + (2 * memberTimeout) + 1500; InternalDistributedMember neighbor = gmsHealthMonitor.getNextNeighbor(); while (System.currentTimeMillis() < giveup && neighbor == initialNeighbor) { Thread.sleep(50); neighbor = gmsHealthMonitor.getNextNeighbor(); } // neighbor should change. In order to not be a flaky test we don't demand // that it be myAddressIndex+2 but just require that the neighbor being // monitored has changed System.out.println("testHMNextNeighborAfterTimeout ending"); Assert.assertNotNull(gmsHealthMonitor.getView()); Assert.assertNotEquals("neighbor to not be " + neighbor + "; my ID is " + mockMembers.get(myAddressIndex) + "; view=" + gmsHealthMonitor.getView(), initialNeighbor, neighbor); } /** * it checks neighbor before member-timeout, it should be same */ @Test public void testHMNextNeighborBeforeTimeout() throws IOException { installAView(); // Should we remove these sleeps and force the checkmember directly instead of waiting? try { // member-timeout is 1000 ms. We initiate a check and choose // a new neighbor at 500 ms Thread.sleep(memberTimeout / GMSHealthMonitor.LOGICAL_INTERVAL - 100); } catch (InterruptedException e) { } // neighbor should be same System.out.println("next neighbor is " + gmsHealthMonitor.getNextNeighbor() + "\nmy address is " + mockMembers.get(myAddressIndex) + "\nview is " + joinLeave.getView()); Assert.assertEquals(mockMembers.get(myAddressIndex + 1), gmsHealthMonitor.getNextNeighbor()); } /*** * checks whether member-check thread sends suspectMembers message */ @Test public void testSuspectMembersCalledThroughMemberCheckThread() throws Exception { installAView(); // when the view is installed we start a heartbeat timeout. After // that expires we request a heartbeat Thread.sleep(3 * memberTimeout + 100); System.out.println("testSuspectMembersCalledThroughMemberCheckThread ending"); assertTrue(gmsHealthMonitor.isSuspectMember(mockMembers.get(myAddressIndex + 1))); Assert.assertTrue(gmsHealthMonitor.getStats().getHeartbeatRequestsSent() > 0); Assert.assertTrue(gmsHealthMonitor.getStats().getSuspectsSent() > 0); } private NetView installAView() { System.out.println("installAView starting"); NetView v = new NetView(mockMembers.get(0), 2, mockMembers); // 3rd is current member when(messenger.getMemberID()).thenReturn(mockMembers.get(myAddressIndex)); gmsHealthMonitor.started(); gmsHealthMonitor.installView(v); return v; } private void setFailureDetectionPorts(NetView v) { java.util.Iterator<InternalDistributedMember> itr = mockMembers.iterator(); int port = 7899; while (itr.hasNext()) { v.setFailureDetectionPort(itr.next(), port++); } } /*** * checks ping thread didn't sends suspectMembers message before timeout */ @Test public void testSuspectMembersNotCalledThroughPingThreadBeforeTimeout() { installAView(); InternalDistributedMember neighbor = gmsHealthMonitor.getNextNeighbor(); try { // member-timeout is 1000 ms // plus 100 ms for ack Thread.sleep(memberTimeout - 200); } catch (InterruptedException e) { } assertFalse(gmsHealthMonitor.isSuspectMember(neighbor)); } /*** * Checks whether suspect thread sends suspectMembers message */ @Test public void testSuspectMembersCalledThroughSuspectThread() throws Exception { installAView(); gmsHealthMonitor.suspect(mockMembers.get(1), "Not responding"); Thread.sleep(GMSHealthMonitor.MEMBER_SUSPECT_COLLECTION_INTERVAL + 1000); verify(messenger, atLeastOnce()).send(any(SuspectMembersMessage.class)); Assert.assertTrue(gmsHealthMonitor.getStats().getSuspectsSent() > 0); } /*** * Checks suspect thread doesn't sends suspectMembers message before timeout */ @Test public void testSuspectMembersNotCalledThroughSuspectThreadBeforeTimeout() { installAView(); gmsHealthMonitor.suspect(mockMembers.get(1), "Not responding"); try { // suspect thread timeout is 200 ms Thread.sleep(100l); } catch (InterruptedException e) { } verify(messenger, atLeastOnce()).send(isA(SuspectMembersMessage.class)); Assert.assertTrue(gmsHealthMonitor.getStats().getSuspectsSent() > 0); } /*** * Send remove member message after doing final check, ping Timeout */ @Test public void testRemoveMemberCalled() throws Exception { System.out.println("testRemoveMemberCalled starting"); NetView v = new NetView(mockMembers.get(0), 2, mockMembers); // 3rd is current member when(messenger.getMemberID()).thenReturn(mockMembers.get(0)); // coordinator and local member gmsHealthMonitor.started(); gmsHealthMonitor.installView(v); Thread.sleep(memberTimeout / GMSHealthMonitor.LOGICAL_INTERVAL); ArrayList<InternalDistributedMember> recipient = new ArrayList<InternalDistributedMember>(); recipient.add(mockMembers.get(0)); ArrayList<SuspectRequest> as = new ArrayList<SuspectRequest>(); SuspectRequest sr = new SuspectRequest(mockMembers.get(1), "Not Responding");// removing member // 1 as.add(sr); SuspectMembersMessage sm = new SuspectMembersMessage(recipient, as); sm.setSender(mockMembers.get(0)); gmsHealthMonitor.processMessage(sm); Awaitility.await("waiting for remove(member) to be invoked") .atMost(3 * memberTimeout, TimeUnit.SECONDS).until(() -> { verify(joinLeave, atLeastOnce()).remove(any(InternalDistributedMember.class), any(String.class)); }); Assert.assertTrue(gmsHealthMonitor.getStats().getSuspectsReceived() > 0); } /*** * Shouldn't send remove member message before doing final check, or before ping Timeout */ @Test public void testRemoveMemberNotCalledBeforeTimeout() { System.out.println("testRemoveMemberNotCalledBeforeTimeout starting"); NetView v = new NetView(mockMembers.get(0), 2, mockMembers); // 3rd is current member when(messenger.getMemberID()).thenReturn(mockMembers.get(0)); // coordinator and local member when(joinLeave.getMemberID()).thenReturn(mockMembers.get(0)); // coordinator and local member gmsHealthMonitor.started(); gmsHealthMonitor.installView(v); ArrayList<InternalDistributedMember> recipient = new ArrayList<InternalDistributedMember>(); recipient.add(mockMembers.get(0)); ArrayList<SuspectRequest> as = new ArrayList<SuspectRequest>(); SuspectRequest sr = new SuspectRequest(mockMembers.get(1), "Not Responding");// removing member // 1 as.add(sr); SuspectMembersMessage sm = new SuspectMembersMessage(recipient, as); sm.setSender(mockMembers.get(0)); gmsHealthMonitor.processMessage(sm); try { // this happens after final check, ping timeout Thread.sleep(memberTimeout - 100); } catch (InterruptedException e) { } System.out.println("testRemoveMemberNotCalledBeforeTimeout ending"); verify(joinLeave, never()).remove(any(InternalDistributedMember.class), any(String.class)); Assert.assertTrue(gmsHealthMonitor.getStats().getSuspectsReceived() > 0); } /*** * Send remove member message after doing final check for coordinator, ping timeout This test * trying to remove coordinator */ @Test public void testRemoveMemberCalledAfterDoingFinalCheckOnCoordinator() throws Exception { NetView v = new NetView(mockMembers.get(0), 2, mockMembers); // preferred coordinators are 0 and 1 when(messenger.getMemberID()).thenReturn(mockMembers.get(1));// next preferred coordinator gmsHealthMonitor.started(); gmsHealthMonitor.installView(v); Thread.sleep(memberTimeout / GMSHealthMonitor.LOGICAL_INTERVAL); ArrayList<InternalDistributedMember> recipient = new ArrayList<InternalDistributedMember>(); recipient.add(mockMembers.get(0)); recipient.add(mockMembers.get(1)); ArrayList<SuspectRequest> as = new ArrayList<SuspectRequest>(); SuspectRequest sr = new SuspectRequest(mockMembers.get(0), "Not Responding");// removing // coordinator as.add(sr); SuspectMembersMessage sm = new SuspectMembersMessage(recipient, as); sm.setSender(mockMembers.get(myAddressIndex + 1));// member 4 sends suspect message gmsHealthMonitor.processMessage(sm); // this happens after final check, ping timeout = 1000 ms Thread.sleep(memberTimeout + 200); verify(joinLeave, atLeastOnce()).remove(any(InternalDistributedMember.class), any(String.class)); Assert.assertTrue(gmsHealthMonitor.getStats().getSuspectsReceived() > 0); } /*** * validates HealthMonitor.CheckIfAvailable api */ @Test public void testCheckIfAvailableNoHeartBeatDontRemoveMember() { installAView(); long startTime = System.currentTimeMillis(); boolean retVal = gmsHealthMonitor.checkIfAvailable(mockMembers.get(1), "Not responding", true); long timeTaken = System.currentTimeMillis() - startTime; assertFalse("CheckIfAvailable should have return false", retVal); assertTrue("This should have taken member ping timeout 100ms but it took " + timeTaken, timeTaken >= gmsHealthMonitor.memberTimeout); } @Test public void testCheckIfAvailableWithSimulatedHeartBeat() { NetView v = installAView(); InternalDistributedMember memberToCheck = mockMembers.get(1); HeartbeatMessage fakeHeartbeat = new HeartbeatMessage(); fakeHeartbeat.setSender(memberToCheck); when(messenger.send(any(HeartbeatRequestMessage.class))).then(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { gmsHealthMonitor.processMessage(fakeHeartbeat); return null; } }); boolean retVal = gmsHealthMonitor.checkIfAvailable(memberToCheck, "Not responding", true); assertTrue("CheckIfAvailable should have return true", retVal); } @Test public void testCheckIfAvailableWithSimulatedHeartBeatWithTcpCheck() { System.out.println("testCheckIfAvailableWithSimulatedHeartBeatWithTcpCheck"); useGMSHealthMonitorTestClass = true; try { NetView v = installAView(); setFailureDetectionPorts(v); InternalDistributedMember memberToCheck = mockMembers.get(1); boolean retVal = gmsHealthMonitor.checkIfAvailable(memberToCheck, "Not responding", true); assertTrue("CheckIfAvailable should have return true", retVal); } finally { useGMSHealthMonitorTestClass = false; } } @Test public void testShutdown() { installAView(); gmsHealthMonitor.stop(); try { // this happens after final check, membertimeout = 1000 Thread.sleep(100l); } catch (InterruptedException e) { } assertTrue("HeathMonitor should have shutdown", gmsHealthMonitor.isShutdown()); } @Test public void testCreateServerSocket() throws Exception { try (ServerSocket socket = gmsHealthMonitor.createServerSocket(InetAddress.getLocalHost(), portRange)) { Assert.assertTrue( portRange[0] <= socket.getLocalPort() && socket.getLocalPort() <= portRange[1]); } } @Test public void testCreateServerSocketPortRangeInvalid() throws Exception { try (ServerSocket socket = gmsHealthMonitor.createServerSocket(InetAddress.getLocalHost(), new int[] {-1, -1})) { Assert.fail("socket was created with invalid port range"); } catch (IllegalArgumentException e) { } } @Test public void testClientSocketHandler() throws Exception { int viewId = 2; long msb = 3; long lsb = 4; GMSMember otherMember = createGMSMember(Version.CURRENT_ORDINAL, viewId, msb, lsb); GMSMember gmsMember = createGMSMember(Version.CURRENT_ORDINAL, viewId, msb, lsb); executeTestClientSocketHandler(gmsMember, otherMember, GMSHealthMonitor.OK); } @Test public void testClientSocketHandlerWhenMsbDoNotMatch() throws Exception { int viewId = 2; long msb = 3; long lsb = 4; GMSMember otherMember = createGMSMember(Version.CURRENT_ORDINAL, viewId, msb + 1, lsb); GMSMember gmsMember = createGMSMember(Version.CURRENT_ORDINAL, viewId, msb, lsb); executeTestClientSocketHandler(gmsMember, otherMember, GMSHealthMonitor.ERROR); } @Test public void testClientSocketHandlerWhenLsbDoNotMatch() throws Exception { int viewId = 2; long msb = 3; long lsb = 4; GMSMember otherMember = createGMSMember(Version.CURRENT_ORDINAL, viewId, msb, lsb + 1); GMSMember gmsMember = createGMSMember(Version.CURRENT_ORDINAL, viewId, msb, lsb); executeTestClientSocketHandler(gmsMember, otherMember, GMSHealthMonitor.ERROR); } @Test public void testClientSocketHandlerWhenViewIdDoNotMatch() throws Exception { int viewId = 2; long msb = 3; long lsb = 4; GMSMember otherMember = createGMSMember(Version.CURRENT_ORDINAL, viewId + 1, msb, lsb); GMSMember gmsMember = createGMSMember(Version.CURRENT_ORDINAL, viewId, msb, lsb); executeTestClientSocketHandler(gmsMember, otherMember, GMSHealthMonitor.ERROR); } public void executeTestClientSocketHandler(GMSMember gmsMember, GMSMember otherMember, int expectedResult) throws Exception { // We have already set the view id in the member but when creating the IDM it resets it to -1 // for some reason int viewId = gmsMember.getVmViewId(); InternalDistributedMember testMember = new InternalDistributedMember("localhost", 9000, Version.CURRENT, gmsMember); // We set to our expected test viewId in the IDM as well as reseting the gms member testMember.setVmViewId(viewId); gmsMember.setBirthViewId(viewId); // Set up the incoming/received bytes. We just wrap output streams and write out the gms member // information byte[] receivedBytes = writeMemberToBytes(otherMember); InputStream mockInputStream = new ByteArrayInputStream(receivedBytes); // configure the mock to return the mocked incoming bytes and provide an outputstream that we // will check Socket fakeSocket = mock(Socket.class); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); when(fakeSocket.getInputStream()).thenReturn(mockInputStream); when(fakeSocket.getOutputStream()).thenReturn(outputStream); // run the socket handler gmsHealthMonitor.setLocalAddress(testMember); ClientSocketHandler handler = gmsHealthMonitor.new ClientSocketHandler(fakeSocket); handler.run(); // verify the written bytes are as expected DataInputStream dis = new DataInputStream(new ByteArrayInputStream(outputStream.toByteArray())); int byteReply = dis.read(); Assert.assertEquals(expectedResult, byteReply); Assert.assertTrue(gmsHealthMonitor.getStats().getFinalCheckResponsesSent() > 0); Assert.assertTrue(gmsHealthMonitor.getStats().getTcpFinalCheckResponsesSent() > 0); } @Test public void testBeSickAndPlayDead() throws Exception { NetView v = new NetView(mockMembers.get(0), 2, mockMembers); gmsHealthMonitor.installView(v); gmsHealthMonitor.beSick(); // a sick member will not respond to a heartbeat request HeartbeatRequestMessage req = new HeartbeatRequestMessage(mockMembers.get(0), 10); req.setSender(mockMembers.get(0)); gmsHealthMonitor.processMessage(req); verify(messenger, never()).send(isA(HeartbeatMessage.class)); // a sick member will not record a heartbeat from another member HeartbeatMessage hb = new HeartbeatMessage(-1); hb.setSender(mockMembers.get(0)); gmsHealthMonitor.processMessage(hb); assertTrue(gmsHealthMonitor.memberTimeStamps.get(hb.getSender()) == null); // a sick member will not take action on a Suspect message from another member SuspectMembersMessage smm = mock(SuspectMembersMessage.class); Error err = new AssertionError("expected suspect message to be ignored"); when(smm.getMembers()).thenThrow(err); when(smm.getSender()).thenThrow(err); when(smm.getDSFID()).thenCallRealMethod(); gmsHealthMonitor.processMessage(smm); } @Test public void testDoTCPCheckMemberWithOkStatus() throws Exception { executeTestDoTCPCheck(GMSHealthMonitor.OK, true); } @Test public void testDoTCPCheckMemberWithErrorStatus() throws Exception { executeTestDoTCPCheck(GMSHealthMonitor.ERROR, false); } @Test public void testDoTCPCheckMemberWithUnkownStatus() throws Exception { executeTestDoTCPCheck(GMSHealthMonitor.ERROR + 100, false); } private void executeTestDoTCPCheck(int receivedStatus, boolean expectedResult) throws Exception { InternalDistributedMember otherMember = createInternalDistributedMember(Version.CURRENT_ORDINAL, 0, 1, 1); InternalDistributedMember gmsMember = createInternalDistributedMember(Version.CURRENT_ORDINAL, 0, 1, 1); // Set up the incoming/received bytes. We just wrap output streams and write out the gms member // information ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(receivedStatus); byte[] receivedBytes = baos.toByteArray(); InputStream mockInputStream = new ByteArrayInputStream(receivedBytes); Socket fakeSocket = mock(Socket.class); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); when(fakeSocket.getInputStream()).thenReturn(mockInputStream); when(fakeSocket.getOutputStream()).thenReturn(outputStream); when(fakeSocket.isConnected()).thenReturn(true); Assert.assertEquals(expectedResult, gmsHealthMonitor.doTCPCheckMember(otherMember, fakeSocket)); Assert.assertTrue(gmsHealthMonitor.getStats().getFinalCheckRequestsSent() > 0); Assert.assertTrue(gmsHealthMonitor.getStats().getTcpFinalCheckRequestsSent() > 0); Assert.assertTrue(gmsHealthMonitor.getStats().getFinalCheckResponsesReceived() > 0); Assert.assertTrue(gmsHealthMonitor.getStats().getTcpFinalCheckResponsesReceived() > 0); // we can check to see if the gms member information was written out by the tcp check byte[] bytesWritten = outputStream.toByteArray(); Assert.assertArrayEquals(writeMemberToBytes((GMSMember) gmsMember.getNetMember()), bytesWritten); } private InternalDistributedMember createInternalDistributedMember(short version, int viewId, long msb, long lsb) throws UnknownHostException { GMSMember gmsMember = createGMSMember(version, viewId, msb, lsb); InternalDistributedMember idm = new InternalDistributedMember("localhost", 9000, Version.CURRENT, gmsMember); // We set to our expected test viewId in the IDM as well as reseting the gms member idm.setVmViewId(viewId); gmsMember.setBirthViewId(viewId); return idm; } private GMSMember createGMSMember(short version, int viewId, long msb, long lsb) throws UnknownHostException { GMSMember gmsMember = new GMSMember(); gmsMember.setVersionOrdinal(version); gmsMember.setBirthViewId(viewId); gmsMember.setUUID(new UUID(msb, lsb)); gmsMember.setInetAddr(InetAddress.getLocalHost()); return gmsMember; } private byte[] writeMemberToBytes(GMSMember gmsMember) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dataReceive = new DataOutputStream(baos); gmsHealthMonitor.writeMemberToStream(gmsMember, dataReceive); return baos.toByteArray(); } public class GMSHealthMonitorTest extends GMSHealthMonitor { @Override boolean doTCPCheckMember(InternalDistributedMember suspectMember, int port) { if (useGMSHealthMonitorTestClass) { HeartbeatMessage fakeHeartbeat = new HeartbeatMessage(); fakeHeartbeat.setSender(suspectMember); gmsHealthMonitor.processMessage(fakeHeartbeat); return false; } return super.doTCPCheckMember(suspectMember, port); } } }
/** * https://leetcode.com/problems/kth-largest-element-in-a-stream/ * https://leetcode.com/problems/kth-largest-element-in-a-stream/discuss/149050/Java-Priority-Queue */ class KthLargest { final int k; final PriorityQueue<Integer> q; public KthLargest(int k, int[] a) { this.k = k; q = new PriorityQueue<Integer>(k); for (int n : a) add(n); } public int add(int n) { if (q.size() < k) { q.offer(n); } else if (q.peek() < n) { q.poll(); q.offer(n); } return q.peek(); } } /** * Your KthLargest object will be instantiated and called as such: * KthLargest obj = new KthLargest(k, nums); * int param_1 = obj.add(val); */
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.aliyun.openservices.odps.console.cupid.common; import com.aliyun.odps.Odps; import com.aliyun.odps.OdpsException; import com.aliyun.odps.account.AliyunAccount; import com.aliyun.openservices.odps.console.ExecutionContext; public class BearerTokenGenerator { public static String getBearerToken(ExecutionContext cxt) throws OdpsException { AliyunAccount account = new AliyunAccount(cxt.getAccessId(), cxt.getAccessKey()); Odps odps = new Odps(account); odps.setEndpoint(cxt.getEndpoint()); odps.setDefaultProject(cxt.getProjectName()); // expires in 7 days String policy = "{\n" + "\"expires_in_hours\": 168,\n" + "\"policy\": {\n" + "\"Statement\": [\n" + "{\n" + "\"Action\": [\"odps:*\"],\n" + "\"Effect\": \"Allow\",\n" + "\"Resource\": \"acs:odps:*:*\"\n" + "}\n" + "],\n" + "\"Version\": \"1\"\n" + "}\n" + "}\n"; return odps.projects().get().getSecurityManager().generateAuthorizationToken(policy, "bearer"); } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2020.11.04 at 11:05:52 AM EST // package net.opengis.gml; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import org.w3.xlink.v1999.ActuateType; import org.w3.xlink.v1999.ShowType; import org.w3.xlink.v1999.TypeType; /** * gml:AbstractGeneralOperationParameterPropertyType is a property type for association roles to an operation parameter or group, either referencing or containing the definition of that parameter or group. * * <p>Java class for AbstractGeneralOperationParameterPropertyType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="AbstractGeneralOperationParameterPropertyType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence minOccurs="0"> * &lt;element ref="{http://www.opengis.net/gml/3.2}AbstractGeneralOperationParameter"/> * &lt;/sequence> * &lt;attGroup ref="{http://www.opengis.net/gml/3.2}AssociationAttributeGroup"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AbstractGeneralOperationParameterPropertyType", propOrder = { "abstractGeneralOperationParameter" }) public class AbstractGeneralOperationParameterPropertyType { @XmlElementRef(name = "AbstractGeneralOperationParameter", namespace = "http://www.opengis.net/gml/3.2", type = JAXBElement.class, required = false) protected JAXBElement<? extends AbstractGeneralOperationParameterType> abstractGeneralOperationParameter; @XmlAttribute(name = "nilReason") protected List<String> nilReason; @XmlAttribute(name = "remoteSchema", namespace = "http://www.opengis.net/gml/3.2") @XmlSchemaType(name = "anyURI") protected String remoteSchema; @XmlAttribute(name = "type", namespace = "http://www.w3.org/1999/xlink") protected TypeType type; @XmlAttribute(name = "href", namespace = "http://www.w3.org/1999/xlink") protected String href; @XmlAttribute(name = "role", namespace = "http://www.w3.org/1999/xlink") protected String role; @XmlAttribute(name = "arcrole", namespace = "http://www.w3.org/1999/xlink") protected String arcrole; @XmlAttribute(name = "title", namespace = "http://www.w3.org/1999/xlink") protected String titleAttribute; @XmlAttribute(name = "show", namespace = "http://www.w3.org/1999/xlink") protected ShowType show; @XmlAttribute(name = "actuate", namespace = "http://www.w3.org/1999/xlink") protected ActuateType actuate; /** * Gets the value of the abstractGeneralOperationParameter property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link OperationParameterType }{@code >} * {@link JAXBElement }{@code <}{@link OperationParameterGroupType }{@code >} * {@link JAXBElement }{@code <}{@link AbstractGeneralOperationParameterType }{@code >} * */ public JAXBElement<? extends AbstractGeneralOperationParameterType> getAbstractGeneralOperationParameter() { return abstractGeneralOperationParameter; } /** * Sets the value of the abstractGeneralOperationParameter property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link OperationParameterType }{@code >} * {@link JAXBElement }{@code <}{@link OperationParameterGroupType }{@code >} * {@link JAXBElement }{@code <}{@link AbstractGeneralOperationParameterType }{@code >} * */ public void setAbstractGeneralOperationParameter(JAXBElement<? extends AbstractGeneralOperationParameterType> value) { this.abstractGeneralOperationParameter = value; } /** * Gets the value of the nilReason property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the nilReason property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNilReason().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getNilReason() { if (nilReason == null) { nilReason = new ArrayList<String>(); } return this.nilReason; } /** * Gets the value of the remoteSchema property. * * @return * possible object is * {@link String } * */ public String getRemoteSchema() { return remoteSchema; } /** * Sets the value of the remoteSchema property. * * @param value * allowed object is * {@link String } * */ public void setRemoteSchema(String value) { this.remoteSchema = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link TypeType } * */ public TypeType getType() { if (type == null) { return TypeType.SIMPLE; } else { return type; } } /** * Sets the value of the type property. * * @param value * allowed object is * {@link TypeType } * */ public void setType(TypeType value) { this.type = value; } /** * Gets the value of the href property. * * @return * possible object is * {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is * {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the role property. * * @return * possible object is * {@link String } * */ public String getRole() { return role; } /** * Sets the value of the role property. * * @param value * allowed object is * {@link String } * */ public void setRole(String value) { this.role = value; } /** * Gets the value of the arcrole property. * * @return * possible object is * {@link String } * */ public String getArcrole() { return arcrole; } /** * Sets the value of the arcrole property. * * @param value * allowed object is * {@link String } * */ public void setArcrole(String value) { this.arcrole = value; } /** * Gets the value of the titleAttribute property. * * @return * possible object is * {@link String } * */ public String getTitleAttribute() { return titleAttribute; } /** * Sets the value of the titleAttribute property. * * @param value * allowed object is * {@link String } * */ public void setTitleAttribute(String value) { this.titleAttribute = value; } /** * Gets the value of the show property. * * @return * possible object is * {@link ShowType } * */ public ShowType getShow() { return show; } /** * Sets the value of the show property. * * @param value * allowed object is * {@link ShowType } * */ public void setShow(ShowType value) { this.show = value; } /** * Gets the value of the actuate property. * * @return * possible object is * {@link ActuateType } * */ public ActuateType getActuate() { return actuate; } /** * Sets the value of the actuate property. * * @param value * allowed object is * {@link ActuateType } * */ public void setActuate(ActuateType value) { this.actuate = value; } }
/* This file is part of the iText (R) project. Copyright (c) 1998-2020 iText Group NV Authors: iText Software. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation with the addition of the following permission added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, see http://www.gnu.org/licenses or write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA, 02110-1301 USA, or download the license from the following URL: http://itextpdf.com/terms-of-use/ The interactive user interfaces in modified source and object code versions of this program must display Appropriate Legal Notices, as required under Section 5 of the GNU Affero General Public License. In accordance with Section 7(b) of the GNU Affero General Public License, a covered work must retain the producer line in every PDF that is created or manipulated using iText. You can be released from the requirements of the license by purchasing a commercial license. Buying such a license is mandatory as soon as you develop commercial activities involving the iText software without disclosing the source code of your own applications. These activities include: offering paid services to customers as an ASP, serving PDFs on the fly in a web application, shipping iText with a closed source product. For more information, please contact iText Software Corp. at this address: sales@itextpdf.com */ package com.itextpdf.html2pdf.css.w3c.css21.normal_flow; import com.itextpdf.html2pdf.css.w3c.W3CCssTest; public class WidthAppliesTo015Test extends W3CCssTest { @Override protected String getHtmlFileName() { return "width-applies-to-015.xht"; } }
package ro.pub.cs.systems.eim.modelpracticaltest02; import android.util.Log; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; public class ClientThread extends Thread{ private String address; private int port; private String city; private String informationType; private TextView weatherForecastTextView; private Socket socket; public ClientThread(String address, int port, String city, String informationType, TextView weatherForecastTextView) { this.address = address; this.port = port; this.city = city; this.informationType = informationType; this.weatherForecastTextView = weatherForecastTextView; } @Override public void run() { try { socket = new Socket(address, port); if (socket == null) { Log.e(Constants.TAG, "[CLIENT THREAD] Could not create socket!"); return; } BufferedReader bufferedReader = Utilities.getReader(socket); PrintWriter printWriter = Utilities.getWriter(socket); if (bufferedReader == null || printWriter == null) { Log.e(Constants.TAG, "[CLIENT THREAD] Buffered Reader / Print Writer are null!"); return; } printWriter.println(city); printWriter.flush(); printWriter.println(informationType); printWriter.flush(); String weatherInformation; while ((weatherInformation = bufferedReader.readLine()) != null) { final String finalizedWeateherInformation = weatherInformation; weatherForecastTextView.post(new Runnable() { @Override public void run() { weatherForecastTextView.setText(finalizedWeateherInformation); } }); } } catch (IOException ioException) { Log.e(Constants.TAG, "[CLIENT THREAD] An exception has occurred: " + ioException.getMessage()); // if (Constants.DEBUG) { // ioException.printStackTrace(); // } } finally { if (socket != null) { try { socket.close(); } catch (IOException ioException) { Log.e(Constants.TAG, "[CLIENT THREAD] An exception has occurred: " + ioException.getMessage()); // if (Constants.DEBUG) { // ioException.printStackTrace(); // } } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.network.models; import com.azure.core.annotation.Fluent; import com.azure.resourcemanager.network.NetworkManager; import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsBatchDeletion; import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsDeletingByResourceGroup; import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsGettingById; import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsGettingByResourceGroup; import com.azure.resourcemanager.resources.fluentcore.arm.collection.SupportsListingByResourceGroup; import com.azure.resourcemanager.resources.fluentcore.arm.models.HasManager; import com.azure.resourcemanager.resources.fluentcore.collection.SupportsBatchCreation; import com.azure.resourcemanager.resources.fluentcore.collection.SupportsCreating; import com.azure.resourcemanager.resources.fluentcore.collection.SupportsDeletingById; import com.azure.resourcemanager.resources.fluentcore.collection.SupportsListing; import reactor.core.publisher.Flux; import java.util.Collection; /** Entry point to application gateway management API in Azure. */ @Fluent() public interface ApplicationGateways extends SupportsCreating<ApplicationGateway.DefinitionStages.Blank>, SupportsListing<ApplicationGateway>, SupportsListingByResourceGroup<ApplicationGateway>, SupportsGettingByResourceGroup<ApplicationGateway>, SupportsGettingById<ApplicationGateway>, SupportsDeletingById, SupportsDeletingByResourceGroup, SupportsBatchCreation<ApplicationGateway>, SupportsBatchDeletion, HasManager<NetworkManager> { /** * Starts the specified application gateways. * * @param ids application gateway resource ids */ void start(String... ids); /** * Starts the specified application gateways. * * @param ids application gateway resource ids */ void start(Collection<String> ids); /** * Starts the specified application gateways in parallel asynchronously. * * @param ids application gateway resource id * @return an emitter of the resource ID for each successfully started application gateway */ Flux<String> startAsync(String... ids); /** * Starts the specified application gateways in parallel asynchronously. * * @param ids application gateway resource id * @return an emitter of the resource ID for each successfully started application gateway */ Flux<String> startAsync(Collection<String> ids); /** * Stops the specified application gateways. * * @param ids application gateway resource ids */ void stop(String... ids); /** * Stops the specified application gateways. * * @param ids application gateway resource ids */ void stop(Collection<String> ids); /** * Stops the specified application gateways in parallel asynchronously. * * @param ids application gateway resource ids * @return an emitter of the resource ID for each successfully stopped application gateway */ Flux<String> stopAsync(String... ids); /** * Stops the specified application gateways in parallel asynchronously. * * @param ids application gateway resource id * @return an emitter of the resource ID for each successfully stopped application gateway */ Flux<String> stopAsync(Collection<String> ids); }
package com.ms.utils; import cn.hutool.core.bean.BeanUtil; import com.ms.entity.User; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import java.util.Date; /** * @author Ming */ @Component @Slf4j public class GmtUtil { @Resource private HttpSession session; public void setGmtCreate(Object bean){ User u = (User) session.getAttribute("user"); if ( u != null){ try { BeanUtil.setProperty(bean,"gmtCreate",u.getUsername()); BeanUtil.setProperty(bean,"gmtCreateTime",new Date()); } catch (Exception e) { log.error("设置gmt错误:",e); } } } public void setGmtUpdate(Object bean){ User u = (User) session.getAttribute("user"); if ( u != null){ try { BeanUtil.setProperty(bean,"gmtUpdate",u.getUsername()); BeanUtil.setProperty(bean,"gmtUpdateTime",new Date()); } catch (Exception e) { log.error("设置gmt错误:",e); } } } }
package snow.ast; import java.util.Iterator; import snow.token.Token; public class NumberLiteral extends ASTLeaf { public NumberLiteral(Token t) { super(t); // TODO Auto-generated constructor stub } public int value(){return token().getNumber();} }
package com.nai.gulimall.product.feign; import com.nai.gulimall.common.to.SkuReductionTo; import com.nai.gulimall.common.to.SpuBoundTo; import com.nai.gulimall.common.utils.R; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @FeignClient("gulimall-coupon") public interface CouponFeignService { /** * 1.CouponFeignService.saveSpuBound(spuBoundTo); * 1).@RequestBody将这个对象转为JSON * 2).找到gilimall-coupon服务,给/coupon/skuladder/save发送求情. * 将上一步转的JSON放在请求体位置,发送请求 * 3).对方服务收到请求.请求体里有JSON数据. * (@RequestBody SpuBoundsEntity spuBounds):将请求体的JSON转为SpuBoundsEntity; * 只要JSON数据模型是兼容的,双方服务无需使用同一个to. * @param spuBoundTo * @return */ @PostMapping("/coupon/spuBounds/save") R saveSpuBound(@RequestBody SpuBoundTo spuBoundTo); @PostMapping("/coupon/skuFullReduction/saveInfo") R saveSkuReduction(@RequestBody SkuReductionTo skuReductionTo); }
/* * 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.oodt.cas.metadata; // JDK Input/output import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.IOException; // Junit Testing framework import junit.framework.TestCase; /** * Base test case for metadata tests. Provides access to test data files. * * @author Kelly */ public class MetadataTestCase extends TestCase { /** * Construct a metadata test case. * * @param name Case name. */ public MetadataTestCase(String name) { super(name); } /** * Augment set up of a test case by creating a play directory where we can temporarily * keep our test data files. * * @throws Exception If any errors occur in directory setup, or if superclass setUp throws it. */ public void setUp() throws Exception { super.setUp(); // Set up the framework test harness tmpDir = File.createTempFile("metadata", ".tests"); // Get a temporary file if (!tmpDir.delete()) // File?! We don't want no stinkin' file throw new IOException("Cannot delete temporary file " + tmpDir); if (!tmpDir.mkdirs()) // Directory is what we want throw new IOException("Cannot create temporary directory " + tmpDir); //tmpDir.deleteOnExit(); } /** * Augment tear down of a test case by cleaning up our play directory. * * @throws Exception if any errors occur in directory deletion, or if superclass tearDown throws it. */ public void tearDown() throws Exception { String[] entries = tmpDir.list(); // Get contents of our play area for (int i = 0; i < entries.length; ++i) { // Step through each one File entry = new File(tmpDir, entries[i]); // Make a file out of it if (!entry.delete()) // Nuke it if possible ... throw new IOException("Cannot delete temporary file " + entry); // Or if not ... } if (!tmpDir.delete()) // Nuke the play area throw new IOException("Cannot delete temporary directory " + tmpDir); // Or if not ... super.tearDown(); // Tear down the test harness } /** * Get a named test data file. This will yield a test data file using the standard Java resource mechanism * (ie, fetching out of a jar, from the class path, etc.) and stick it in a temporary file, since the * metadata API works with files it can both name and use, not just streams of file data. * * @param name Name of the test data file to retrieve. * @return A {@link java.io.File} containing the named test dat. * @throws IOException If an I/O error occurs. */ public File getTestDataFile(String name) throws IOException { InputStream in = MetadataTestCase.class.getResourceAsStream(name); // Not found? Try resource stream if (in == null) // Still not found? Bummer. throw new IllegalArgumentException("Unknown test data file `" + name + "`; not found in resource path"); File fn = new File(tmpDir, name); // What the tests want: Files. BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fn)); // Copy data to it in = new BufferedInputStream(in); // Buffer for efficiency byte[] buf = new byte[512]; // Classic disk page size for (;;) { // For ever int c = in.read(buf); // Read into our buffer if (c == -1) break; // EOF? Done. out.write(buf, 0, c); // Not EOF? Copy out. } in.close(); out.close(); return fn; } /** Play area */ private File tmpDir; }
/* * Copyright (c) 2007-2011 by The Broad Institute of MIT and Harvard. All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR * WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER * OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE * TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES * OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, * ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER * THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT * SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. */ /* * TrackPanel.java * * Created on Sep 5, 2007, 4:09:39 PM * * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.ui.panel; import java.awt.Color; import java.awt.Cursor; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.event.MouseEvent; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.event.MouseInputAdapter; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.PreferenceManager; import org.broad.igv.feature.Chromosome; import org.broad.igv.feature.genome.Genome; import org.broad.igv.ui.FontManager; import org.broad.igv.ui.IGV; import org.broad.igv.ui.UIConstants; import org.broad.igv.ui.WaitCursorManager; import org.broad.igv.util.LongRunningTask; import org.broad.igv.util.NamedRunnable; /** * @author jrobinso * <p/> * Lucida Blackletter * Lucida Bright * Lucida Calligraphy * Lucida Fax * Lucida Grande * Lucida Handwriting * Lucida Sans * Lucida Sans Typewriter */ public class RulerPanel extends JPanel { private static Logger log = Logger.getLogger(RulerPanel.class); // TODO -- get from preferences boolean drawSpan = true; boolean drawEllipsis = false; private Font tickFont = FontManager.getFont(Font.BOLD, 9, PreferenceManager.RULER_FONT_SCALE); private Font spanFont = FontManager.getFont(Font.BOLD, 12, PreferenceManager.RULER_FONT_SCALE); private List<ClickLink> chromosomeRects = new ArrayList(); private static Color dragColor = new Color(.5f, .5f, 1f, .3f); private static Color zoomBoundColor = new Color(0.5f, 0.5f, 0.5f); boolean dragging = false; int dragStart; int dragEnd; public static final String WHOLE_GENOME_TOOLTIP = "<html>Click on a chromosome number to jump to that chromosome," + "<br>or click and drag to zoom in."; public static final String CHROM_TOOLTIP = "Click and drag to zoom in."; ReferenceFrame frame; public RulerPanel(ReferenceFrame frame) { this.frame = frame; init(); } private boolean isWholeGenomeView() { return frame.getChrName().equals(Globals.CHR_ALL); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.black); if (isWholeGenomeView()) { drawChromosomeTicks(g); } else { // Clear panel drawTicks(g); if (drawSpan) { drawSpan(g); } if (drawEllipsis) { drawEllipsis(g); } } if (dragging) { g.setColor(dragColor); int start = Math.min(dragStart, dragEnd); int w = Math.abs(dragEnd - dragStart); final int height = getHeight(); g.fillRect(start, 0, w, height); g.setColor(zoomBoundColor); g.drawLine(dragStart, 0, dragStart, height); g.drawLine(dragEnd, 0, dragEnd, height); } } private void drawSpan(Graphics g) { //TODO -- hack int w = getWidth(); g.setFont(spanFont); // Positions are 1/2 open, subtract 1 to compensate int range = (int) (frame.getScale() * w) + 1; // TODO -- hack, assumes location unit for whole genome is kilo-base boolean scaleInKB = frame.getChrName().equals(Globals.CHR_ALL); TickSpacing ts = findSpacing(range,scaleInKB); String rangeString = formatNumber((double) range / ts.getUnitMultiplier()) + " " + ts.getMajorUnit(); int strWidth = g.getFontMetrics().stringWidth(rangeString); int strHeight = g.getFontMetrics().getAscent(); int strPosition = (w - strWidth) / 2; int lineY = getHeight() - 35 - strHeight / 2; g.drawLine(0, lineY, (w - strWidth) / 2 - 10, lineY); int[] arrowX = {0, 10, 10}; int[] arrowY = {lineY, lineY + 3, lineY - 3}; g.fillPolygon(arrowX, arrowY, arrowX.length); g.drawLine((w + strWidth) / 2 + 10, lineY, w, lineY); arrowX = new int[]{w, w - 10, w - 10}; g.fillPolygon(arrowX, arrowY, arrowX.length); g.drawString(rangeString, strPosition, getHeight() - 35); } private void drawEllipsis(Graphics g) { double cytobandScale = ((double) frame.getChromosomeLength()) / getWidth(); double maxPixel = frame.getMaxPixel(); //visibleFraction = maxPixel < 0 ? 0 : ((double) getViewContext().getDataPanelWidth()) / maxPixel; int start = (int) ((frame.getOrigin()) / cytobandScale); int span = (int) ((getWidth() * frame.getScale()) / cytobandScale); int end = start + span; g.drawLine(start, 0, 0, getHeight()); g.drawLine(end, 0, getWidth(), getHeight()); } private void drawTicks(Graphics g) { int w = getWidth(); if (w < 200) { return; } g.setFont(tickFont); // TODO -- hack, assumes location unit for whole genome is kilo-base boolean scaleInKB = frame.getChrName().equals(Globals.CHR_ALL); int range = (int) (w * frame.getScale()); TickSpacing ts = findSpacing(range, scaleInKB); double spacing = ts.getMajorTick(); // Find starting point closest to the current origin int nTick = (int) (frame.getOrigin() / spacing) - 1; int l = (int) (nTick * spacing); int x = frame.getScreenPosition(l - 1); // 0 vs 1 based coordinates //int strEnd = Integer.MIN_VALUE; int deltaX = Math.abs(frame.getScreenPosition(nTick * spacing) - frame.getScreenPosition(nTick * spacing + 1)); while (x < getWidth()) { l = (int) (nTick * spacing); x = frame.getScreenPosition(l - 1); String chrPosition = formatNumber((double) l / ts.getUnitMultiplier()) + " " + ts.getMajorUnit(); int strWidth = g.getFontMetrics().stringWidth(chrPosition); int strPosition = x - strWidth / 2; //if (strPosition > strEnd) { if (nTick % 2 == 0 || ((float)strWidth / deltaX) < 0.33) { g.drawString(chrPosition, strPosition, getHeight() - 15); } //strEnd = strPosition + strWidth; //} g.drawLine(x, getHeight() - 10, x, getHeight() - 2); nTick++; } } private void drawChromosomeTicks(Graphics g) { Font chrFont = FontManager.getFont(10); //this.removeAll(); this.setLayout(null); // TODO -- remove hardcoded value int locationUnit = 1000; g.setFont(chrFont); Genome genome = IGV.getInstance().getGenomeManager().getCurrentGenome(); if (genome == null) { log.info("No genome found with id: " + genome.getId()); PreferenceManager.getInstance().remove(PreferenceManager.DEFAULT_GENOME_KEY); } boolean even = true; long offset = 0; chromosomeRects.clear(); List<String> chrNames = genome.getChromosomeNames(); if (chrNames == null) { log.info("No chromosomes found for genome: " + genome.getId()); PreferenceManager.getInstance().remove(PreferenceManager.DEFAULT_GENOME_KEY); } if (chrNames.size() > 500) { return; } final FontMetrics fontMetrics = g.getFontMetrics(); for (String chrName : chrNames) { Chromosome c = genome.getChromosome(chrName); int chrLength = c.getLength(); int x = (int) (offset / (locationUnit * frame.getScale())); int dw = (int) (chrLength / (locationUnit * frame.getScale())); // Dont draw very small chromosome & contigs in whole genome view if (dw > 1) { g.drawLine(x, getHeight() - 10, x, getHeight() - 2); // Don't label chromosome if its width is < 5 pixels if (dw > 5) { int center = x + dw / 2; String displayName = null; if (chrName.startsWith("gi|")) { displayName = Genome.getNCBIName(chrName); } else { displayName = chrName.replace("chr", ""); } int strWidth = fontMetrics.stringWidth(displayName); int strPosition = center - strWidth / 2; int y = (even ? getHeight() - 35 : getHeight() - 25); g.drawString(displayName, strPosition, y); int sw = (int) fontMetrics.getStringBounds(displayName, g).getWidth(); Rectangle clickRect = new Rectangle(strPosition, y - 15, sw, 15); String tooltipText = "Jump to chromosome: " + chrName; chromosomeRects.add(new ClickLink(clickRect, chrName, tooltipText)); even = !even; } } offset += chrLength; } } public static String formatNumber(double position) { //NumberFormatter f = new NumberFormatter(); DecimalFormat formatter = new DecimalFormat(); return formatter.format((int) position); //return f.valueToString(position); } public static TickSpacing findSpacing(long maxValue, boolean scaleInKB) { // establish genome Genome genome = IGV.getInstance().getGenomeManager().getCurrentGenome(); if (maxValue < 10 && genome != null ) { return new TickSpacing(1, genome.getCoordinateUnitSingle(), 1); } String suffix = (genome != null) ? genome.getCoordinateUnitSuffix() : "b"; String single = (genome != null) ? genome.getCoordinateUnitSingle() : "kb"; boolean isGeneticMap = (genome != null) ? genome.isGeneticMap() : false; // Now man zeroes? int nZeroes = (int) Math.log10(maxValue); String majorUnit = scaleInKB ? ("k" + suffix) : single; int unitMultiplier = 1; if ( !isGeneticMap ) { if (nZeroes > 9) { majorUnit = (scaleInKB ? "t" : "g") + suffix; unitMultiplier = 1000000000; } if (nZeroes > 6) { majorUnit = (scaleInKB ? "g" : "m") + suffix; unitMultiplier = 1000000; } else if (nZeroes > 3) { majorUnit = (scaleInKB ? "m" : "k") + suffix; unitMultiplier = 1000; } } double nMajorTicks = maxValue / Math.pow(10, nZeroes - 1); if (nMajorTicks < 25) { return new TickSpacing(Math.pow(10, nZeroes - 1), majorUnit, unitMultiplier); } else { return new TickSpacing(Math.pow(10, nZeroes) / 2, majorUnit, unitMultiplier); } } private void init() { setBorder(BorderFactory.createLineBorder(UIConstants.TRACK_BORDER_GRAY)); setCursor(Cursor.getDefaultCursor()); if (isWholeGenomeView()) { this.setToolTipText(WHOLE_GENOME_TOOLTIP); } else { this.setToolTipText("Click and drag to zoom"); } MouseInputAdapter mouseAdapter = new MouseInputAdapter() { int lastMousePressX; @Override public void mouseClicked(MouseEvent evt) { final MouseEvent e = evt; setCursor(Cursor.getDefaultCursor()); WaitCursorManager.CursorToken token = WaitCursorManager.showWaitCursor(); try { if (!isWholeGenomeView()) { double newLocation = frame.getChromosomePosition(e.getX()); frame.centerOnLocation(newLocation); } else { for (final ClickLink link : chromosomeRects) { if (link.region.contains(e.getPoint())) { NamedRunnable runnable = new NamedRunnable() { final String chrName = link.value; public void run() { frame.setChrName(chrName); frame.recordHistory(); // TODO -- get rid of this ugly reference to IGV.theInstance IGV.getInstance().chromosomeChangeEvent(chrName); } public String getName() { return "Select chromosome: " + chrName; } }; LongRunningTask.submit(runnable); return; } } } } finally { WaitCursorManager.removeWaitCursor(token); } } @Override public void mouseMoved(MouseEvent e) { if (isWholeGenomeView()) { for (ClickLink link : chromosomeRects) { if (link.region.contains(e.getPoint())) { setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); setToolTipText(link.tooltipText); return; } } setCursor(Cursor.getDefaultCursor()); setToolTipText(WHOLE_GENOME_TOOLTIP); } } @Override public void mouseEntered(MouseEvent e) { setCursor(Cursor.getDefaultCursor()); if (isWholeGenomeView()) { setToolTipText(WHOLE_GENOME_TOOLTIP); } else { setToolTipText(CHROM_TOOLTIP); } } @Override public void mouseDragged(MouseEvent e) { if (Math.abs(e.getPoint().getX() - dragStart) > 1) { dragEnd = e.getX(); dragging = true; repaint(); } } @Override public void mousePressed(MouseEvent e) { dragStart = e.getX(); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { dragEnd = e.getX(); dragging = false; zoom(); } } //@Override //public void mouseExited(MouseEvent e) { //dragging = false; //} }; addMouseMotionListener(mouseAdapter); addMouseListener(mouseAdapter); } private void zoom() { NamedRunnable runnable = new NamedRunnable() { public void run() { double s = frame.getChromosomePosition(dragStart); double e = frame.getChromosomePosition(dragEnd); if (e < s) { double tmp = s; s = e; e = tmp; } double minSize = 40; if ( IGV.getInstance().getGenomeManager().currentGenome.isGeneticMap() ) minSize = 1; if (e - s < minSize) { double c = (s + e) / 2.0; s = c - (minSize / 2.0); e = c + (minSize / 2.0); } String chr = null; if (isWholeGenomeView()) { Genome genome = IGV.getInstance().getGenomeManager().getCurrentGenome(); Genome.ChromosomeCoordinate start = genome.getChromosomeCoordinate((int) s); Genome.ChromosomeCoordinate end = genome.getChromosomeCoordinate((int) e); chr = start.getChr(); s = start.getCoordinate(); e = end.getCoordinate(); if (end.getChr() != start.getChr()) { e = genome.getChromosome(start.getChr()).getLength(); } } else { chr = frame.getChrName(); } frame.jumpTo(chr, (int) Math.min(s, e), (int) Math.max(s, e)); frame.recordHistory(); } public String getName() { return "Rule panel zoom"; } }; LongRunningTask.submit(runnable); } public static class TickSpacing { private double majorTick; private double minorTick; private String majorUnit = ""; private int unitMultiplier = 1; TickSpacing(double majorTick, String majorUnit, int unitMultiplier) { this.majorTick = majorTick; this.minorTick = majorTick / 10.0; this.majorUnit = majorUnit; this.unitMultiplier = unitMultiplier; } public double getMajorTick() { return majorTick; } public double getMinorTick() { return minorTick; } public String getMajorUnit() { return majorUnit; } public void setMajorUnit(String majorUnit) { this.majorUnit = majorUnit; } public int getUnitMultiplier() { return unitMultiplier; } public void setUnitMultiplier(int unitMultiplier) { this.unitMultiplier = unitMultiplier; } } // TODO -- possibly generalize? class ClickLink { Rectangle region; String value; String tooltipText; ClickLink(Rectangle region, String value, String tooltipText) { this.region = region; this.value = value; this.tooltipText = tooltipText; } } }
package zserio.runtime.validation; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import zserio.runtime.SqlDatabase; /** * Contains SQL utilities need for validation code generated by Zserio. */ public class ValidationSqlUtil { /** * Describes the table column. */ public static class ColumnDescription { /** * Constructs table column description from all properties. * * @param name Name of the column. * @param type Column SQLite data type ("INTEGER", "REAL", "TEXT" or "BLOB"). * @param isNotNull true if column has "NOT NULL" constraint. * @param isPrimaryKey true if column is primary key. */ public ColumnDescription(String name, String type, boolean isNotNull, boolean isPrimaryKey) { this.name = name; this.type = type; this.isNotNull = isNotNull; this.isPrimaryKey = isPrimaryKey; } /** * Gets the column name. * * @return Column name. */ public String getName() { return name; } /** * Gets the column SQLite data type. * * @return Column SQLite data type ("INTEGER", "REAL", "TEXT" or "BLOB"). */ public String getType() { return type; } /** * Gets "NOT NULL" constaint flag of this column. * * @return true if column has "NOT NULL" constraint. */ public boolean isNotNull() { return isNotNull; } /** * Gets primary key flag of this column. * * @return true if this column is primary key. */ public boolean isPrimaryKey() { return isPrimaryKey; } private final String name; private final String type; private final boolean isNotNull; private final boolean isPrimaryKey; }; /** * Returns a map of column names to column description for given SQLite table. * * @param db Database to use. * @param attachedDbName Attached database name if table is relocated in different database or null. * @param tableName Name of the table to get column types of. * * @return Map of column names to column description. * * @throws SQLException Throws in case of any SQLite error. */ public static Map<String, ColumnDescription> getTableSchema(SqlDatabase db, String attachedDbName, String tableName) throws SQLException { Map<String, ColumnDescription> columnTypes = new HashMap<String, ColumnDescription>(); // prepare SQL query final StringBuilder sqlQuery = new StringBuilder("PRAGMA "); if (attachedDbName != null) { sqlQuery.append(attachedDbName); sqlQuery.append('.'); } sqlQuery.append("table_info("); sqlQuery.append(tableName); sqlQuery.append(")"); // get table info final PreparedStatement statement = db.prepareStatement(sqlQuery.toString()); try { final ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { final String columnName = resultSet.getString(2); final String columnType = resultSet.getString(3); final boolean isNullable = resultSet.getBoolean(4); final int primaryKeyIndex = resultSet.getInt(6); columnTypes.put(columnName, new ColumnDescription(columnName, columnType, isNullable, primaryKeyIndex != 0)); } } finally { statement.close(); } return columnTypes; } /** * Checks if hidden column exits in given SQLite table. * * @param db Database to use. * @param attachedDbName Attached database name if table is relocated in different database or null. * @param tableName Name of the table where to check hidden column. * @param hiddenColumnName Name of hidden column to check. * * @return true if hidden column exists in given SQLite table. */ public static boolean isHiddenColumnInTable(SqlDatabase db, String attachedDbName, String tableName, String hiddenColumnName) { // prepare SQL query final StringBuilder sqlQuery = new StringBuilder("SELECT "); sqlQuery.append(hiddenColumnName); sqlQuery.append(" FROM "); if (attachedDbName != null) { sqlQuery.append(attachedDbName); sqlQuery.append('.'); } sqlQuery.append(tableName); sqlQuery.append(" LIMIT 0"); // try select to check if hidden column exists try { final PreparedStatement statement = db.prepareStatement(sqlQuery.toString()); statement.close(); return true; } catch (SQLException exception) { return false; } } }
package org.praisenter.data; import java.util.HashMap; import java.util.Map; public final class StringTextStore implements TextStore { final String text; final Map<TextType, TextItem> items; public StringTextStore(String text) { this.text = text; this.items = new HashMap<TextType, TextItem>(); this.items.put(TextType.TEXT, new TextItem(this.text)); this.items.put(TextType.TITLE, new TextItem(this.text)); } @Override public TextStore copy() { return new StringTextStore(this.text); } @Override public Map<TextType, TextItem> get(TextVariant variant) { return this.items; } @Override public TextItem get(TextVariant variant, TextType type) { return this.items.get(TextType.TEXT); } @Override public String toString() { return this.text; } }
package challenges; import challenges.utilities.MainFile; import org.junit.Test; import static org.junit.Assert.*; public class multiBracketTest { @Test public void testMultiBracketValidate () throws Exception { String test = "{}[]()"; MainFile mainFile = new MainFile(); // test easy assertTrue(mainFile.multiBracketValidation(test)); // testing close bracket with no open test = "}()[sda]"; assertFalse(mainFile.multiBracketValidation(test)); // testing same type bracket closed correct inside test = "[[]](df)"; assertTrue(mainFile.multiBracketValidation(test)); // testing open bracket never closed test = "[]](df)"; assertFalse(mainFile.multiBracketValidation(test)); // testing wrong brackets close test = "[{]}"; assertFalse(mainFile.multiBracketValidation(test)); // test end with open bracket test = "()("; assertFalse(mainFile.multiBracketValidation(test)); } }
LinkedList<Type> list = new LinkedList<Type>(); for(Type i: list){ //each element will be in variable "i" System.out.println(i); }
package GUI.Swing.groupLayout; import java.awt.*; import javax.swing.*; /** * @version 1.0 2012-05-05 * @author Cay Horstmann */ public class GroupLayoutTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { JFrame frame = new FontFrame(); frame.setTitle("GroupLayoutTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } }
/* * Copyright (C) 2017 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.settings.notification; import android.content.Context; import android.support.v7.preference.Preference; import com.android.settings.core.PreferenceControllerMixin; import com.android.settingslib.core.AbstractPreferenceController; public class ZenModeAutomationPreferenceController extends AbstractPreferenceController implements PreferenceControllerMixin { protected static final String KEY_ZEN_MODE_AUTOMATION = "zen_mode_automation_settings"; private final ZenModeSettings.SummaryBuilder mSummaryBuilder; public ZenModeAutomationPreferenceController(Context context) { super(context); mSummaryBuilder = new ZenModeSettings.SummaryBuilder(context); } @Override public String getPreferenceKey() { return KEY_ZEN_MODE_AUTOMATION; } @Override public boolean isAvailable() { return true; } @Override public void updateState(Preference preference) { preference.setSummary(mSummaryBuilder.getAutomaticRulesSummary()); } }
package org.openregistry.core.authorization; import java.io.Serializable; import java.util.*; /** * Created by IntelliJ IDEA. * User: nah67 * Date: 9/6/11 * Time: 11:30 AM * To change this template use File | Settings | File Templates. */ public interface Group extends Serializable{ Long getId(); String getGroupName(); String getDescription(); boolean isEnabled(); void setGroupName(String groupName); void setDescription(String description); void setEnabled(boolean value); Authority addAuthority(Authority authority); void removeAuthority(Authority authority); public List<User> getUsers(); User addUser(User user); void removeUser(User user); List<Authority> getGroupAuthorities(); public void removeAllAuthorities(); public void removeAllUsers(); }
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.conscrypt; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.security.InvalidKeyException; import java.security.interfaces.ECPublicKey; import java.security.spec.ECParameterSpec; import java.security.spec.ECPoint; import java.security.spec.ECPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; /** * An implementation of a {@link java.security.PublicKey} for EC keys based on BoringSSL. */ final class OpenSSLECPublicKey implements ECPublicKey, OpenSSLKeyHolder { private static final long serialVersionUID = 3215842926808298020L; private static final String ALGORITHM = "EC"; protected transient OpenSSLKey key; protected transient OpenSSLECGroupContext group; OpenSSLECPublicKey(OpenSSLECGroupContext group, OpenSSLKey key) { this.group = group; this.key = key; } OpenSSLECPublicKey(OpenSSLKey key) { this.group = new OpenSSLECGroupContext(new NativeRef.EC_GROUP( NativeCrypto.EC_KEY_get1_group(key.getNativeRef()))); this.key = key; } OpenSSLECPublicKey(ECPublicKeySpec ecKeySpec) throws InvalidKeySpecException { try { group = OpenSSLECGroupContext.getInstance(ecKeySpec.getParams()); OpenSSLECPointContext pubKey = OpenSSLECPointContext.getInstance(group, ecKeySpec.getW()); key = new OpenSSLKey(NativeCrypto.EVP_PKEY_new_EC_KEY(group.getNativeRef(), pubKey.getNativeRef(), null)); } catch (Exception e) { throw new InvalidKeySpecException(e); } } static OpenSSLKey getInstance(ECPublicKey ecPublicKey) throws InvalidKeyException { try { OpenSSLECGroupContext group = OpenSSLECGroupContext .getInstance(ecPublicKey.getParams()); OpenSSLECPointContext pubKey = OpenSSLECPointContext.getInstance(group, ecPublicKey.getW()); return new OpenSSLKey(NativeCrypto.EVP_PKEY_new_EC_KEY(group.getNativeRef(), pubKey.getNativeRef(), null)); } catch (Exception e) { throw new InvalidKeyException(e); } } @Override public String getAlgorithm() { return ALGORITHM; } @Override public String getFormat() { return "X.509"; } @Override public byte[] getEncoded() { return NativeCrypto.EVP_marshal_public_key(key.getNativeRef()); } @Override public ECParameterSpec getParams() { return group.getECParameterSpec(); } private ECPoint getPublicKey() { final OpenSSLECPointContext pubKey = new OpenSSLECPointContext(group, new NativeRef.EC_POINT(NativeCrypto.EC_KEY_get_public_key(key.getNativeRef()))); return pubKey.getECPoint(); } @Override public ECPoint getW() { return getPublicKey(); } @Override public OpenSSLKey getOpenSSLKey() { return key; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (o instanceof OpenSSLECPublicKey) { OpenSSLECPublicKey other = (OpenSSLECPublicKey) o; return key.equals(other.key); } if (!(o instanceof ECPublicKey)) { return false; } final ECPublicKey other = (ECPublicKey) o; if (!getPublicKey().equals(other.getW())) { return false; } final ECParameterSpec spec = getParams(); final ECParameterSpec otherSpec = other.getParams(); return spec.getCurve().equals(otherSpec.getCurve()) && spec.getGenerator().equals(otherSpec.getGenerator()) && spec.getOrder().equals(otherSpec.getOrder()) && spec.getCofactor() == otherSpec.getCofactor(); } @Override public int hashCode() { return Arrays.hashCode(NativeCrypto.EVP_marshal_public_key(key.getNativeRef())); } @Override public String toString() { return NativeCrypto.EVP_PKEY_print_public(key.getNativeRef()); } private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); byte[] encoded = (byte[]) stream.readObject(); key = new OpenSSLKey(NativeCrypto.EVP_parse_public_key(encoded)); group = new OpenSSLECGroupContext(new NativeRef.EC_GROUP( NativeCrypto.EC_KEY_get1_group(key.getNativeRef()))); } private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(getEncoded()); } }
package Beginner; // Selection in Vector I import java.util.Scanner; public class Uri1174 { public static void main(String[]args) { Scanner in = new Scanner (System.in); double vetor[] = new double[100]; for(int i=0; i<100; i++) { vetor[i]=in.nextDouble(); } for(int i=0; i<100; i++) { if(vetor[i]<=10) { System.out.println("A["+i+"] = "+vetor[i]); } } } }
package pl.itj.dev.services.eurekaserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }