repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
AvanzaBank/astrix
astrix-metrics/src/test/java/com/avanza/astrix/metrics/DropwizardMetricsTest.java
2943
/* * Copyright 2014 Avanza Bank AB * * 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.avanza.astrix.metrics; import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertEquals; import static org.hamcrest.MatcherAssert.assertThat; import java.util.function.Supplier; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.avanza.astrix.context.AstrixApplicationContext; import com.avanza.astrix.context.TestAstrixConfigurer; import com.avanza.astrix.context.metrics.MetricsSpi; import com.avanza.astrix.context.metrics.TimerSnaphot; import com.avanza.astrix.context.metrics.TimerSpi; import com.avanza.astrix.core.function.CheckedCommand; import rx.Observable; public class DropwizardMetricsTest { private DropwizardMetrics dropwizardMetrics; private AstrixApplicationContext astrixContext; @Before public void setup() { astrixContext = (AstrixApplicationContext) new TestAstrixConfigurer().configure(); MetricsSpi metricsSpi = astrixContext.getInstance(MetricsSpi.class); assertEquals(DropwizardMetrics.class, metricsSpi.getClass()); dropwizardMetrics = (DropwizardMetrics) metricsSpi; } @After public void cleanup() throws Exception { astrixContext.close(); } @Test public void timeExecution() throws Throwable { TimerSpi timer = dropwizardMetrics.createTimer(); CheckedCommand<String> execution = timer.timeExecution(() -> { Thread.sleep(10); return "foo-bar"; }); assertEquals("foo-bar", execution.call()); // Should meassure execution time roughly equal to 10 ms TimerSnaphot timerSnapshot = timer.getSnapshot(); assertEquals(1, timerSnapshot.getCount()); assertThat(timerSnapshot.getMax(), greaterThan(8D)); } @Test public void timeObservable() throws Throwable { TimerSpi timer = dropwizardMetrics.createTimer(); Supplier<Observable<String>> observable = timer.timeObservable(() -> Observable.unsafeCreate(subscriber -> { try { Thread.sleep(10); subscriber.onNext("foo"); subscriber.onCompleted(); } catch (InterruptedException e) { subscriber.onError(e); } })); assertEquals("foo", observable.get().toBlocking().first()); TimerSnaphot timerSnapshot = timer.getSnapshot(); assertEquals(1, timerSnapshot.getCount()); // Should meassure execution time roughly equal to 10 ms assertThat(timerSnapshot.getMax(), greaterThan(8D)); } }
apache-2.0
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/cfc/model/UpdateTriggerRequest.java
3724
/* * Copyright 2019 Baidu, Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.baidubce.services.cfc.model; import com.baidubce.auth.BceCredentials; import com.baidubce.model.AbstractBceRequest; import com.baidubce.util.JsonUtils; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonProcessingException; import java.util.Map; /** * Request object for updating the trigger */ public class UpdateTriggerRequest extends AbstractBceRequest { /** * Trigger ID */ @JsonProperty(value = "RelationId") private String RelationId; /** * Function BRN */ @JsonProperty(value = "Target") private String Target; /** * Trigger source */ @JsonProperty(value = "Source") private String Source; /** * Trigger parameter configuration */ @JsonProperty(value = "Data") private Map<String, String> Data; /** * Get the relation Id * @return The relation Id */ @JsonProperty(value = "RelationId") public String getRelationId() { return this.RelationId; } /** * Set the relation Id * @param relationId The relation Id */ public void setRelationId(String relationId) { this.RelationId = relationId; } /** * Get the target * @return The target */ @JsonProperty(value = "Target") public String getTarget() { return this.Target; } /** * Set the target * @param target The target */ public void setTarget(String target) { this.Target = target; } /** * Get the source * @return The source */ @JsonProperty(value = "Source") public String getSource() { return this.Source; } /** * Set the source * @param source The source */ public void setSource(String source) { this.Source = source; } /** * Get the data * @return The data */ @JsonProperty(value = "Data") public Map<String, String> getDate() { return this.Data; } /** * Set the data * @param data The data */ public void setData(Map<String, String> data) { this.Data = data; } public UpdateTriggerRequest withRelationId(String relationId) { this.setRelationId(relationId); return this; } public UpdateTriggerRequest withTarget(String target) { this.setTarget(target); return this; } public UpdateTriggerRequest withSource(String source) { this.setSource(source); return this; } public UpdateTriggerRequest withData(Map<String, String> data) { this.setData(data); return this; } public UpdateTriggerRequest withRequestCredentials(BceCredentials credentials) { this.setRequestCredentials(credentials); return this; } /** * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { try { return JsonUtils.toJsonPrettyString(this); } catch (JsonProcessingException e) { return ""; } } }
apache-2.0
googleads/googleads-java-lib
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201809/cm/OperatingSystemVersion.java
4836
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.adwords.jaxws.v201809.cm; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * * Represents an Operating System Version Criterion. * <a href="/adwords/api/docs/appendix/mobileplatforms">View the complete * list of available mobile platforms</a>. You can also get the list from * {@link ConstantDataService#getOperatingSystemVersionCriterion ConstantDataService}. * <p>A criterion of this type can only be created using an ID. A criterion of this type can be either targeted or excluded. * <span class="constraint AdxEnabled">This is enabled for AdX.</span> * * * <p>Java class for OperatingSystemVersion complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="OperatingSystemVersion"> * &lt;complexContent> * &lt;extension base="{https://adwords.google.com/api/adwords/cm/v201809}Criterion"> * &lt;sequence> * &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="osMajorVersion" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="osMinorVersion" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="operatorType" type="{https://adwords.google.com/api/adwords/cm/v201809}OperatingSystemVersion.OperatorType" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "OperatingSystemVersion", propOrder = { "name", "osMajorVersion", "osMinorVersion", "operatorType" }) public class OperatingSystemVersion extends Criterion { protected String name; protected Integer osMajorVersion; protected Integer osMinorVersion; @XmlSchemaType(name = "string") protected OperatingSystemVersionOperatorType operatorType; /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the osMajorVersion property. * * @return * possible object is * {@link Integer } * */ public Integer getOsMajorVersion() { return osMajorVersion; } /** * Sets the value of the osMajorVersion property. * * @param value * allowed object is * {@link Integer } * */ public void setOsMajorVersion(Integer value) { this.osMajorVersion = value; } /** * Gets the value of the osMinorVersion property. * * @return * possible object is * {@link Integer } * */ public Integer getOsMinorVersion() { return osMinorVersion; } /** * Sets the value of the osMinorVersion property. * * @param value * allowed object is * {@link Integer } * */ public void setOsMinorVersion(Integer value) { this.osMinorVersion = value; } /** * Gets the value of the operatorType property. * * @return * possible object is * {@link OperatingSystemVersionOperatorType } * */ public OperatingSystemVersionOperatorType getOperatorType() { return operatorType; } /** * Sets the value of the operatorType property. * * @param value * allowed object is * {@link OperatingSystemVersionOperatorType } * */ public void setOperatorType(OperatingSystemVersionOperatorType value) { this.operatorType = value; } }
apache-2.0
GaborPeto/android-exercise
api/src/main/java/com/gaborpeto/androidexercise/api/model/RemoteComment.java
1573
package com.gaborpeto.androidexercise.api.model; import com.google.gson.annotations.SerializedName; public class RemoteComment { @SerializedName("id") public int id; @SerializedName("postId") public int postId; @SerializedName("name") public String name; @SerializedName("email") public String email; @SerializedName("body") public String body; @Override public String toString() { return "RemoteComment{" + "id=" + id + ", postId=" + postId + ", name='" + name + '\'' + ", email='" + email + '\'' + ", body='" + body + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RemoteComment that = (RemoteComment) o; if (id != that.id) return false; if (postId != that.postId) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; if (email != null ? !email.equals(that.email) : that.email != null) return false; return body != null ? body.equals(that.body) : that.body == null; } @Override public int hashCode() { int result = id; result = 31 * result + postId; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (email != null ? email.hashCode() : 0); result = 31 * result + (body != null ? body.hashCode() : 0); return result; } }
apache-2.0
girirajsharma/elasticsearch
core/src/main/java/org/elasticsearch/index/mapper/GeoPointFieldMapperLegacy.java
14641
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.mapper; import com.carrotsearch.hppc.ObjectHashSet; import com.carrotsearch.hppc.cursors.ObjectCursor; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.util.BytesRef; import org.elasticsearch.common.Explicit; import org.elasticsearch.common.Strings; import org.elasticsearch.common.geo.GeoDistance; import org.elasticsearch.common.geo.GeoPoint; import org.elasticsearch.common.geo.GeoUtils; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.DistanceUnit; import org.elasticsearch.common.util.ByteUtils; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.support.XContentMapValues; import java.io.IOException; import java.util.Iterator; import java.util.Map; /** * Parsing: We handle: * <p> * - "field" : "geo_hash" * - "field" : "lat,lon" * - "field" : { * "lat" : 1.1, * "lon" : 2.1 * } */ public class GeoPointFieldMapperLegacy extends BaseGeoPointFieldMapper implements ArrayValueMapperParser { public static final String CONTENT_TYPE = "geo_point"; public static class Names extends BaseGeoPointFieldMapper.Names { public static final String COERCE = "coerce"; } public static class Defaults extends BaseGeoPointFieldMapper.Defaults{ public static final Explicit<Boolean> COERCE = new Explicit(false, false); public static final GeoPointFieldType FIELD_TYPE = new GeoPointFieldType(); static { FIELD_TYPE.setIndexOptions(IndexOptions.DOCS); FIELD_TYPE.setTokenized(false); FIELD_TYPE.setOmitNorms(true); FIELD_TYPE.freeze(); } } /** * Concrete builder for legacy GeoPointField */ public static class Builder extends BaseGeoPointFieldMapper.Builder<Builder, GeoPointFieldMapperLegacy> { private Boolean coerce; public Builder(String name) { super(name, Defaults.FIELD_TYPE); this.builder = this; } public Builder coerce(boolean coerce) { this.coerce = coerce; return builder; } protected Explicit<Boolean> coerce(BuilderContext context) { if (coerce != null) { return new Explicit<>(coerce, true); } if (context.indexSettings() != null) { return new Explicit<>(COERCE_SETTING.get(context.indexSettings()), false); } return Defaults.COERCE; } @Override public GeoPointFieldMapperLegacy build(BuilderContext context, String simpleName, MappedFieldType fieldType, MappedFieldType defaultFieldType, Settings indexSettings, FieldMapper latMapper, FieldMapper lonMapper, KeywordFieldMapper geoHashMapper, MultiFields multiFields, Explicit<Boolean> ignoreMalformed, CopyTo copyTo) { fieldType.setTokenized(false); setupFieldType(context); fieldType.setHasDocValues(false); defaultFieldType.setHasDocValues(false); return new GeoPointFieldMapperLegacy(simpleName, fieldType, defaultFieldType, indexSettings, latMapper, lonMapper, geoHashMapper, multiFields, ignoreMalformed, coerce(context), copyTo); } @Override public GeoPointFieldMapperLegacy build(BuilderContext context) { return super.build(context); } } public static Builder parse(Builder builder, Map<String, Object> node, Mapper.TypeParser.ParserContext parserContext) throws MapperParsingException { for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, Object> entry = iterator.next(); String propName = entry.getKey(); Object propNode = entry.getValue(); if (propName.equals(Names.COERCE)) { builder.coerce = XContentMapValues.lenientNodeBooleanValue(propNode); iterator.remove(); } } return builder; } /** * A byte-aligned fixed-length encoding for latitudes and longitudes. */ public static final class Encoding { // With 14 bytes we already have better precision than a double since a double has 11 bits of exponent private static final int MAX_NUM_BYTES = 14; private static final Encoding[] INSTANCES; static { INSTANCES = new Encoding[MAX_NUM_BYTES + 1]; for (int numBytes = 2; numBytes <= MAX_NUM_BYTES; numBytes += 2) { INSTANCES[numBytes] = new Encoding(numBytes); } } /** Get an instance based on the number of bytes that has been used to encode values. */ public static Encoding of(int numBytesPerValue) { final Encoding instance = INSTANCES[numBytesPerValue]; if (instance == null) { throw new IllegalStateException("No encoding for " + numBytesPerValue + " bytes per value"); } return instance; } /** Get an instance based on the expected precision. Here are examples of the number of required bytes per value depending on the * expected precision:<ul> * <li>1km: 4 bytes</li> * <li>3m: 6 bytes</li> * <li>1m: 8 bytes</li> * <li>1cm: 8 bytes</li> * <li>1mm: 10 bytes</li></ul> */ public static Encoding of(DistanceUnit.Distance precision) { for (Encoding encoding : INSTANCES) { if (encoding != null && encoding.precision().compareTo(precision) <= 0) { return encoding; } } return INSTANCES[MAX_NUM_BYTES]; } private final DistanceUnit.Distance precision; private final int numBytes; private final int numBytesPerCoordinate; private final double factor; private Encoding(int numBytes) { assert numBytes >= 1 && numBytes <= MAX_NUM_BYTES; assert (numBytes & 1) == 0; // we don't support odd numBytes for the moment this.numBytes = numBytes; this.numBytesPerCoordinate = numBytes / 2; this.factor = Math.pow(2, - numBytesPerCoordinate * 8 + 9); assert (1L << (numBytesPerCoordinate * 8 - 1)) * factor > 180 && (1L << (numBytesPerCoordinate * 8 - 2)) * factor < 180 : numBytesPerCoordinate + " " + factor; if (numBytes == MAX_NUM_BYTES) { // no precision loss compared to a double precision = new DistanceUnit.Distance(0, DistanceUnit.DEFAULT); } else { precision = new DistanceUnit.Distance( GeoDistance.PLANE.calculate(0, 0, factor / 2, factor / 2, DistanceUnit.DEFAULT), // factor/2 because we use Math.round instead of a cast to convert the double to a long DistanceUnit.DEFAULT); } } public DistanceUnit.Distance precision() { return precision; } /** The number of bytes required to encode a single geo point. */ public int numBytes() { return numBytes; } /** The number of bits required to encode a single coordinate of a geo point. */ public int numBitsPerCoordinate() { return numBytesPerCoordinate << 3; } /** Return the bits that encode a latitude/longitude. */ public long encodeCoordinate(double lat) { return Math.round((lat + 180) / factor); } /** Decode a sequence of bits into the original coordinate. */ public double decodeCoordinate(long bits) { return bits * factor - 180; } private void encodeBits(long bits, byte[] out, int offset) { for (int i = 0; i < numBytesPerCoordinate; ++i) { out[offset++] = (byte) bits; bits >>>= 8; } assert bits == 0; } private long decodeBits(byte [] in, int offset) { long r = in[offset++] & 0xFFL; for (int i = 1; i < numBytesPerCoordinate; ++i) { r = (in[offset++] & 0xFFL) << (i * 8); } return r; } /** Encode a geo point into a byte-array, over {@link #numBytes()} bytes. */ public void encode(double lat, double lon, byte[] out, int offset) { encodeBits(encodeCoordinate(lat), out, offset); encodeBits(encodeCoordinate(lon), out, offset + numBytesPerCoordinate); } /** Decode a geo point from a byte-array, reading {@link #numBytes()} bytes. */ public GeoPoint decode(byte[] in, int offset, GeoPoint out) { final long latBits = decodeBits(in, offset); final long lonBits = decodeBits(in, offset + numBytesPerCoordinate); return decode(latBits, lonBits, out); } /** Decode a geo point from the bits of the encoded latitude and longitudes. */ public GeoPoint decode(long latBits, long lonBits, GeoPoint out) { final double lat = decodeCoordinate(latBits); final double lon = decodeCoordinate(lonBits); return out.reset(lat, lon); } } protected Explicit<Boolean> coerce; public GeoPointFieldMapperLegacy(String simpleName, MappedFieldType fieldType, MappedFieldType defaultFieldType, Settings indexSettings, FieldMapper latMapper, FieldMapper lonMapper, KeywordFieldMapper geoHashMapper, MultiFields multiFields, Explicit<Boolean> ignoreMalformed, Explicit<Boolean> coerce, CopyTo copyTo) { super(simpleName, fieldType, defaultFieldType, indexSettings, latMapper, lonMapper, geoHashMapper, multiFields, ignoreMalformed, copyTo); this.coerce = coerce; } @Override protected void doMerge(Mapper mergeWith, boolean updateAllTypes) { super.doMerge(mergeWith, updateAllTypes); GeoPointFieldMapperLegacy gpfmMergeWith = (GeoPointFieldMapperLegacy) mergeWith; if (gpfmMergeWith.coerce.explicit()) { if (coerce.explicit() && coerce.value() != gpfmMergeWith.coerce.value()) { throw new IllegalArgumentException("mapper [" + fieldType().name() + "] has different [coerce]"); } } if (gpfmMergeWith.coerce.explicit()) { this.coerce = gpfmMergeWith.coerce; } } @Override protected void parse(ParseContext context, GeoPoint point, String geoHash) throws IOException { boolean validPoint = false; if (coerce.value() == false && ignoreMalformed.value() == false) { if (point.lat() > 90.0 || point.lat() < -90.0) { throw new IllegalArgumentException("illegal latitude value [" + point.lat() + "] for " + name()); } if (point.lon() > 180.0 || point.lon() < -180) { throw new IllegalArgumentException("illegal longitude value [" + point.lon() + "] for " + name()); } validPoint = true; } if (coerce.value() == true && validPoint == false) { // by setting coerce to false we are assuming all geopoints are already in a valid coordinate system // thus this extra step can be skipped GeoUtils.normalizePoint(point, true, true); } if (fieldType().indexOptions() != IndexOptions.NONE || fieldType().stored()) { Field field = new Field(fieldType().name(), Double.toString(point.lat()) + ',' + Double.toString(point.lon()), fieldType()); context.doc().add(field); } super.parse(context, point, geoHash); if (fieldType().hasDocValues()) { CustomGeoPointDocValuesField field = (CustomGeoPointDocValuesField) context.doc().getByKey(fieldType().name()); if (field == null) { field = new CustomGeoPointDocValuesField(fieldType().name(), point.lat(), point.lon()); context.doc().addWithKey(fieldType().name(), field); } else { field.add(point.lat(), point.lon()); } } } @Override protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException { super.doXContentBody(builder, includeDefaults, params); if (includeDefaults || coerce.explicit()) { builder.field(Names.COERCE, coerce.value()); } } public static class CustomGeoPointDocValuesField extends CustomDocValuesField { private final ObjectHashSet<GeoPoint> points; public CustomGeoPointDocValuesField(String name, double lat, double lon) { super(name); points = new ObjectHashSet<>(2); points.add(new GeoPoint(lat, lon)); } public void add(double lat, double lon) { points.add(new GeoPoint(lat, lon)); } @Override public BytesRef binaryValue() { final byte[] bytes = new byte[points.size() * 16]; int off = 0; for (Iterator<ObjectCursor<GeoPoint>> it = points.iterator(); it.hasNext(); ) { final GeoPoint point = it.next().value; ByteUtils.writeDoubleLE(point.getLat(), bytes, off); ByteUtils.writeDoubleLE(point.getLon(), bytes, off + 8); off += 16; } return new BytesRef(bytes); } } }
apache-2.0
aws/aws-sdk-java-v2
services/s3/src/test/java/software/amazon/awssdk/services/s3/internal/resource/S3AccessPointResourceTest.java
17352
/* * Copyright 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 software.amazon.awssdk.services.s3.internal.resource; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class S3AccessPointResourceTest { @Rule public ExpectedException exception = ExpectedException.none(); @Test public void buildWithAllPropertiesSet() { S3AccessPointResource s3AccessPointResource = S3AccessPointResource.builder() .accessPointName("access_point-name") .accountId("account-id") .partition("partition") .region("region") .build(); assertEquals("access_point-name", s3AccessPointResource.accessPointName()); assertEquals(Optional.of("account-id"), s3AccessPointResource.accountId()); assertEquals(Optional.of("partition"), s3AccessPointResource.partition()); assertEquals(Optional.of("region"), s3AccessPointResource.region()); assertEquals("accesspoint", s3AccessPointResource.type()); } @Test public void toBuilder() { S3AccessPointResource s3AccessPointResource = S3AccessPointResource.builder() .accessPointName("access_point-name") .accountId("account-id") .partition("partition") .region("region") .build() .toBuilder() .build(); assertEquals("access_point-name", s3AccessPointResource.accessPointName()); assertEquals(Optional.of("account-id"), s3AccessPointResource.accountId()); assertEquals(Optional.of("partition"), s3AccessPointResource.partition()); assertEquals(Optional.of("region"), s3AccessPointResource.region()); assertEquals("accesspoint", s3AccessPointResource.type()); } @Test public void buildWithBlankRegion() { S3AccessPointResource s3AccessPointResource = S3AccessPointResource.builder() .accessPointName("access_point-name") .accountId("account-id") .partition("partition") .region("") .build(); assertEquals("access_point-name", s3AccessPointResource.accessPointName()); assertEquals(Optional.of("account-id"), s3AccessPointResource.accountId()); assertEquals(Optional.of("partition"), s3AccessPointResource.partition()); assertEquals(Optional.of(""), s3AccessPointResource.region()); assertEquals("accesspoint", s3AccessPointResource.type()); } @Test public void buildWithMissingRegion() { S3AccessPointResource s3AccessPointResource = S3AccessPointResource.builder() .accessPointName("access_point-name") .accountId("account-id") .partition("partition") .build(); assertEquals("access_point-name", s3AccessPointResource.accessPointName()); assertEquals(Optional.of("account-id"), s3AccessPointResource.accountId()); assertEquals(Optional.of("partition"), s3AccessPointResource.partition()); assertEquals(Optional.empty(), s3AccessPointResource.region()); assertEquals("accesspoint", s3AccessPointResource.type()); } @Test(expected = IllegalArgumentException.class) public void buildWithBlankPartition() { S3AccessPointResource.builder() .accessPointName("access_point-name") .accountId("account-id") .region("region") .partition("") .build(); } @Test(expected = IllegalArgumentException.class) public void buildWithBlankAccountId() { S3AccessPointResource.builder() .accessPointName("access_point-name") .partition("partition") .region("region") .accountId("") .build(); } @Test(expected = IllegalArgumentException.class) public void buildWithBlankAccessPointName() { S3AccessPointResource.builder() .accountId("account-id") .partition("partition") .region("region") .accessPointName("") .build(); } @Test(expected = NullPointerException.class) public void buildWithMissingPartition() { S3AccessPointResource.builder() .accessPointName("access_point-name") .accountId("account-id") .region("region") .build(); } @Test(expected = NullPointerException.class) public void buildWithMissingAccountId() { S3AccessPointResource.builder() .accessPointName("access_point-name") .partition("partition") .region("region") .build(); } @Test(expected = NullPointerException.class) public void buildWithMissingAccessPointName() { S3AccessPointResource.builder() .accountId("account-id") .partition("partition") .region("region") .build(); } @Test public void buildWithSetters() { S3AccessPointResource.Builder builder = S3AccessPointResource.builder(); builder.setAccessPointName("access_point-name"); builder.setAccountId("account-id"); builder.setPartition("partition"); builder.setRegion("region"); S3AccessPointResource s3AccessPointResource = builder.build(); assertEquals("access_point-name", s3AccessPointResource.accessPointName()); assertEquals(Optional.of("account-id"), s3AccessPointResource.accountId()); assertEquals(Optional.of("partition"), s3AccessPointResource.partition()); assertEquals(Optional.of("region"), s3AccessPointResource.region()); assertEquals("accesspoint", s3AccessPointResource.type()); } @Test public void equalsHashcode_withoutParent() { S3AccessPointResource s3BucketResource1 = S3AccessPointResource.builder() .accessPointName("access_point") .accountId("account-id") .partition("partition") .region("region") .build(); S3AccessPointResource s3BucketResource2 = S3AccessPointResource.builder() .accessPointName("access_point") .accountId("account-id") .partition("partition") .region("region") .build(); S3AccessPointResource s3BucketResource3 = S3AccessPointResource.builder() .accessPointName("access_point") .accountId("account-id") .partition("different-partition") .region("region") .build(); assertEquals(s3BucketResource1, s3BucketResource2); assertEquals(s3BucketResource1.hashCode(), s3BucketResource2.hashCode()); assertNotEquals(s3BucketResource1, s3BucketResource3); assertNotEquals(s3BucketResource1.hashCode(), s3BucketResource3.hashCode()); } @Test public void equalsHashcode_withParent() { S3OutpostResource parentResource = S3OutpostResource.builder() .outpostId("1234") .accountId("account-id") .partition("partition") .region("region") .build(); S3OutpostResource parentResource2 = S3OutpostResource.builder() .outpostId("5678") .accountId("account-id") .partition("partition") .region("region") .build(); S3AccessPointResource s3BucketResource1 = S3AccessPointResource.builder() .accessPointName("access_point") .parentS3Resource(parentResource) .build(); S3AccessPointResource s3BucketResource2 = S3AccessPointResource.builder() .accessPointName("access_point") .parentS3Resource(parentResource) .build(); S3AccessPointResource s3BucketResource3 = S3AccessPointResource.builder() .accessPointName("access_point") .parentS3Resource(parentResource2) .build(); assertEquals(s3BucketResource1, s3BucketResource2); assertEquals(s3BucketResource1.hashCode(), s3BucketResource2.hashCode()); assertNotEquals(s3BucketResource1, s3BucketResource3); assertNotEquals(s3BucketResource1.hashCode(), s3BucketResource3.hashCode()); } @Test public void buildWithOutpostParent() { S3OutpostResource parentResource = S3OutpostResource.builder() .outpostId("1234") .accountId("account-id") .partition("partition") .region("region") .build(); S3AccessPointResource s3AccessPointResource = S3AccessPointResource.builder() .parentS3Resource(parentResource) .accessPointName("access-point-name") .build(); assertEquals("access-point-name", s3AccessPointResource.accessPointName()); assertEquals(Optional.of("account-id"), s3AccessPointResource.accountId()); assertEquals(Optional.of("partition"), s3AccessPointResource.partition()); assertEquals(Optional.of("region"), s3AccessPointResource.region()); assertEquals("accesspoint", s3AccessPointResource.type()); assertEquals(Optional.of(parentResource), s3AccessPointResource.parentS3Resource()); } @Test public void buildWithInvalidParent_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("parentS3Resource"); S3BucketResource invalidParent = S3BucketResource.builder() .bucketName("bucket") .build(); S3AccessPointResource.builder() .parentS3Resource(invalidParent) .accessPointName("access-point-name") .build(); } @Test public void hasParentAndPartition_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("has parent resource"); S3OutpostResource parentResource = S3OutpostResource.builder() .outpostId("1234") .accountId("account-id") .partition("partition") .region("region") .build(); S3AccessPointResource.builder() .accessPointName("access_point") .partition("partition") .parentS3Resource(parentResource) .build(); } @Test public void hasParentAndAccountId_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("has parent resource"); S3OutpostResource parentResource = S3OutpostResource.builder() .outpostId("1234") .accountId("account-id") .partition("partition") .region("region") .build(); S3AccessPointResource.builder() .accessPointName("access_point") .accountId("account id") .parentS3Resource(parentResource) .build(); } @Test public void hasParentAndRegion_shouldThrowException() { exception.expect(IllegalArgumentException.class); exception.expectMessage("has parent resource"); S3OutpostResource parentResource = S3OutpostResource.builder() .outpostId("1234") .accountId("account-id") .partition("partition") .region("region") .build(); S3AccessPointResource.builder() .accessPointName("access_point") .region("region") .parentS3Resource(parentResource) .build(); } }
apache-2.0
garybentley/quollwriter
src/com/quollwriter/exporter/ExportUtils.java
1441
package com.quollwriter.exporter; import java.util.*; import javax.swing.*; import javax.swing.tree.*; import com.quollwriter.data.*; public class ExportUtils { public static Project getSelectedItems (JTree tree, Project proj) { Project p = new Project (proj.getName ()); Book b = new Book (p, null); p.addBook (b); b.setName (proj.getName ()); DefaultTreeModel dtm = (DefaultTreeModel) tree.getModel (); DefaultMutableTreeNode root = (DefaultMutableTreeNode) dtm.getRoot (); Enumeration en = root.depthFirstEnumeration (); while (en.hasMoreElements ()) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) en.nextElement (); Object o = node.getUserObject (); if (o instanceof SelectableDataObject) { SelectableDataObject so = (SelectableDataObject) o; if (so.selected) { if (so.obj instanceof Asset) { p.addAsset ((Asset) so.obj); } if (so.obj instanceof Chapter) { p.getBooks ().get (0).addChapter ((Chapter) so.obj); } } } } return p; } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-kinesisanalyticsv2/src/main/java/com/amazonaws/services/kinesisanalyticsv2/model/EnvironmentPropertyDescriptions.java
5981
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.kinesisanalyticsv2.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Describes the execution properties for a Java-based Amazon Kinesis Data Analytics application. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kinesisanalyticsv2-2018-05-23/EnvironmentPropertyDescriptions" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class EnvironmentPropertyDescriptions implements Serializable, Cloneable, StructuredPojo { /** * <p> * Describes the execution property groups. * </p> */ private java.util.List<PropertyGroup> propertyGroupDescriptions; /** * <p> * Describes the execution property groups. * </p> * * @return Describes the execution property groups. */ public java.util.List<PropertyGroup> getPropertyGroupDescriptions() { return propertyGroupDescriptions; } /** * <p> * Describes the execution property groups. * </p> * * @param propertyGroupDescriptions * Describes the execution property groups. */ public void setPropertyGroupDescriptions(java.util.Collection<PropertyGroup> propertyGroupDescriptions) { if (propertyGroupDescriptions == null) { this.propertyGroupDescriptions = null; return; } this.propertyGroupDescriptions = new java.util.ArrayList<PropertyGroup>(propertyGroupDescriptions); } /** * <p> * Describes the execution property groups. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setPropertyGroupDescriptions(java.util.Collection)} or * {@link #withPropertyGroupDescriptions(java.util.Collection)} if you want to override the existing values. * </p> * * @param propertyGroupDescriptions * Describes the execution property groups. * @return Returns a reference to this object so that method calls can be chained together. */ public EnvironmentPropertyDescriptions withPropertyGroupDescriptions(PropertyGroup... propertyGroupDescriptions) { if (this.propertyGroupDescriptions == null) { setPropertyGroupDescriptions(new java.util.ArrayList<PropertyGroup>(propertyGroupDescriptions.length)); } for (PropertyGroup ele : propertyGroupDescriptions) { this.propertyGroupDescriptions.add(ele); } return this; } /** * <p> * Describes the execution property groups. * </p> * * @param propertyGroupDescriptions * Describes the execution property groups. * @return Returns a reference to this object so that method calls can be chained together. */ public EnvironmentPropertyDescriptions withPropertyGroupDescriptions(java.util.Collection<PropertyGroup> propertyGroupDescriptions) { setPropertyGroupDescriptions(propertyGroupDescriptions); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getPropertyGroupDescriptions() != null) sb.append("PropertyGroupDescriptions: ").append(getPropertyGroupDescriptions()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof EnvironmentPropertyDescriptions == false) return false; EnvironmentPropertyDescriptions other = (EnvironmentPropertyDescriptions) obj; if (other.getPropertyGroupDescriptions() == null ^ this.getPropertyGroupDescriptions() == null) return false; if (other.getPropertyGroupDescriptions() != null && other.getPropertyGroupDescriptions().equals(this.getPropertyGroupDescriptions()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getPropertyGroupDescriptions() == null) ? 0 : getPropertyGroupDescriptions().hashCode()); return hashCode; } @Override public EnvironmentPropertyDescriptions clone() { try { return (EnvironmentPropertyDescriptions) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.kinesisanalyticsv2.model.transform.EnvironmentPropertyDescriptionsMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
selenium-webdriver-software-testing/keyword-driven-framework
src/main/java/com/kagrana/keyword_driven_framework/App.java
1672
package com.kagrana.keyword_driven_framework; import java.util.HashMap; /** * This library helps in automating Selenium tests and makes keyword driven * framework to execute TestNG tests. * * @author mayur * */ public class App { public static void main(String[] args) throws Exception { HashMap<String, String> arguments = new HashMap<String, String>(); for (int i = 0; i < args.length; i++) { if (!args[i].startsWith("-")) throw new Exception("Invalid argument" + args[i]); if (!args[i].contains("=")) throw new Exception("Argument " + args[i] + " does not have any value"); String[] splittedArgs = args[i].split("="); if (!(splittedArgs.length == 2)) throw new Exception( "Argument " + args[i] + " does not have any value.\nFormat:\n\t-argument=value"); arguments.put(splittedArgs[0].replace("-", ""), splittedArgs[1]); } ExcelFile xlFile = new ExcelFile( arguments.get("excelfilename") != null ? arguments .get("excelfilename") : "input.xls"); XMLFile xmlFile = new XMLFile( arguments.get("testngfilename") != null ? arguments .get("testngfilename") : "testng.xml"); SuiteConfiguration sp = new SuiteConfiguration(xlFile.getSuite(), arguments.get("configfilename") != null ? arguments .get("configfilename") : "config.properties"); sp.set("gridURL", "gridURL"); sp.set("ReportLocation", "ReportLocation"); sp.set("baseURL", "baseURL"); sp.set("internal", "internal"); sp.setSuiteName("suite_name"); sp.setParallel("parallel"); sp.setThread_Count("thread_count"); sp.setClassPackage("tests_package"); xmlFile.makeXMLFile(sp.getSuite()); } }
apache-2.0
araqne/logdb
araqne-logstorage/src/main/java/org/araqne/logstorage/engine/LogStorageMonitorEngine.java
10490
/* * Copyright 2011 Future Systems * * 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.araqne.logstorage.engine; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.felix.ipojo.annotations.Component; import org.apache.felix.ipojo.annotations.Provides; import org.apache.felix.ipojo.annotations.Requires; import org.araqne.confdb.ConfigService; import org.araqne.cron.PeriodicJob; import org.araqne.logstorage.DiskLackAction; import org.araqne.logstorage.DiskLackCallback; import org.araqne.logstorage.DiskSpaceType; import org.araqne.logstorage.LogRetentionPolicy; import org.araqne.logstorage.LogStorage; import org.araqne.logstorage.LogStorageMonitor; import org.araqne.logstorage.LogStorageStatus; import org.araqne.logstorage.LogTableRegistry; import org.araqne.logstorage.TableLockedException; import org.araqne.storage.api.FilePath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @PeriodicJob("* * * * *") @Component(name = "logstorage-monitor") @Provides public class LogStorageMonitorEngine implements LogStorageMonitor { private static final String DEFAULT_MIN_FREE_SPACE_TYPE = DiskSpaceType.Percentage.toString(); private static final int DEFAULT_MIN_FREE_SPACE_VALUE = 5; private static final String DEFAULT_DISK_LACK_ACTION = DiskLackAction.StopLogging.toString(); private final Logger logger = LoggerFactory.getLogger(LogStorageMonitorEngine.class.getName()); @Requires private LogTableRegistry tableRegistry; @Requires private LogStorage storage; @Requires private ConfigService conf; // last check time, check retention policy and purge files for every hour private long lastPurgeCheck; private DiskSpaceType minFreeSpaceType; private int minFreeSpaceValue; private DiskLackAction diskLackAction; private Set<DiskLackCallback> diskLackCallbacks = new HashSet<DiskLackCallback>(); private boolean stopByLowDisk; public LogStorageMonitorEngine() { reload(); } private void reload() { minFreeSpaceType = DiskSpaceType.valueOf(getStringParameter(Constants.MinFreeDiskSpaceType, DEFAULT_MIN_FREE_SPACE_TYPE)); minFreeSpaceValue = getIntParameter(Constants.MinFreeDiskSpaceValue, DEFAULT_MIN_FREE_SPACE_VALUE); diskLackAction = DiskLackAction.valueOf(getStringParameter(Constants.DiskLackAction, DEFAULT_DISK_LACK_ACTION)); } @Override public int getMinFreeSpaceValue() { return minFreeSpaceValue; } @Override public DiskSpaceType getMinFreeSpaceType() { return minFreeSpaceType; } @Override public void setMinFreeSpace(int value, DiskSpaceType type) { if (type == DiskSpaceType.Percentage) { if (value <= 0 || value >= 100) throw new IllegalArgumentException("invalid value"); } else if (type == DiskSpaceType.Megabyte) { if (value <= 0) throw new IllegalArgumentException("invalid value"); } else if (type == null) throw new IllegalArgumentException("type cannot be null"); this.minFreeSpaceType = type; this.minFreeSpaceValue = value; ConfigUtil.set(conf, Constants.MinFreeDiskSpaceType, type.toString()); ConfigUtil.set(conf, Constants.MinFreeDiskSpaceValue, Integer.toString(value)); } @Override public DiskLackAction getDiskLackAction() { return diskLackAction; } @Override public void setDiskLackAction(DiskLackAction action) { if (action == null) throw new IllegalArgumentException("action cannot be null"); this.diskLackAction = action; ConfigUtil.set(conf, Constants.DiskLackAction, action.toString()); } @Override public void registerDiskLackCallback(DiskLackCallback callback) { diskLackCallbacks.add(callback); } @Override public void unregisterDiskLackCallback(DiskLackCallback callback) { diskLackCallbacks.remove(callback); } @Override public void forceRetentionCheck() { checkRetentions(true); } private boolean isDiskLack(FilePath dir) { if (!dir.exists()) return false; long usable = dir.getUsableSpace(); long total = dir.getTotalSpace(); logger.trace("araqne logstorage: check {} {} free space of partition [{}], current [{}] total [{}]", new Object[] { minFreeSpaceValue, minFreeSpaceType.toString().toLowerCase(), dir.getAbsolutePath(), usable, total }); if (total == 0) { logger.error("araqne logstorage: low disk, dir [{}] usable [{}] total [{}]", new Object[] { dir.getAbsoluteFilePath(), usable, total }); return true; } String unit = (minFreeSpaceType == DiskSpaceType.Percentage ? "%" : "MB"); if (minFreeSpaceType == DiskSpaceType.Percentage) { int percent = (int) (usable * 100 / total); if (percent < minFreeSpaceValue) { logger.error("araqne logstorage: low disk, dir [{}] usable [{}] total [{}] percent [{}] threshold [{} {}]", new Object[] { dir.getAbsoluteFilePath(), usable, total, percent, minFreeSpaceValue, unit }); return true; } } else if (minFreeSpaceType == DiskSpaceType.Megabyte) { int mega = (int) (usable / 1048576); if (mega < minFreeSpaceValue) { logger.error("araqne logstorage: low disk, dir [{}] usable [{}] total [{}] percent [{}] threshold [{} {}]", new Object[] { dir.getAbsoluteFilePath(), usable, total, mega, minFreeSpaceValue, unit }); return true; } } return false; } @Override public void run() { try { runOnce(); } catch (Exception e) { logger.error("araqne logstorage: storage monitor error", e); } } private void runOnce() { reload(); checkRetentions(false); checkDiskLack(); } private void checkRetentions(boolean force) { long now = System.currentTimeMillis(); if (!force && now - lastPurgeCheck < 3600 * 1000) return; for (String tableName : tableRegistry.getTableNames()) { checkAndPurgeFiles(tableName); } lastPurgeCheck = now; } private void checkAndPurgeFiles(String tableName) { LogRetentionPolicy p = storage.getRetentionPolicy(tableName); if (p == null || p.getRetentionDays() == 0) { logger.debug("araqne logstorage: no retention policy for table [{}]", tableName); return; } // purge tables Date logBaseline = storage.getPurgeBaseline(tableName); if (logBaseline != null) { try { storage.purge(tableName, null, logBaseline); } catch (TableLockedException e) { logger.debug("purge skipped: table is locked by {}", e.getMessage()); } } } private void checkDiskLack() { // categorize by partition path Map<FilePath, List<String>> partitionTables = new HashMap<FilePath, List<String>>(); for (String tableName : tableRegistry.getTableNames()) { FilePath tableDir = storage.getTableDirectory(tableName); if (tableDir == null) continue; FilePath dir = tableDir.getAbsoluteFilePath().getParentFilePath(); List<String> tables = partitionTables.get(dir); if (tables == null) { tables = new ArrayList<String>(); partitionTables.put(dir, tables); } tables.add(tableName); } boolean lowDisk = false; for (FilePath dir : partitionTables.keySet()) { lowDisk |= checkDiskPartitions(dir, partitionTables.get(dir)); } if (lowDisk) { for (DiskLackCallback callback : diskLackCallbacks) { try { callback.callback(); } catch (Throwable t) { logger.warn("araqne logstorage: disk lack callback should not throw any exception", t); } } } else { // open log storage if low disk problem is resolved if (stopByLowDisk) startStorage(); } } private boolean checkDiskPartitions(FilePath partitionPath, List<String> tableNames) { if (isDiskLack(partitionPath)) { logger.error("araqne logstorage: not enough disk space, current minimum free space config [{}] {}", minFreeSpaceValue, (minFreeSpaceType == DiskSpaceType.Percentage ? "%" : "MB")); if (diskLackAction == DiskLackAction.StopLogging) { if (storage.getStatus() == LogStorageStatus.Open) { stopStorage(partitionPath); } } else if (diskLackAction == DiskLackAction.RemoveOldLog) { List<LogFile> files = new ArrayList<LogFile>(); for (String tableName : tableNames) { for (Date date : storage.getLogDates(tableName)) files.add(new LogFile(tableName, date)); } Collections.sort(files, new LogFileComparator()); int index = 0; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); do { if (index >= files.size()) { if (storage.getStatus() == LogStorageStatus.Open) { stopStorage(partitionPath); } break; } LogFile lf = files.get(index++); logger.info("araqne logstorage: removing old log, table [{}], date [{}]", lf.tableName, sdf.format(lf.date)); storage.purge(lf.tableName, lf.date); } while (isDiskLack(partitionPath)); } return true; } return false; } private void startStorage() { logger.info("araqne logstorage: low disk problem is resolved, restart logstorage"); storage.start(); stopByLowDisk = false; } private void stopStorage(FilePath partitionPath) { logger.error("araqne logstorage: [{}] not enough space, stop logging", partitionPath.getAbsolutePath()); storage.stop(); stopByLowDisk = true; } private String getStringParameter(Constants key, String defaultValue) { String value = ConfigUtil.get(conf, key); if (value != null) return value; return defaultValue; } private int getIntParameter(Constants key, int defaultValue) { String value = ConfigUtil.get(conf, key); if (value != null) return Integer.valueOf(value); return defaultValue; } private class LogFile { private String tableName; private Date date; private LogFile(String tableName, Date date) { this.tableName = tableName; this.date = date; } } private class LogFileComparator implements Comparator<LogFile> { @Override public int compare(LogFile o1, LogFile o2) { return o1.date.compareTo(o2.date); } } }
apache-2.0
jnbt/digits-android
digits/src/main/java/com/digits/sdk/android/DigitsCallback.java
1660
/* * Copyright (C) 2015 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.digits.sdk.android; import android.content.Context; import com.twitter.sdk.android.core.Callback; import com.twitter.sdk.android.core.TwitterException; import java.lang.ref.WeakReference; import io.fabric.sdk.android.Fabric; public abstract class DigitsCallback<T> extends Callback<T> { final DigitsController controller; private final WeakReference<Context> context; DigitsCallback(Context context, DigitsController controller) { this.context = new WeakReference<Context>(context); this.controller = controller; } @Override public void failure(TwitterException exception) { final DigitsException digitsException = DigitsException.create(controller.getErrors(), exception); Fabric.getLogger().e(Digits.TAG, "HTTP Error: " + exception.getMessage() + ", API Error: " + "" + digitsException.getErrorCode() + ", User Message: " + digitsException .getMessage()); controller.handleError(context.get(), digitsException); } }
apache-2.0
VT-Visionarium/osnap
src/main/java/x3d/model/X3DMetadataObject.java
3960
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 // 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: 2011.06.16 at 09:21:15 AM EDT // package x3d.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import x3d.fields.SFString; /** * <p>Java class for X3DMetadataObject complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="X3DMetadataObject"> * &lt;complexContent> * &lt;extension base="{}X3DNode"> * &lt;attribute name="name" type="{}SFString" /> * &lt;attribute name="reference" type="{}SFString" /> * &lt;attribute name="containerField" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" default="metadata" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name="X3DMetadataObject") @XmlType(name = "X3DMetadataObject", propOrder = { "name", "reference", "containerField" }) @XmlSeeAlso({ MetadataString.class, MetadataInteger.class, MetadataFloat.class, MetadataDouble.class, MetadataSet.class }) public abstract class X3DMetadataObject // extends X3DNode { @XmlAttribute(name = "name") protected SFString name; @XmlAttribute(name = "reference") protected SFString reference; @XmlAttribute(name = "containerField") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NMTOKEN") protected String containerField; /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public SFString getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(SFString value) { this.name = value; } /** * Gets the value of the reference property. * * @return * possible object is * {@link String } * */ public SFString getReference() { return reference; } /** * Sets the value of the reference property. * * @param value * allowed object is * {@link String } * */ public void setReference(SFString value) { this.reference = value; } /** * Gets the value of the containerField property. * * @return * possible object is * {@link String } * */ public String getContainerField() { if (containerField == null) { return "metadata"; } else { return containerField; } } /** * Sets the value of the containerField property. * * @param value * allowed object is * {@link String } * */ public void setContainerField(String value) { this.containerField = value; } public X3DMetadataObject(SFString name, SFString reference, String containerField) { this.name = name; this.reference = reference; this.containerField = containerField; } public X3DMetadataObject(){ this (new SFString(), new SFString(), null); } }
apache-2.0
somasun/reactivesocket-java
rsocket-core/src/main/java/io/rsocket/util/Clock.java
1088
/* * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.rsocket.util; import java.util.concurrent.TimeUnit; /** * Abstraction to get current time and durations. */ public final class Clock { private Clock() { // No Instances. } public static long now() { return System.nanoTime() / 1000; } public static long elapsedSince(long timestamp) { long t = now(); return Math.max(0L, t - timestamp); } public static TimeUnit unit() { return TimeUnit.MICROSECONDS; } }
apache-2.0
electricalwind/greycat
greycat/src/main/java/greycat/internal/heap/HeapStringIntMap.java
14947
/** * Copyright 2017 The GreyCat Authors. All rights reserved. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package greycat.internal.heap; import greycat.Constants; import greycat.internal.CoreConstants; import greycat.struct.Buffer; import greycat.struct.StringIntMap; import greycat.struct.StringLongMapCallBack; import greycat.utility.Base64; import greycat.utility.HashHelper; import java.util.Arrays; class HeapStringIntMap implements StringIntMap { private final HeapContainer parent; private int mapSize = 0; private int capacity = 0; private String[] keys = null; private int[] keysH = null; private int[] values = null; private int[] nexts = null; private int[] hashs = null; HeapStringIntMap(final HeapContainer p_parent) { this.parent = p_parent; } private String key(final int i) { return keys[i]; } private void setKey(final int i, final String newValue) { keys[i] = newValue; } private int keyH(final int i) { return keysH[i]; } private void setKeyH(final int i, int newValue) { keysH[i] = newValue; } private int value(int i) { return values[i]; } private void setValue(int i, int newValue) { values[i] = newValue; } private int next(int i) { return nexts[i]; } private void setNext(int i, int newValue) { nexts[i] = newValue; } private int hash(int i) { return hashs[i]; } private void setHash(int i, int newValue) { hashs[i] = newValue; } void reallocate(int newCapacity) { if (newCapacity > capacity) { //extend keys String[] new_keys = new String[newCapacity]; if (keys != null) { System.arraycopy(keys, 0, new_keys, 0, capacity); } keys = new_keys; //extend keysH int[] new_keysH = new int[newCapacity]; if (keysH != null) { System.arraycopy(keysH, 0, new_keysH, 0, capacity); } keysH = new_keysH; //extend values int[] new_values = new int[newCapacity]; if (values != null) { System.arraycopy(values, 0, new_values, 0, capacity); } values = new_values; int[] new_nexts = new int[newCapacity]; int[] new_hashes = new int[newCapacity * 2]; Arrays.fill(new_nexts, 0, newCapacity, -1); Arrays.fill(new_hashes, 0, newCapacity * 2, -1); hashs = new_hashes; nexts = new_nexts; int double_capacity = newCapacity * 2; for (int i = 0; i < mapSize; i++) { int new_key_hash = keyH(i) % double_capacity; if (new_key_hash < 0) { new_key_hash = new_key_hash * -1; } setNext(i, hash(new_key_hash)); setHash(new_key_hash, i); } capacity = newCapacity; } } HeapStringIntMap cloneFor(HeapContainer newContainer) { HeapStringIntMap cloned = new HeapStringIntMap(newContainer); cloned.mapSize = mapSize; cloned.capacity = capacity; if (keys != null) { String[] cloned_keys = new String[capacity]; System.arraycopy(keys, 0, cloned_keys, 0, capacity); cloned.keys = cloned_keys; } if (keysH != null) { int[] cloned_keysH = new int[capacity]; System.arraycopy(keysH, 0, cloned_keysH, 0, capacity); cloned.keysH = cloned_keysH; } if (values != null) { int[] cloned_values = new int[capacity]; System.arraycopy(values, 0, cloned_values, 0, capacity); cloned.values = cloned_values; } if (nexts != null) { int[] cloned_nexts = new int[capacity]; System.arraycopy(nexts, 0, cloned_nexts, 0, capacity); cloned.nexts = cloned_nexts; } if (hashs != null) { int[] cloned_hashs = new int[capacity * 2]; System.arraycopy(hashs, 0, cloned_hashs, 0, capacity * 2); cloned.hashs = cloned_hashs; } return cloned; } @Override public final int getValue(final String requestString) { int result = -1; synchronized (parent) { if (keys != null) { final int keyHash = HashHelper.hash(requestString); int hashIndex = keyHash % (capacity * 2); if (hashIndex < 0) { hashIndex = hashIndex * -1; } int m = hash(hashIndex); while (m >= 0) { if (keyHash == keyH(m)) { result = value(m); break; } m = next(m); } } } return result; } @Override public String getByHash(final int keyHash) { String result = null; synchronized (parent) { if (keys != null) { int hashIndex = keyHash % (capacity * 2); if (hashIndex < 0) { hashIndex = hashIndex * -1; } int m = hash(hashIndex); while (m >= 0) { if (keyHash == keyH(m)) { result = key(m); break; } m = next(m); } } } return result; } @Override public boolean containsHash(int keyHash) { boolean result = false; synchronized (parent) { if (keys != null) { int hashIndex = keyHash % (capacity * 2); if (hashIndex < 0) { hashIndex = hashIndex * -1; } int m = hash(hashIndex); while (m >= 0) { if (keyHash == keyH(m)) { result = true; break; } m = next(m); } } } return result; } @Override public final void each(StringLongMapCallBack callback) { synchronized (parent) { unsafe_each(callback); } } final void unsafe_each(StringLongMapCallBack callback) { for (int i = 0; i < mapSize; i++) { callback.on(key(i), value(i)); } } @Override public final int size() { int result; synchronized (parent) { result = mapSize; } return result; } @Override public final void remove(final String requestKey) { synchronized (parent) { if (keys != null && mapSize != 0) { final int keyHash = HashHelper.hash(requestKey); int hashCapacity = capacity * 2; int hashIndex = keyHash % hashCapacity; if (hashIndex < 0) { hashIndex = hashIndex * -1; } int m = hash(hashIndex); int found = -1; while (m >= 0) { if (keyHash == keyH(m)) { found = m; break; } m = next(m); } if (found != -1) { //first remove currentKey from hashChain int toRemoveHash = keyHash % hashCapacity; if (toRemoveHash < 0) { toRemoveHash = toRemoveHash * -1; } m = hash(toRemoveHash); if (m == found) { setHash(toRemoveHash, next(m)); } else { while (m != -1) { int next_of_m = next(m); if (next_of_m == found) { setNext(m, next(next_of_m)); break; } m = next_of_m; } } final int lastIndex = mapSize - 1; if (lastIndex == found) { //easy, was the last element mapSize--; } else { //less cool, we have to unchain the last value of the map final String lastKey = key(lastIndex); final int lastKeyH = keyH(lastIndex); setKey(found, lastKey); setKeyH(found, lastKeyH); setValue(found, value(lastIndex)); setNext(found, next(lastIndex)); int victimHash = lastKeyH % hashCapacity; if (victimHash < 0) { victimHash = victimHash * -1; } m = hash(victimHash); if (m == lastIndex) { //the victim was the head of hashing list setHash(victimHash, found); } else { //the victim is in the next, reChain it while (m != -1) { int next_of_m = next(m); if (next_of_m == lastIndex) { setNext(m, found); break; } m = next_of_m; } } mapSize--; } parent.declareDirty(); } } } } @Override public final StringIntMap put(final String insertKey, final int insertValue) { synchronized (parent) { final int keyHash = HashHelper.hash(insertKey); if (keys == null) { reallocate(Constants.MAP_INITIAL_CAPACITY); setKey(0, insertKey); setKeyH(0, keyHash); setValue(0, insertValue); int hashIndex = keyHash % (capacity * 2); if (hashIndex < 0) { hashIndex = hashIndex * -1; } setHash(hashIndex, 0); setNext(0, -1); mapSize++; } else { int hashCapacity = capacity * 2; int insertKeyHash = keyHash % hashCapacity; if (insertKeyHash < 0) { insertKeyHash = insertKeyHash * -1; } int currentHash = hash(insertKeyHash); int m = currentHash; int found = -1; while (m >= 0) { if (keyHash == keyH(m)) { if (!(insertKey.equals(key(m)))) { throw new RuntimeException("Lotteries Winner !!! hashing conflict between " + key(m) + " and " + insertKey); } found = m; break; } m = next(m); } if (found == -1) { final int lastIndex = mapSize; if (lastIndex == capacity) { reallocate(capacity * 2); } setKey(lastIndex, insertKey); setKeyH(lastIndex, keyHash); setValue(lastIndex, insertValue); int hashIndex = keyHash % (capacity * 2); if (hashIndex < 0) { hashIndex = hashIndex * -1; } setHash(hashIndex, lastIndex); setNext(lastIndex, currentHash); mapSize++; parent.declareDirty(); } else { if (value(found) != insertValue) { setValue(found, insertValue); parent.declareDirty(); } } } } return this; } public final void save(final Buffer buffer) { if (mapSize != 0) { Base64.encodeIntToBuffer(mapSize, buffer); for (int j = 0; j < mapSize; j++) { buffer.write(CoreConstants.CHUNK_VAL_SEP); Base64.encodeStringToBuffer(keys[j], buffer); buffer.write(CoreConstants.CHUNK_VAL_SEP); Base64.encodeIntToBuffer(values[j], buffer); } } else { Base64.encodeIntToBuffer(0, buffer); } } public final long load(final Buffer buffer, final long offset, final long max) { long cursor = offset; byte current = buffer.read(cursor); boolean isFirst = true; long previous = offset; String previousKey = null; while (cursor < max && current != Constants.CHUNK_SEP && current != Constants.BLOCK_CLOSE) { if (current == Constants.CHUNK_VAL_SEP) { if (isFirst) { reallocate(Base64.decodeToIntWithBounds(buffer, previous, cursor)); isFirst = false; } else { if (previousKey == null) { previousKey = Base64.decodeToStringWithBounds(buffer, previous, cursor); } else { put(previousKey, Base64.decodeToIntWithBounds(buffer, previous, cursor)); previousKey = null; } } previous = cursor + 1; } cursor++; if (cursor < max) { current = buffer.read(cursor); } } if (isFirst) { reallocate(Base64.decodeToIntWithBounds(buffer, previous, cursor)); } else { if (previousKey != null) { put(previousKey, Base64.decodeToIntWithBounds(buffer, previous, cursor)); } } return cursor; } }
apache-2.0
jesuino/droolsjbpm-integration
kie-spring-boot/kie-spring-boot-samples/jbpm-spring-boot-sample-basic/src/test/resources/kjars/kafka-process/src/main/java/com/myspace/kafka_process/Box.java
3300
/* * Copyright 2020 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 com.myspace.kafka_process; import java.io.Serializable; import java.math.BigInteger; import java.util.List; public class Box implements Serializable { static final long serialVersionUID = 1L; private BigInteger id; private List<Integer> numbers; private String name; private Boolean valid; public Box() { } public BigInteger getId() { return this.id; } public void setId(BigInteger id) { this.id = id; } public List<Integer> getNumbers() { return this.numbers; } public void setNumbers(List<Integer> numbers) { this.numbers = numbers; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Boolean getValid() { return this.valid; } public void setValid(Boolean valid) { this.valid = valid; } public Box(BigInteger id, List<Integer> numbers, String name, Boolean valid) { this.id = id; this.numbers = numbers; this.name = name; this.valid = valid; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((numbers == null) ? 0 : numbers.hashCode()); result = prime * result + ((valid == null) ? 0 : valid.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Box other = (Box) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (numbers == null) { if (other.numbers != null) return false; } else if (!numbers.equals(other.numbers)) return false; if (valid == null) { if (other.valid != null) return false; } else if (!valid.equals(other.valid)) return false; return true; } @Override public String toString() { return "Box [id=" + id + ", numbers=" + numbers + ", name=" + name + ", valid=" + valid + "]"; } }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-servicenetworking/v1beta/1.31.0/com/google/api/services/servicenetworking/v1beta/model/Subnetwork.java
6002
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.servicenetworking.v1beta.model; /** * Represents a subnet that was created or discovered by a private access management service. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Service Networking API. For a detailed explanation * see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class Subnetwork extends com.google.api.client.json.GenericJson { /** * Subnetwork CIDR range in `10.x.x.x/y` format. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String ipCidrRange; /** * Subnetwork name. See https://cloud.google.com/compute/docs/vpc/ * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String name; /** * In the Shared VPC host project, the VPC network that's peered with the consumer network. For * example: `projects/1234321/global/networks/host-network` * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String network; /** * This is a discovered subnet that is not within the current consumer allocated ranges. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean outsideAllocation; /** * GCP region where the subnetwork is located. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String region; /** * List of secondary IP ranges in this subnetwork. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<SecondaryIpRange> secondaryIpRanges; static { // hack to force ProGuard to consider SecondaryIpRange used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(SecondaryIpRange.class); } /** * Subnetwork CIDR range in `10.x.x.x/y` format. * @return value or {@code null} for none */ public java.lang.String getIpCidrRange() { return ipCidrRange; } /** * Subnetwork CIDR range in `10.x.x.x/y` format. * @param ipCidrRange ipCidrRange or {@code null} for none */ public Subnetwork setIpCidrRange(java.lang.String ipCidrRange) { this.ipCidrRange = ipCidrRange; return this; } /** * Subnetwork name. See https://cloud.google.com/compute/docs/vpc/ * @return value or {@code null} for none */ public java.lang.String getName() { return name; } /** * Subnetwork name. See https://cloud.google.com/compute/docs/vpc/ * @param name name or {@code null} for none */ public Subnetwork setName(java.lang.String name) { this.name = name; return this; } /** * In the Shared VPC host project, the VPC network that's peered with the consumer network. For * example: `projects/1234321/global/networks/host-network` * @return value or {@code null} for none */ public java.lang.String getNetwork() { return network; } /** * In the Shared VPC host project, the VPC network that's peered with the consumer network. For * example: `projects/1234321/global/networks/host-network` * @param network network or {@code null} for none */ public Subnetwork setNetwork(java.lang.String network) { this.network = network; return this; } /** * This is a discovered subnet that is not within the current consumer allocated ranges. * @return value or {@code null} for none */ public java.lang.Boolean getOutsideAllocation() { return outsideAllocation; } /** * This is a discovered subnet that is not within the current consumer allocated ranges. * @param outsideAllocation outsideAllocation or {@code null} for none */ public Subnetwork setOutsideAllocation(java.lang.Boolean outsideAllocation) { this.outsideAllocation = outsideAllocation; return this; } /** * GCP region where the subnetwork is located. * @return value or {@code null} for none */ public java.lang.String getRegion() { return region; } /** * GCP region where the subnetwork is located. * @param region region or {@code null} for none */ public Subnetwork setRegion(java.lang.String region) { this.region = region; return this; } /** * List of secondary IP ranges in this subnetwork. * @return value or {@code null} for none */ public java.util.List<SecondaryIpRange> getSecondaryIpRanges() { return secondaryIpRanges; } /** * List of secondary IP ranges in this subnetwork. * @param secondaryIpRanges secondaryIpRanges or {@code null} for none */ public Subnetwork setSecondaryIpRanges(java.util.List<SecondaryIpRange> secondaryIpRanges) { this.secondaryIpRanges = secondaryIpRanges; return this; } @Override public Subnetwork set(String fieldName, Object value) { return (Subnetwork) super.set(fieldName, value); } @Override public Subnetwork clone() { return (Subnetwork) super.clone(); } }
apache-2.0
NawaMan/DirectInterceptor
Agent/src/main/java/direct/interceptor/agent/Agent.java
4023
package direct.interceptor.agent; import static net.bytebuddy.matcher.ElementMatchers.nameMatches; import static net.bytebuddy.matcher.ElementMatchers.not; import java.lang.instrument.Instrumentation; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import net.bytebuddy.agent.builder.AgentBuilder; import net.bytebuddy.description.NamedElement; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.matcher.ElementMatcher; import net.bytebuddy.matcher.ElementMatcher.Junction; public class Agent { private static final $Util util = $Util.getInstance(); // Due to some problem with error handling in ByteBuddy 0.7.7, // There is error message that is deem to be no danger so we will ignore it. private static final Set<String> workaroundMessages; static { List<String> messages = util.linesFromResource(Agent.class, "workaround-messages-list.txt"); workaroundMessages = Collections.unmodifiableSet(new HashSet<>(messages)); } private static final List<String> ignoredPackages; static { List<String> packages = util.linesFromResource(Agent.class, "ignored-packages-list.txt"); ignoredPackages = Collections.unmodifiableList(packages); } private static void onError(String errMsg, Throwable throwable) { // TODO Should propose to ByteBuddy that this case more accurately // detectable // as this case it is quite common. // (unless super complex matcher was done) if (IllegalStateException.class.isInstance(throwable)) { String message = throwable.getMessage(); if (workaroundMessages.contains(message)) { return; } } System.out.println("Error - " + errMsg + ", " + throwable.getMessage()); throwable.printStackTrace(); } public static void agentmain(String agentArgument, Instrumentation instrumentation) { premain(agentArgument, instrumentation); } /** * The premain method which will be run before the main method (dah!). It * perform the registration for class transformation. * * @param agentArgument * the agent argument. * @param instrumentation * the instrumentation object. */ @SuppressWarnings({ "unchecked" }) public static void premain(String agentArgument, Instrumentation instrumentation) { try { $AgentListener listener = theListener(); $ClassTransformer transformer = new $ClassTransformer(agentArgument); Junction<NamedElement> ignoredPackages = theIgnoredPackages(); Junction<NamedElement> exceptTypes = not(ignoredPackages).and(notAnnotation()).and(notInterface()); new AgentBuilder.Default() .withListener(listener) .type(exceptTypes) .transform(transformer) .installOn(instrumentation); } catch (RuntimeException e) { System.out.println("Exception instrumenting code : " + e); e.printStackTrace(); } } private static $AgentListener theListener() { $AgentListener listener = new $AgentListener() { @Override public void onError(String errMsg, Throwable throwable) { Agent.onError(errMsg, throwable); } }; return listener; } private static Junction<NamedElement> theIgnoredPackages() { Junction<NamedElement> ignored = null; for (String exceptPackage : ignoredPackages) { String regEx = util.matchPackageNameStartWith(exceptPackage); Junction<NamedElement> except = nameMatches(regEx); ignored = (ignored == null) ? except : ignored.or(except); } return ignored; } @SuppressWarnings("rawtypes") private static ElementMatcher notAnnotation() { return new ElementMatcher() { @Override public boolean matches(Object target) { TypeDescription type = (TypeDescription) target; return !type.isAnnotation(); } }; } @SuppressWarnings("rawtypes") private static ElementMatcher notInterface() { return new ElementMatcher() { @Override public boolean matches(Object target) { TypeDescription type = (TypeDescription) target; return !type.isInterface(); } }; } }
apache-2.0
CruorVolt/mu_bbmap
src/bbmap/current/bloom/KmerCountAbstract.java
1279
package bloom; import align2.Shared; /** * @author Brian Bushnell * @date Dec 2, 2014 * */ public abstract class KmerCountAbstract { protected static final long[] transformToFrequency(int[] count){ long[] freq=new long[2000]; int max=freq.length-1; for(int i=0; i<count.length; i++){ int x=count[i]; x=min(x, max); freq[x]++; } return freq; } protected static final long sum(int[] array){ long x=0; for(int y : array){x+=y;} return x; } protected static final long sum(long[] array){ long x=0; for(long y : array){x+=y;} return x; } protected static final int min(int x, int y){return x<y ? x : y;} protected static final int max(int x, int y){return x>y ? x : y;} public static byte minQuality=6; public static long readsProcessed=0; public static long maxReads=-1; // public static int kmersamplerate=1; // public static int readsamplerate=1; public static int BUFFERLEN=500; public static float minProb=0.5f; public static long keysCounted=0; public static int THREADS=Shared.threads(); public static boolean verbose=false; public static boolean PREJOIN=false; public static boolean CANONICAL=false; public static boolean KEEP_DUPLICATE_KMERS=false; }
apache-2.0
kangaroo-server/kangaroo
kangaroo-server-authz/src/test/java/net/krotscheck/kangaroo/authz/oauth2/rfc6749/AbstractRFC6749Test.java
6546
/* * Copyright (c) 2016 Michael Krotscheck * * 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 net.krotscheck.kangaroo.authz.oauth2.rfc6749; import net.krotscheck.kangaroo.authz.AuthzAPI; import net.krotscheck.kangaroo.authz.common.database.entity.ClientConfig; import net.krotscheck.kangaroo.authz.common.database.entity.OAuthToken; import net.krotscheck.kangaroo.authz.common.database.entity.OAuthTokenType; import net.krotscheck.kangaroo.authz.oauth2.resource.TokenResponseEntity; import net.krotscheck.kangaroo.common.hibernate.id.IdUtil; import net.krotscheck.kangaroo.test.jersey.ContainerTest; import net.krotscheck.kangaroo.test.jersey.SingletonTestContainerFactory; import net.krotscheck.kangaroo.test.runner.SingleInstanceTestRunner; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.spi.TestContainerException; import org.glassfish.jersey.test.spi.TestContainerFactory; import org.hibernate.Session; import org.junit.runner.RunWith; import javax.ws.rs.core.MultivaluedMap; import java.math.BigInteger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * Abstract testing class that bootstraps a full OAuthAPI that's ready for * external hammering. * * @author Michael Krotscheck * @see <a href="https://tools.ietf.org/html/rfc6749#section-2.3">https://tools.ietf.org/html/rfc6749#section-2.3</a> */ @RunWith(SingleInstanceTestRunner.class) public abstract class AbstractRFC6749Test extends ContainerTest { /** * Test container factory. */ private SingletonTestContainerFactory testContainerFactory; /** * The current running test application. */ private ResourceConfig testApplication; /** * This method asserts that a token has been persisted to the database, * and contains a brief set of expected variables. * * @param params URL Parameters. * @param requireIdentity Whether a User Identity is required. */ protected final void assertValidBearerToken( final MultivaluedMap<String, String> params, final boolean requireIdentity) { Session s = getSession(); String accessTokenString = params.getFirst("access_token"); String tokenType = params.getFirst("token_type"); String state = params.getFirst("state"); Long expiresIn = Long.valueOf(params.getFirst("expires_in")); BigInteger accessTokenId = IdUtil.fromString(accessTokenString); OAuthToken t = s.get(OAuthToken.class, accessTokenId); assertEquals(OAuthTokenType.valueOf(tokenType), t.getTokenType()); assertEquals(expiresIn, t.getExpiresIn()); TokenResponseEntity entity = TokenResponseEntity.factory(t, state); assertValidBearerToken(entity, requireIdentity); } /** * This method asserts that a token has been persisted to the database, * and contains a brief set of expected variables. * * @param token The token. * @param requireIdentity Whether a User Identity is required. */ protected final void assertValidBearerToken(final TokenResponseEntity token, final boolean requireIdentity) { Session s = getSession(); // Validate the token itself. assertNotNull(token.getAccessToken()); assertEquals( Long.valueOf(ClientConfig.ACCESS_TOKEN_EXPIRES_DEFAULT), token.getExpiresIn()); assertEquals(OAuthTokenType.Bearer, token.getTokenType()); OAuthToken bearer = s.get(OAuthToken.class, token.getAccessToken()); assertNotNull(bearer); assertEquals( Long.valueOf(ClientConfig.ACCESS_TOKEN_EXPIRES_DEFAULT), bearer.getExpiresIn()); assertEquals(bearer.getTokenType(), OAuthTokenType.Bearer); // Do we expect an identity? if (requireIdentity) { assertNotNull(bearer.getIdentity()); } // Validate any attached refresh token. BigInteger refreshTokenId = token.getRefreshToken(); if (refreshTokenId != null) { OAuthToken refresh = s.get(OAuthToken.class, refreshTokenId); assertEquals(refresh.getAuthToken(), bearer); assertEquals(refresh.getIdentity(), bearer.getIdentity()); assertEquals(refresh.getScopes(), bearer.getScopes()); assertEquals(refresh.getTokenType(), OAuthTokenType.Refresh); assertEquals(refresh.getClient(), bearer.getClient()); assertEquals( Long.valueOf(ClientConfig.REFRESH_TOKEN_EXPIRES_DEFAULT), refresh.getExpiresIn()); } } /** * This method overrides the underlying default test container provider, * with one that provides a singleton instance. This allows us to * circumvent the often expensive initialization routines that come from * bootstrapping our services. * * @return an instance of {@link TestContainerFactory} class. * @throws TestContainerException if the initialization of * {@link TestContainerFactory} instance * is not successful. */ protected final TestContainerFactory getTestContainerFactory() throws TestContainerException { if (this.testContainerFactory == null) { this.testContainerFactory = new SingletonTestContainerFactory( super.getTestContainerFactory(), this.getClass()); } return testContainerFactory; } /** * Create the application under test. * * @return A configured api servlet. */ @Override protected final ResourceConfig createApplication() { if (testApplication == null) { testApplication = new AuthzAPI(); } return testApplication; } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-cloudhsm/src/main/java/com/amazonaws/services/cloudhsm/model/transform/DeleteLunaClientRequestMarshaller.java
2030
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.cloudhsm.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.cloudhsm.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * DeleteLunaClientRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DeleteLunaClientRequestMarshaller { private static final MarshallingInfo<String> CLIENTARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("ClientArn").build(); private static final DeleteLunaClientRequestMarshaller instance = new DeleteLunaClientRequestMarshaller(); public static DeleteLunaClientRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(DeleteLunaClientRequest deleteLunaClientRequest, ProtocolMarshaller protocolMarshaller) { if (deleteLunaClientRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteLunaClientRequest.getClientArn(), CLIENTARN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
steven-zhc/hummingbird-framework
hummingbird-spring/src/main/java/com/hczhang/hummingbird/spring/def/DefaultEventLogBinding.java
1041
package com.hczhang.hummingbird.spring.def; import com.hczhang.hummingbird.eventlog.SimpleEventLog; import com.hczhang.hummingbird.spring.ExtensionBinding; import com.hczhang.hummingbird.spring.ExtensionType; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.ParserContext; import org.w3c.dom.Element; /** * Created by steven on 8/12/15. */ public class DefaultEventLogBinding implements ExtensionBinding { @Override public ExtensionType getExtensionType() { return ExtensionType.EVENT_LOG; } @Override public boolean lookingFor(String type) { if (StringUtils.equals("simple", type)) { return true; } return false; } @Override public Class<?> getImplementClass() { return SimpleEventLog.class; } @Override public void moreConfig(BeanDefinitionBuilder componentFactory, Element element, ParserContext parserContext) { } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-ssmcontacts/src/main/java/com/amazonaws/services/ssmcontacts/model/ActivateContactChannelRequest.java
5688
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.ssmcontacts.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ssm-contacts-2021-05-03/ActivateContactChannel" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ActivateContactChannelRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The Amazon Resource Name (ARN) of the contact channel. * </p> */ private String contactChannelId; /** * <p> * The code sent to the contact channel when it was created in the contact. * </p> */ private String activationCode; /** * <p> * The Amazon Resource Name (ARN) of the contact channel. * </p> * * @param contactChannelId * The Amazon Resource Name (ARN) of the contact channel. */ public void setContactChannelId(String contactChannelId) { this.contactChannelId = contactChannelId; } /** * <p> * The Amazon Resource Name (ARN) of the contact channel. * </p> * * @return The Amazon Resource Name (ARN) of the contact channel. */ public String getContactChannelId() { return this.contactChannelId; } /** * <p> * The Amazon Resource Name (ARN) of the contact channel. * </p> * * @param contactChannelId * The Amazon Resource Name (ARN) of the contact channel. * @return Returns a reference to this object so that method calls can be chained together. */ public ActivateContactChannelRequest withContactChannelId(String contactChannelId) { setContactChannelId(contactChannelId); return this; } /** * <p> * The code sent to the contact channel when it was created in the contact. * </p> * * @param activationCode * The code sent to the contact channel when it was created in the contact. */ public void setActivationCode(String activationCode) { this.activationCode = activationCode; } /** * <p> * The code sent to the contact channel when it was created in the contact. * </p> * * @return The code sent to the contact channel when it was created in the contact. */ public String getActivationCode() { return this.activationCode; } /** * <p> * The code sent to the contact channel when it was created in the contact. * </p> * * @param activationCode * The code sent to the contact channel when it was created in the contact. * @return Returns a reference to this object so that method calls can be chained together. */ public ActivateContactChannelRequest withActivationCode(String activationCode) { setActivationCode(activationCode); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getContactChannelId() != null) sb.append("ContactChannelId: ").append(getContactChannelId()).append(","); if (getActivationCode() != null) sb.append("ActivationCode: ").append(getActivationCode()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ActivateContactChannelRequest == false) return false; ActivateContactChannelRequest other = (ActivateContactChannelRequest) obj; if (other.getContactChannelId() == null ^ this.getContactChannelId() == null) return false; if (other.getContactChannelId() != null && other.getContactChannelId().equals(this.getContactChannelId()) == false) return false; if (other.getActivationCode() == null ^ this.getActivationCode() == null) return false; if (other.getActivationCode() != null && other.getActivationCode().equals(this.getActivationCode()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getContactChannelId() == null) ? 0 : getContactChannelId().hashCode()); hashCode = prime * hashCode + ((getActivationCode() == null) ? 0 : getActivationCode().hashCode()); return hashCode; } @Override public ActivateContactChannelRequest clone() { return (ActivateContactChannelRequest) super.clone(); } }
apache-2.0
dorzey/assertj-core
src/test/java/org/assertj/core/api/comparable/GenericComparableAssert_isNotEqualByComparingTo_Test.java
1316
/** * 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 2012-2016 the original author or authors. */ package org.assertj.core.api.comparable; import static org.mockito.Mockito.verify; import org.assertj.core.api.GenericComparableAssert; import org.assertj.core.api.GenericComparableAssertBaseTest; /** * Tests for <code>{@link GenericComparableAssert#isNotEqualByComparingTo(Comparable)}</code>. */ public class GenericComparableAssert_isNotEqualByComparingTo_Test extends GenericComparableAssertBaseTest { @Override protected GenericComparableAssert<Integer> invoke_api_method() { return assertions.isNotEqualByComparingTo(0); } @Override protected void verify_internal_effects() { verify(comparables).assertNotEqualByComparison(getInfo(assertions), getActual(assertions), 0); } }
apache-2.0
didi/DoraemonKit
Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/network/stream/HttpOutputStreamProxy.java
1425
package com.didichuxing.doraemonkit.kit.network.stream; import com.didichuxing.doraemonkit.kit.network.NetworkManager; import com.didichuxing.doraemonkit.kit.network.bean.NetworkRecord; import com.didichuxing.doraemonkit.kit.network.core.NetworkInterpreter; import com.didichuxing.doraemonkit.kit.network.core.RequestBodyHelper; import java.io.IOException; import java.io.OutputStream; /** * @author: linjizong * 2019/3/14 * @desc: */ public class HttpOutputStreamProxy extends OutputStreamProxy { private final int mRequestId; private final NetworkInterpreter mInterpreter; public HttpOutputStreamProxy(OutputStream out,int requestId, NetworkInterpreter interpreter) { super(out); mRequestId = requestId; mInterpreter = interpreter; } @Override protected void onStreamComplete() throws IOException { NetworkRecord record = NetworkManager.get().getRecord(mRequestId); if (record != null && record.mRequest != null) { RequestBodyHelper requestBodyHelper = new RequestBodyHelper(); try { OutputStream out = requestBodyHelper.createBodySink(record.mRequest.encode); mOutputStream.writeTo(out); } finally { out.close(); } byte[] body = requestBodyHelper.getDisplayBody(); mInterpreter.fetRequestBody(record, body); } } }
apache-2.0
spring-projects/spring-data-examples
jpa/deferred/src/main/java/example/repo/Customer1438Repository.java
284
package example.repo; import example.model.Customer1438; import java.util.List; import org.springframework.data.repository.CrudRepository; public interface Customer1438Repository extends CrudRepository<Customer1438, Long> { List<Customer1438> findByLastName(String lastName); }
apache-2.0
nibabkin/BarcodeReaderExample
app/src/main/java/ru/teamidea/barcodereader/ui/main/MainActivity.java
6632
package ru.teamidea.barcodereader.ui.main; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import java.util.ArrayList; import ru.teamidea.barcodereader.R; import ru.teamidea.barcodereader.data.Product; import ru.teamidea.barcodereader.data.ProductsData; import ru.teamidea.barcodereader.ui.BarcodeCaptureActivity; import ru.teamidea.barcodereader.ui.product.ProductDetailsActivity; public class MainActivity extends AppCompatActivity implements ProductsAdapter.OnProductClickedListener { private RecyclerView productsRecycler; private ProductsAdapter adapter; private EditText searchByCode; private View clear; private TextView empty; private FloatingActionButton scan; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); scan = (FloatingActionButton) findViewById(R.id.fab); productsRecycler = (RecyclerView) findViewById(R.id.productRecycler); productsRecycler.setLayoutManager(new LinearLayoutManager(this)); adapter = new ProductsAdapter(this); productsRecycler.setAdapter(adapter); productsRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if (dy > 5) { scan.hide(); } else if (dy < -5) { scan.show(); } } }); searchByCode = (EditText) findViewById(R.id.searchByCode); searchByCode.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { if (charSequence.toString().isEmpty()) { clear.setVisibility(View.INVISIBLE); adapter.clearList(); } else { clear.setVisibility(View.VISIBLE); ArrayList<Product> serchedProducts = ProductsData.getInstance().getProductsStartsWith(charSequence.toString()); adapter.updateProducts(serchedProducts); } showEmptyViewIfNeeded(); } @Override public void afterTextChanged(Editable editable) { } }); clear = findViewById(R.id.clear); clear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { searchByCode.setText(""); } }); scan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { searchByCode.setText(""); IntentIntegrator integrator = new IntentIntegrator(MainActivity.this); integrator.setCaptureActivity(BarcodeCaptureActivity.class); integrator.setOrientationLocked(false); integrator.initiateScan(); } }); empty = (TextView) findViewById(R.id.productRecyclerEmpty); showEmptyViewIfNeeded(); } private void showEmptyViewIfNeeded() { if (adapter.getItemCount() > 0) { empty.setVisibility(View.INVISIBLE); productsRecycler.setVisibility(View.VISIBLE); } else { productsRecycler.setVisibility(View.INVISIBLE); empty.setVisibility(View.VISIBLE); if (searchByCode.getText().toString().isEmpty()) { empty.setText("Отсканируйте штрихкод продукта или введите номер вручную"); } else { empty.setText("К сожалению, в базе нет товаров с таким номeром :("); } } if(!scan.isShown()) { scan.show(); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { if (resultCode == Activity.RESULT_CANCELED) { Snackbar.make(searchByCode, "Письмо об ошибке отправлено", Snackbar.LENGTH_LONG).show(); } } else { IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (result != null) { if (result.getContents() == null) { Log.d("MainActivity", "Cancelled scan"); Snackbar.make(searchByCode, "Сканирование отменено", Snackbar.LENGTH_LONG).show(); } else { Log.d("MainActivity", "Scanned"); Product scannedProduct = ProductsData.getInstance().getProductByCode(result.getContents()); if (scannedProduct == null) { Snackbar.make(searchByCode, "Такого товара в базе нет :(", Snackbar.LENGTH_LONG).show(); adapter.clearList(); showEmptyViewIfNeeded(); } else { startActivityForResult(ProductDetailsActivity.getLaunchIntent(this, scannedProduct.getId()), 1); } } } else { // This is important, otherwise the result will not be passed to the fragment super.onActivityResult(requestCode, resultCode, data); } } } @Override public void onProductClicked(int id) { startActivityForResult(ProductDetailsActivity.getLaunchIntent(this, id), 1); } }
apache-2.0
dianaui/dianaui-universal
core/src/main/java/com/dianaui/universal/core/client/ui/Affix.java
2358
/* * #%L * Diana UI Core * %% * Copyright (C) 2014 Diana UI * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.dianaui.universal.core.client.ui; import com.google.gwt.dom.client.Element; import com.google.gwt.user.client.ui.UIObject; /** * An Affix is an element/container that gets "pinned" as soon as a certain * amount of pixels have been scrolled. * Any element/container can become an Affix. Usually used for sidebar * navigation. * <strong>Note:</strong> Bootstrap adds/removes classes from Affix based on * scroll position which requires custom styling. See Bootstrap's <a * href="http://getbootstrap.com/javascript/#affix">documentation</a>. * * @author Sven Jacobs * @author <a href='mailto:donbeave@gmail.com'>Alexey Zhokhov</a> */ public class Affix { /** * Applys affix functionality to specified element. * * @param element Element to "affixnize" */ public static void affix(final Element element) { // TODO // internalAffix(element, 10); } /** * Applys affix functionality to specified element. * * @param element Element to "affixnize" * @param offset Offset of affix */ public static void affix(final Element element, final int offset) { // TODO // internalAffix(element, offset); } /** * Applys affix functionality to specified object. * * @param object Object to "affixnize" */ public static void affix(final UIObject object) { affix(object.getElement()); } /** * Applys affix functionality to specified object. * * @param object Object to "affixnize" * @param offset Offset of affix */ public static void affix(final UIObject object, final int offset) { affix(object.getElement(), offset); } }
apache-2.0
jacarrichan/eoffice
src/main/java/com/palmelf/eoffice/model/communicate/OutMailUserSeting.java
4907
package com.palmelf.eoffice.model.communicate; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; import com.google.gson.annotations.Expose; import com.palmelf.core.model.BaseModel; import com.palmelf.eoffice.model.system.AppUser; @Entity @Table(name = "out_mail_user_seting") public class OutMailUserSeting extends BaseModel { /** * */ private static final long serialVersionUID = -3462957793863636827L; @Expose private Long id; @Expose private String userName; @Expose private String mailAddress; @Expose private String mailPass; @Expose private String smtpHost; @Expose private String smtpPort; @Expose private String popHost; @Expose private String popPort; private AppUser appUser; private Set<OutMail> outMails = new HashSet<OutMail>(); public OutMailUserSeting() { } public OutMailUserSeting(Long in_id) { this.setId(in_id); } @Id @GeneratedValue @Column(name = "id", unique = true, nullable = false) public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "userId") public AppUser getAppUser() { return this.appUser; } public void setAppUser(AppUser appUser) { this.appUser = appUser; } @Column(name = "userName", length = 128) public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } @Column(name = "mailAddress", nullable = false, length = 128) public String getMailAddress() { return this.mailAddress; } public void setMailAddress(String mailAddress) { this.mailAddress = mailAddress; } @Column(name = "mailPass", nullable = false, length = 128) public String getMailPass() { return this.mailPass; } public void setMailPass(String mailPass) { this.mailPass = mailPass; } @Column(name = "smtpHost", nullable = false, length = 128) public String getSmtpHost() { return this.smtpHost; } public void setSmtpHost(String smtpHost) { this.smtpHost = smtpHost; } @Column(name = "smtpPort", nullable = false, length = 64) public String getSmtpPort() { return this.smtpPort; } public void setSmtpPort(String smtpPort) { this.smtpPort = smtpPort; } @Column(name = "popHost", nullable = false, length = 128) public String getPopHost() { return this.popHost; } public void setPopHost(String popHost) { this.popHost = popHost; } @Column(name = "popPort", nullable = false, length = 64) public String getPopPort() { return this.popPort; } public void setPopPort(String popPort) { this.popPort = popPort; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY) public Set<OutMail> getOutMails() { return this.outMails; } public void setOutMails(Set<OutMail> outMails) { this.outMails = outMails; } @Transient public Long getUserId() { return this.getAppUser() == null ? null : this.getAppUser().getUserId(); } public void setUserId(Long aValue) { if (aValue == null) { this.appUser = null; } else if (this.appUser == null) { this.appUser = new AppUser(aValue); this.appUser.setVersion(new Integer(0)); } else { this.appUser.setUserId(aValue); } } @Override public boolean equals(Object object) { if (!(object instanceof OutMailUserSeting)) { return false; } OutMailUserSeting rhs = (OutMailUserSeting) object; return new EqualsBuilder().append(this.id, rhs.id).append(this.userName, rhs.userName) .append(this.mailAddress, rhs.mailAddress).append(this.mailPass, rhs.mailPass) .append(this.smtpHost, rhs.smtpHost).append(this.smtpPort, rhs.smtpPort) .append(this.popHost, rhs.popHost).append(this.popPort, rhs.popPort).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(-82280557, -700257973).append(this.id).append(this.userName) .append(this.mailAddress).append(this.mailPass).append(this.smtpHost).append(this.smtpPort) .append(this.popHost).append(this.popPort).toHashCode(); } @Override public String toString() { return new ToStringBuilder(this).append("id", this.id).append("userName", this.userName) .append("mailAddress", this.mailAddress).append("mailPass", this.mailPass) .append("smtpHost", this.smtpHost).append("smtpPort", this.smtpPort).append("popHost", this.popHost) .append("popPort", this.popPort).toString(); } }
apache-2.0
yeongwei/incubator-calcite
core/src/main/java/org/apache/calcite/jdbc/CalciteResultSet.java
5393
/* * 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.calcite.jdbc; import org.apache.calcite.avatica.AvaticaResultSet; import org.apache.calcite.avatica.AvaticaResultSetMetaData; import org.apache.calcite.avatica.AvaticaStatement; import org.apache.calcite.avatica.ColumnMetaData; import org.apache.calcite.avatica.Handler; import org.apache.calcite.avatica.Meta; import org.apache.calcite.avatica.NoSuchStatementException; import org.apache.calcite.avatica.util.Cursor; import org.apache.calcite.linq4j.Enumerator; import org.apache.calcite.linq4j.Linq4j; import org.apache.calcite.rel.RelCollation; import org.apache.calcite.runtime.ArrayEnumeratorCursor; import org.apache.calcite.runtime.ObjectEnumeratorCursor; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.List; import java.util.TimeZone; import java.util.concurrent.atomic.AtomicBoolean; import static org.apache.calcite.util.Static.RESOURCE; /** * Implementation of {@link ResultSet} * for the Calcite engine. */ public class CalciteResultSet extends AvaticaResultSet { private final AtomicBoolean cancelFlag; CalciteResultSet(AvaticaStatement statement, CalcitePrepare.CalciteSignature calciteSignature, ResultSetMetaData resultSetMetaData, TimeZone timeZone, Meta.Frame firstFrame) { super(statement, null, calciteSignature, resultSetMetaData, timeZone, firstFrame); try { cancelFlag = getCalciteConnection().getCancelFlag(statement.handle); } catch (NoSuchStatementException e) { throw Throwables.propagate(e); } } @Override protected CalciteResultSet execute() throws SQLException { // Call driver's callback. It is permitted to throw a RuntimeException. CalciteConnectionImpl connection = getCalciteConnection(); final boolean autoTemp = connection.config().autoTemp(); Handler.ResultSink resultSink = null; if (autoTemp) { resultSink = new Handler.ResultSink() { public void toBeCompleted() { } }; } connection.getDriver().handler.onStatementExecute(statement, resultSink); super.execute(); return this; } @Override protected void cancel() { cancelFlag.compareAndSet(false, true); } @Override public boolean next() throws SQLException { final boolean next = super.next(); if (cancelFlag.get()) { throw new SQLException(RESOURCE.statementCanceled().str()); } return next; } @Override public ResultSet create(ColumnMetaData.AvaticaType elementType, Iterable<Object> iterable) { final List<ColumnMetaData> columnMetaDataList; if (elementType instanceof ColumnMetaData.StructType) { columnMetaDataList = ((ColumnMetaData.StructType) elementType).columns; } else { columnMetaDataList = ImmutableList.of(ColumnMetaData.dummy(elementType, false)); } final CalcitePrepare.CalciteSignature signature = (CalcitePrepare.CalciteSignature) this.signature; final CalcitePrepare.CalciteSignature<Object> newSignature = new CalcitePrepare.CalciteSignature<>(signature.sql, signature.parameters, signature.internalParameters, signature.rowType, columnMetaDataList, Meta.CursorFactory.ARRAY, ImmutableList.<RelCollation>of(), -1, null); ResultSetMetaData subResultSetMetaData = new AvaticaResultSetMetaData(statement, null, newSignature); final CalciteResultSet resultSet = new CalciteResultSet(statement, signature, subResultSetMetaData, localCalendar.getTimeZone(), new Meta.Frame(0, true, iterable)); final Cursor cursor = resultSet.createCursor(elementType, iterable); return resultSet.execute2(cursor, columnMetaDataList); } private Cursor createCursor(ColumnMetaData.AvaticaType elementType, Iterable iterable) { final Enumerator enumerator = Linq4j.iterableEnumerator(iterable); //noinspection unchecked return !(elementType instanceof ColumnMetaData.StructType) || ((ColumnMetaData.StructType) elementType).columns.size() == 1 ? new ObjectEnumeratorCursor(enumerator) : new ArrayEnumeratorCursor(enumerator); } // do not make public <T> CalcitePrepare.CalciteSignature<T> getSignature() { //noinspection unchecked return (CalcitePrepare.CalciteSignature) signature; } // do not make public CalciteConnectionImpl getCalciteConnection() { return (CalciteConnectionImpl) statement.getConnection(); } } // End CalciteResultSet.java
apache-2.0
Tristanhx/ARealChessGame
app/src/main/java/com/example/tristan/arealchessgame/StaticApplicationContext.java
202
package com.example.tristan.arealchessgame; import android.content.Context; /** * Created by Tristan on 22/06/2017. */ public class StaticApplicationContext { public static Context context; }
apache-2.0
lisaglendenning/safari
src/main/java/edu/uw/zookeeper/safari/Hash.java
1521
package edu.uw.zookeeper.safari; import com.google.common.base.Function; import com.google.common.hash.HashCode; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; import edu.uw.zookeeper.common.Pair; import edu.uw.zookeeper.common.Reference; public enum Hash implements Function<String, Hash.Hashed>, Reference<HashFunction> { MURMUR3_32(Hashing.murmur3_32()); public static Hash default32() { return MURMUR3_32; } public class Hashed extends Pair<String, HashCode> { public Hashed(String first) { this(first, hashFunction.hashUnencodedChars(first)); } public Hashed(String first, HashCode second) { super(first, second); } public Hashed rehash() { return new Hashed(first, hashFunction.newHasher() .putUnencodedChars(first) .putBytes(second.asBytes()).hash()); } public Identifier asIdentifier() { return Identifier.valueOf(second.asInt()); } } private final HashFunction hashFunction; private Hash(HashFunction hashFunction) { this.hashFunction = hashFunction; } public int bits() { return get().bits(); } @Override public Hashed apply(String input) { return new Hashed(input); } @Override public HashFunction get() { return hashFunction; } }
apache-2.0
massx1/syncope
core/persistence-api/src/main/java/org/apache/syncope/core/persistence/api/dao/AttrTemplateDAO.java
1418
/* * 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.syncope.core.persistence.api.dao; import java.util.List; import org.apache.syncope.core.persistence.api.entity.AttrTemplate; import org.apache.syncope.core.persistence.api.entity.Schema; public interface AttrTemplateDAO<K extends Schema> extends DAO<AttrTemplate<K>, Long> { <T extends AttrTemplate<K>> T find(Long key, Class<T> reference); <T extends AttrTemplate<K>> List<Number> findBySchemaName(String schemaName, Class<T> reference); <T extends AttrTemplate<K>> void delete(Long key, Class<T> reference); <T extends AttrTemplate<K>> void delete(T attrTemplate); }
apache-2.0
socrata-platform/ssync
src/main/java/com/socrata/ssync/exceptions/input/UnknownChecksumAlgorithm.java
227
package com.socrata.ssync.exceptions.input; public class UnknownChecksumAlgorithm extends InputException { public UnknownChecksumAlgorithm(String name) { super("Unknown checksum algorithm: " + name, null); } }
apache-2.0
relateiq/AugmentedDriver
src/main/java/com/salesforceiq/augmenteddriver/mobile/ios/pageobjects/IOSPageContainerObject.java
3410
package com.salesforceiq.augmenteddriver.mobile.ios.pageobjects; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.inject.Inject; import com.google.inject.Provider; import com.salesforceiq.augmenteddriver.mobile.ios.AugmentedIOSDriver; import com.salesforceiq.augmenteddriver.mobile.ios.AugmentedIOSElement; import com.salesforceiq.augmenteddriver.mobile.ios.AugmentedIOSFunctions; import com.salesforceiq.augmenteddriver.util.PageObject; import com.salesforceiq.augmenteddriver.util.PageObjectAssertionsInterface; import com.salesforceiq.augmenteddriver.util.PageObjectWaiter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Page Object for IOSPages with a container. * * <p> * Basically it is a helper so it is more convenient to follow the Page Object Pattern. * * The getters initializes the Page Object using Guice for dependency injection. * </p> */ public abstract class IOSPageContainerObject implements IOSPageObjectActionsInterface, PageObjectAssertionsInterface, PageObject { private static final Logger LOG = LoggerFactory.getLogger(IOSPageContainerObject.class); /** * Important we use a Provider, since we need the driver to be initialized when the first test starts to run * not at creation time, like Guice wants. */ @Inject private Provider<AugmentedIOSDriver> driverProvider; @Inject private IOSPageObjectActions iosPageObjectActions; private AugmentedIOSElement container; @Override public <T extends IOSPageObject> T get(Class<T> clazz) { return iosPageObjectActions.get(Preconditions.checkNotNull(clazz)); } @Override public <T extends IOSPageObject> T get(Class<T> clazz, Predicate<T> waitUntil) { return iosPageObjectActions.get(Preconditions.checkNotNull(clazz), Preconditions.checkNotNull(waitUntil)); } @Override public <T extends IOSPageContainerObject> T get(Class<T> clazz, AugmentedIOSElement container) { return iosPageObjectActions.get(Preconditions.checkNotNull(clazz), Preconditions.checkNotNull(container)); } @Override public <T extends IOSPageContainerObject> T get(Class<T> clazz, AugmentedIOSElement container, Predicate<T> waitUntil) { return iosPageObjectActions.get(Preconditions.checkNotNull(clazz), Preconditions.checkNotNull(container), Preconditions.checkNotNull(waitUntil)); } @Override public void assertPresent() { if (visibleBy().isPresent()) { container().augmented().findElementsVisible(visibleBy().get()); } } @Override public AugmentedIOSDriver driver() { return driverProvider.get(); } @Override public AugmentedIOSFunctions augmented() { return driverProvider.get().augmented(); } /** * DO NOT USE * * @param container the container to set. */ void setContainer(AugmentedIOSElement container) { this.container = Preconditions.checkNotNull(container); } /** * @return the container used by the Page Object. */ public AugmentedIOSElement container() { return Preconditions.checkNotNull(container); } @Override public PageObjectWaiter waiter() { return Preconditions.checkNotNull(iosPageObjectActions.waiter()); } }
apache-2.0
harryhoch/DeepPhe
src/org/apache/ctakes/typesystem/type/relation/TemporalTextRelation.java
1770
/* First created by JCasGen Mon May 11 11:00:52 EDT 2015 */ package org.apache.ctakes.typesystem.type.relation; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.jcas.cas.TOP_Type; /** A UMLS relation between clinical elements. * Updated by JCasGen Mon May 11 11:00:52 EDT 2015 * XML source: /home/tseytlin/Work/DeepPhe/ctakes-cancer/src/main/resources/org/apache/ctakes/cancer/types/TypeSystem.xml * @generated */ public class TemporalTextRelation extends BinaryTextRelation { /** @generated * @ordered */ @SuppressWarnings ("hiding") public final static int typeIndexID = JCasRegistry.register(TemporalTextRelation.class); /** @generated * @ordered */ @SuppressWarnings ("hiding") public final static int type = typeIndexID; /** @generated * @return index of the type */ @Override public int getTypeIndexID() {return typeIndexID;} /** Never called. Disable default constructor * @generated */ protected TemporalTextRelation() {/* intentionally empty block */} /** Internal - constructor used by generator * @generated * @param addr low level Feature Structure reference * @param type the type of this Feature Structure */ public TemporalTextRelation(int addr, TOP_Type type) { super(addr, type); readObject(); } /** @generated * @param jcas JCas to which this Feature Structure belongs */ public TemporalTextRelation(JCas jcas) { super(jcas); readObject(); } /** * <!-- begin-user-doc --> * Write your own initialization here * <!-- end-user-doc --> * * @generated modifiable */ private void readObject() {/*default - does nothing empty block */} }
apache-2.0
akritikos/PLH24
eElections/src/main/java/info/akritikos/eelections/queries/EVote.java
236
package info.akritikos.eelections.queries; import info.akritikos.eelections.contracts.ISearchQueries; /** * Search fields on Candidate entities */ public enum EVote implements ISearchQueries { PkVoteId, FldIsInvalid, FldIsBlank }
apache-2.0
rajmahendra/forge-jrebirth-addon
api/src/main/java/org/jrebirth/forge/addon/facets/JRebirthFacet.java
913
/** * Get more info at : www.jrebirth.org * Copyright JRebirth.org © 2011-2013 * Contact : sebastien.bordes@jrebirth.org * * 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.jrebirth.forge.addon.facets; import org.jboss.forge.addon.projects.ProjectFacet; /** * JRebirth Facet. * * @author Rajmahendra Hegde <rajmahendra@gmail.com> */ public interface JRebirthFacet extends ProjectFacet { }
apache-2.0
akhildixit/ad_public
Relative time from now/src/com/time/utilities/RelativeTimer.java
1568
package com.time.utilities; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * @author Akhil Dixit * */ public class RelativeTimer { /** * @param dateString * @param format * @return Relative time from/till now. Returns null in case of any * exception. */ public String compareToNow(String dateString, String format) { DateFormat myDateFormat = new SimpleDateFormat(format); Date lastDate = new Date(System.currentTimeMillis()); Date firstDate = null; try { firstDate = myDateFormat.parse(dateString); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } long first = firstDate.getTime(); long last = lastDate.getTime(); if (first > last) { return "In " + findDifference(last, first); } return findDifference(first, last) + " ago"; } /** * @param first * @param last * @return Approximate time difference between first to last */ private String findDifference(long first, long last) { long diff = last - first; if (diff < 1000) { return (diff + " millisecond(s)"); } diff /= 1000; if (diff < 60) { return (diff + " second(s)"); } diff /= 60; if (diff < 60) { return (diff + " minute(s)"); } diff /= 60; if (diff < 24) { return (diff + " hour(s)"); } diff /= 24; if (diff < 365) { return (diff + " day(s)"); } diff /= 365; return (diff + " year(s)"); } }
apache-2.0
Jimexist/presto
presto-main/src/main/java/com/facebook/presto/operator/ExchangeClient.java
13990
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator; import com.facebook.presto.execution.SystemMemoryUsageListener; import com.facebook.presto.execution.buffer.SerializedPage; import com.facebook.presto.operator.HttpPageBufferClient.ClientCallback; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import io.airlift.http.client.HttpClient; import io.airlift.units.DataSize; import io.airlift.units.Duration; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import java.io.Closeable; import java.net.URI; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import static com.facebook.presto.execution.buffer.PageCompression.UNCOMPRESSED; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Sets.newConcurrentHashSet; import static io.airlift.slice.Slices.EMPTY_SLICE; import static java.util.Objects.requireNonNull; @ThreadSafe public class ExchangeClient implements Closeable { private static final SerializedPage NO_MORE_PAGES = new SerializedPage(EMPTY_SLICE, UNCOMPRESSED, 0, 0); private final long maxBufferedBytes; private final DataSize maxResponseSize; private final int concurrentRequestMultiplier; private final Duration minErrorDuration; private final Duration maxErrorDuration; private final HttpClient httpClient; private final ScheduledExecutorService executor; @GuardedBy("this") private boolean noMoreLocations; private final ConcurrentMap<URI, HttpPageBufferClient> allClients = new ConcurrentHashMap<>(); @GuardedBy("this") private final Deque<HttpPageBufferClient> queuedClients = new LinkedList<>(); private final Set<HttpPageBufferClient> completedClients = newConcurrentHashSet(); private final LinkedBlockingDeque<SerializedPage> pageBuffer = new LinkedBlockingDeque<>(); @GuardedBy("this") private final List<SettableFuture<?>> blockedCallers = new ArrayList<>(); @GuardedBy("this") private long bufferBytes; @GuardedBy("this") private long successfulRequests; @GuardedBy("this") private long averageBytesPerRequest; private final AtomicBoolean closed = new AtomicBoolean(); private final AtomicReference<Throwable> failure = new AtomicReference<>(); private final SystemMemoryUsageListener systemMemoryUsageListener; public ExchangeClient( DataSize maxBufferedBytes, DataSize maxResponseSize, int concurrentRequestMultiplier, Duration minErrorDuration, Duration maxErrorDuration, HttpClient httpClient, ScheduledExecutorService executor, SystemMemoryUsageListener systemMemoryUsageListener) { this.maxBufferedBytes = maxBufferedBytes.toBytes(); this.maxResponseSize = maxResponseSize; this.concurrentRequestMultiplier = concurrentRequestMultiplier; this.minErrorDuration = minErrorDuration; this.maxErrorDuration = maxErrorDuration; this.httpClient = httpClient; this.executor = executor; this.systemMemoryUsageListener = systemMemoryUsageListener; } public synchronized ExchangeClientStatus getStatus() { int bufferedPages = pageBuffer.size(); if (bufferedPages > 0 && pageBuffer.peekLast() == NO_MORE_PAGES) { bufferedPages--; } ImmutableList.Builder<PageBufferClientStatus> exchangeStatus = ImmutableList.builder(); for (HttpPageBufferClient client : allClients.values()) { exchangeStatus.add(client.getStatus()); } return new ExchangeClientStatus(bufferBytes, averageBytesPerRequest, bufferedPages, noMoreLocations, exchangeStatus.build()); } public synchronized void addLocation(URI location) { requireNonNull(location, "location is null"); // ignore duplicate locations if (allClients.containsKey(location)) { return; } checkState(!noMoreLocations, "No more locations already set"); // ignore new locations after close if (closed.get()) { return; } HttpPageBufferClient client = new HttpPageBufferClient( httpClient, maxResponseSize, minErrorDuration, maxErrorDuration, location, new ExchangeClientCallback(), executor); allClients.put(location, client); queuedClients.add(client); scheduleRequestIfNecessary(); } public synchronized void noMoreLocations() { noMoreLocations = true; scheduleRequestIfNecessary(); } @Nullable public SerializedPage pollPage() { checkState(!Thread.holdsLock(this), "Can not get next page while holding a lock on this"); throwIfFailed(); if (closed.get()) { return null; } SerializedPage page = pageBuffer.poll(); return postProcessPage(page); } @Nullable public SerializedPage getNextPage(Duration maxWaitTime) throws InterruptedException { checkState(!Thread.holdsLock(this), "Can not get next page while holding a lock on this"); throwIfFailed(); if (closed.get()) { return null; } scheduleRequestIfNecessary(); SerializedPage page = pageBuffer.poll(); // only wait for a page if we have remote clients if (page == null && maxWaitTime.toMillis() >= 1 && !allClients.isEmpty()) { page = pageBuffer.poll(maxWaitTime.toMillis(), TimeUnit.MILLISECONDS); } return postProcessPage(page); } private SerializedPage postProcessPage(SerializedPage page) { checkState(!Thread.holdsLock(this), "Can not get next page while holding a lock on this"); if (page == NO_MORE_PAGES) { // mark client closed closed.set(true); // add end marker back to queue checkState(pageBuffer.add(NO_MORE_PAGES), "Could not add no more pages marker"); notifyBlockedCallers(); // don't return end of stream marker page = null; } if (page != null) { synchronized (this) { if (!closed.get()) { bufferBytes -= page.getRetainedSizeInBytes(); systemMemoryUsageListener.updateSystemMemoryUsage(-page.getRetainedSizeInBytes()); } } if (!closed.get() && pageBuffer.peek() == NO_MORE_PAGES) { closed.set(true); } scheduleRequestIfNecessary(); } return page; } public boolean isFinished() { throwIfFailed(); // For this to works, locations must never be added after is closed is set return isClosed() && completedClients.size() == allClients.size(); } public boolean isClosed() { return closed.get(); } @Override public synchronized void close() { if (!closed.compareAndSet(false, true)) { return; } for (HttpPageBufferClient client : allClients.values()) { closeQuietly(client); } pageBuffer.clear(); systemMemoryUsageListener.updateSystemMemoryUsage(-bufferBytes); bufferBytes = 0; if (pageBuffer.peekLast() != NO_MORE_PAGES) { checkState(pageBuffer.add(NO_MORE_PAGES), "Could not add no more pages marker"); } notifyBlockedCallers(); } public synchronized void scheduleRequestIfNecessary() { if (isFinished() || isFailed()) { return; } // if finished, add the end marker if (noMoreLocations && completedClients.size() == allClients.size()) { if (pageBuffer.peekLast() != NO_MORE_PAGES) { checkState(pageBuffer.add(NO_MORE_PAGES), "Could not add no more pages marker"); } if (!closed.get() && pageBuffer.peek() == NO_MORE_PAGES) { closed.set(true); } notifyBlockedCallers(); return; } long neededBytes = maxBufferedBytes - bufferBytes; if (neededBytes <= 0) { return; } int clientCount = (int) ((1.0 * neededBytes / averageBytesPerRequest) * concurrentRequestMultiplier); clientCount = Math.max(clientCount, 1); int pendingClients = allClients.size() - queuedClients.size() - completedClients.size(); clientCount -= pendingClients; for (int i = 0; i < clientCount; i++) { HttpPageBufferClient client = queuedClients.poll(); if (client == null) { // no more clients available return; } client.scheduleRequest(); } } public synchronized ListenableFuture<?> isBlocked() { if (isClosed() || isFailed() || pageBuffer.peek() != null) { return Futures.immediateFuture(true); } SettableFuture<?> future = SettableFuture.create(); blockedCallers.add(future); return future; } private synchronized boolean addPages(List<SerializedPage> pages) { if (isClosed() || isFailed()) { return false; } pageBuffer.addAll(pages); // notify all blocked callers notifyBlockedCallers(); long memorySize = pages.stream() .mapToLong(SerializedPage::getRetainedSizeInBytes) .sum(); bufferBytes += memorySize; systemMemoryUsageListener.updateSystemMemoryUsage(memorySize); successfulRequests++; long responseSize = pages.stream() .mapToLong(SerializedPage::getSizeInBytes) .sum(); // AVG_n = AVG_(n-1) * (n-1)/n + VALUE_n / n averageBytesPerRequest = (long) (1.0 * averageBytesPerRequest * (successfulRequests - 1) / successfulRequests + responseSize / successfulRequests); scheduleRequestIfNecessary(); return true; } private synchronized void notifyBlockedCallers() { List<SettableFuture<?>> callers = ImmutableList.copyOf(blockedCallers); blockedCallers.clear(); for (SettableFuture<?> blockedCaller : callers) { blockedCaller.set(null); } } private synchronized void requestComplete(HttpPageBufferClient client) { if (!queuedClients.contains(client)) { queuedClients.add(client); } scheduleRequestIfNecessary(); } private synchronized void clientFinished(HttpPageBufferClient client) { requireNonNull(client, "client is null"); completedClients.add(client); scheduleRequestIfNecessary(); } private synchronized void clientFailed(Throwable cause) { // TODO: properly handle the failed vs closed state // it is important not to treat failures as a successful close if (!isClosed()) { failure.compareAndSet(null, cause); notifyBlockedCallers(); } } private boolean isFailed() { return failure.get() != null; } private void throwIfFailed() { Throwable t = failure.get(); if (t != null) { throw Throwables.propagate(t); } } private class ExchangeClientCallback implements ClientCallback { @Override public boolean addPages(HttpPageBufferClient client, List<SerializedPage> pages) { requireNonNull(client, "client is null"); requireNonNull(pages, "pages is null"); boolean added = ExchangeClient.this.addPages(pages); scheduleRequestIfNecessary(); return added; } @Override public void requestComplete(HttpPageBufferClient client) { requireNonNull(client, "client is null"); ExchangeClient.this.requestComplete(client); } @Override public void clientFinished(HttpPageBufferClient client) { ExchangeClient.this.clientFinished(client); } @Override public void clientFailed(HttpPageBufferClient client, Throwable cause) { requireNonNull(client, "client is null"); requireNonNull(cause, "cause is null"); ExchangeClient.this.clientFailed(cause); } } private static void closeQuietly(HttpPageBufferClient client) { try { client.close(); } catch (RuntimeException e) { // ignored } } }
apache-2.0
demidenko05/beige-uml
beige-uml-swing/src/main/java/org/beigesoft/uml/factory/awt/FactoryAsmRelationshipBinaryClassLight.java
5499
package org.beigesoft.uml.factory.awt; import java.awt.Frame; import java.awt.Graphics2D; import java.awt.Image; import org.beigesoft.graphic.pojo.SettingsDraw; import org.beigesoft.graphic.service.ISrvDraw; import org.beigesoft.service.ISrvI18n; import org.beigesoft.ui.service.ISrvDialog; import org.beigesoft.uml.app.model.SettingsGraphicUml; import org.beigesoft.uml.assembly.AsmElementUmlInteractive; import org.beigesoft.uml.assembly.ClassFull; import org.beigesoft.uml.assembly.IAsmElementUmlInteractive; import org.beigesoft.uml.factory.IFactoryAsmElementUml; import org.beigesoft.uml.factory.swing.FactoryEditorRelationshipBinaryClass; import org.beigesoft.uml.pojo.ClassUml; import org.beigesoft.uml.pojo.RectangleRelationship; import org.beigesoft.uml.pojo.RelationshipBinary; import org.beigesoft.uml.service.graphic.SrvGraphicRelationshipBinary; import org.beigesoft.uml.service.interactive.SrvInteractiveRelationshipBinaryClass; import org.beigesoft.uml.service.persist.xmllight.FileAndWriter; import org.beigesoft.uml.service.persist.xmllight.SrvPersistLightXmlRelationshipBinaryClass; public class FactoryAsmRelationshipBinaryClassLight implements IFactoryAsmElementUml<IAsmElementUmlInteractive<RelationshipBinary<RectangleRelationship<ClassFull<ClassUml>, ClassUml>, ClassFull<ClassUml>, ClassUml>, Graphics2D, SettingsDraw, FileAndWriter>, Graphics2D, SettingsDraw, FileAndWriter, RelationshipBinary<RectangleRelationship<ClassFull<ClassUml>, ClassUml>, ClassFull<ClassUml>, ClassUml>> { private final ISrvDraw<Graphics2D, SettingsDraw, Image> srvDraw; private final SettingsGraphicUml settingsGraphic; private final FactoryEditorRelationshipBinaryClass factoryEditorRelationship; private final SrvGraphicRelationshipBinary<RelationshipBinary<RectangleRelationship<ClassFull<ClassUml>, ClassUml>, ClassFull<ClassUml>, ClassUml>, Graphics2D, SettingsDraw> srvGraphicRelationship; private final SrvPersistLightXmlRelationshipBinaryClass srvPersistRelationship; private final SrvInteractiveRelationshipBinaryClass<RelationshipBinary<RectangleRelationship<ClassFull<ClassUml>, ClassUml>, ClassFull<ClassUml>, ClassUml>, Frame, ClassUml> srvInteractiveRelationship; public FactoryAsmRelationshipBinaryClassLight(ISrvDraw<Graphics2D, SettingsDraw, Image> srvDraw, ISrvI18n i18nSrv, ISrvDialog<Frame> dialogSrv, SettingsGraphicUml settingsGraphic, Frame frameMain) { this.srvDraw = srvDraw; this.settingsGraphic = settingsGraphic; factoryEditorRelationship = new FactoryEditorRelationshipBinaryClass(i18nSrv, dialogSrv, settingsGraphic, frameMain); srvPersistRelationship = new SrvPersistLightXmlRelationshipBinaryClass(); srvGraphicRelationship = new SrvGraphicRelationshipBinary<RelationshipBinary<RectangleRelationship<ClassFull<ClassUml>, ClassUml>, ClassFull<ClassUml>, ClassUml>, Graphics2D, SettingsDraw> (srvDraw, settingsGraphic); srvInteractiveRelationship = new SrvInteractiveRelationshipBinaryClass<RelationshipBinary<RectangleRelationship<ClassFull<ClassUml>, ClassUml>, ClassFull<ClassUml>, ClassUml>, Frame, ClassUml> (factoryEditorRelationship, settingsGraphic, srvGraphicRelationship); } @Override public IAsmElementUmlInteractive<RelationshipBinary<RectangleRelationship<ClassFull<ClassUml>, ClassUml>, ClassFull<ClassUml>, ClassUml>, Graphics2D, SettingsDraw, FileAndWriter> createAsmElementUml() { SettingsDraw drawSettings = new SettingsDraw(); RelationshipBinary<RectangleRelationship<ClassFull<ClassUml>, ClassUml>, ClassFull<ClassUml>, ClassUml> relBinary = new RelationshipBinary<RectangleRelationship<ClassFull<ClassUml>, ClassUml>, ClassFull<ClassUml>, ClassUml>(); RectangleRelationship<ClassFull<ClassUml>, ClassUml> classRelStart = new RectangleRelationship<ClassFull<ClassUml>, ClassUml>(); relBinary.setShapeRelationshipStart(classRelStart); RectangleRelationship<ClassFull<ClassUml>, ClassUml> classRelEnd = new RectangleRelationship<ClassFull<ClassUml>, ClassUml>(); relBinary.setShapeRelationshipEnd(classRelEnd); AsmElementUmlInteractive<RelationshipBinary<RectangleRelationship<ClassFull<ClassUml>, ClassUml>, ClassFull<ClassUml>, ClassUml>, Graphics2D, SettingsDraw, FileAndWriter> asmRelBinClassFull = new AsmElementUmlInteractive<RelationshipBinary<RectangleRelationship<ClassFull<ClassUml>, ClassUml>, ClassFull<ClassUml>, ClassUml>, Graphics2D, SettingsDraw, FileAndWriter>(relBinary, drawSettings, srvGraphicRelationship, srvPersistRelationship, srvInteractiveRelationship); return asmRelBinClassFull; } //SGS: public ISrvDraw<Graphics2D, SettingsDraw, Image> getSrvDraw() { return srvDraw; } public SettingsGraphicUml getSettingsGraphic() { return settingsGraphic; } public FactoryEditorRelationshipBinaryClass getFactoryEditorRelationship() { return factoryEditorRelationship; } public SrvGraphicRelationshipBinary<RelationshipBinary<RectangleRelationship<ClassFull<ClassUml>, ClassUml>, ClassFull<ClassUml>, ClassUml>, Graphics2D, SettingsDraw> getSrvGraphicRelationship() { return srvGraphicRelationship; } public SrvPersistLightXmlRelationshipBinaryClass getSrvPersistRelationship() { return srvPersistRelationship; } public SrvInteractiveRelationshipBinaryClass<RelationshipBinary<RectangleRelationship<ClassFull<ClassUml>, ClassUml>, ClassFull<ClassUml>, ClassUml>, Frame, ClassUml> getSrvInteractiveRelationship() { return srvInteractiveRelationship; } }
apache-2.0
FarhatW/MaderaHouse
src/main/java/org/ril/madera/controller/UserController.java
2586
package org.ril.madera.controller; import org.ril.madera.model.Users; import org.ril.madera.service.ServicesUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; @Controller public class UserController { @Autowired private ServicesUser serviceUser; @RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET, headers = "Accept=application/json") public ModelAndView defaultPage() { // List<Users> listOfUsers = serviceUser.getAll(); // model.addAttribute("country", new Users()); // model.addAttribute("listOfUsers", listOfUsers); ModelAndView model = new ModelAndView(); model.addObject("title", "Spring Security Login Form - Database Authentication"); model.addObject("message", "This is default page!"); model.setViewName("users"); return model; } @RequestMapping(value = "/users/{id}", method = RequestMethod.GET, headers = "Accept=application/json") public Users getCountryById(@PathVariable int id) { return serviceUser.getById(id); } @RequestMapping(value = "/addUser", method = RequestMethod.POST, headers = "Accept=application/json") public String addCountry(@ModelAttribute("country") Users country) { if(country.getId()==0) { serviceUser.add(country); } else { serviceUser.update(country); } return "redirect:/users"; } @RequestMapping(value = "/updateUser/{id}", method = RequestMethod.GET, headers = "Accept=application/json") public String updateCountry(@PathVariable("id") int id,Model model) { model.addAttribute("country", this.serviceUser.getById(id)); model.addAttribute("listOfCountries", this.serviceUser.getAll()); return "country"; } @RequestMapping(value = "/deleteUser/{id}", method = RequestMethod.GET, headers = "Accept=application/json") public String deleteCountry(@PathVariable("id") int id) { serviceUser.delete(id); return "redirect:/Users"; } @RequestMapping(value = "/login", method = RequestMethod.GET) public ModelAndView login(@RequestParam(value = "error", required = false) String error, @RequestParam(value = "logout", required = false) String logout) { ModelAndView model = new ModelAndView(); if (error != null) { model.addObject("error", "Invalid username and password!"); } if (logout != null) { model.addObject("msg", "You've been logged out successfully."); } model.setViewName("login"); return model; } }
apache-2.0
Osman93/Android
Toast/src/com/example/toast/MainActivity.java
1138
package com.example.toast; import android.app.Activity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);//Bu kýsýmda layout klasörü içindeki activity_main.xml dosyasýný kullanýcý için getirdik.. Toast.makeText(MainActivity.this, "Toast Bildirim Mesajý", Toast.LENGTH_LONG).show(); /* * Toast sýnýfý makeText ile kullanýcýya bildirilecek mesajý düzenlemek için kullanýlýr.. * * MainActivity.this parametresi Toast 'ý nerde kullanacaðýmýzý göstermektedir. * * "Toast Bildirim Mesajý" kullanýcýya hangi yazýyý gösterceðimizi burda belirliyoruz yani 2.parametrede.. * * Toast.LENGTH_LONG uzun süreli mesajýn görünmesini saðlarken LENGTH_SHORT dersek daha kýsa süre ekranda kalacaktýr.. * * En son show() metodunu yazmazsanýz eðer Toast mesajýný göremezsiniz ....!!!! * * */ } }
apache-2.0
Governance/gadget-server
gadget-core/src/main/java/org/overlord/gadgets/server/model/WidgetPreference.java
1143
/** * */ package org.overlord.gadgets.server.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * @author Jeff Yu */ @Entity @Table(name="GS_WIDGET_PREF") public class WidgetPreference implements Serializable{ private static final long serialVersionUID = -1839969672969289874L; @Id @GeneratedValue @Column(name="WIDGET_PREF_ID") private long id; @Column(name="WIDGET_PREF_NAME") private String name; @Column(name="WIDGET_PREF_VALUE") private String value; @ManyToOne private Widget widget; public long getId() { return id; } public void setId(long id) { this.id = id; } 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 Widget getWidget() { return widget; } public void setWidget(Widget widget) { this.widget = widget; } }
apache-2.0
wolabs/womano
main/java/com/culabs/nfvo/model/ConfigBlock.java
614
package com.culabs.nfvo.model; public class ConfigBlock { private String id; private KVPair<String, String> pairs = KVPair.Factory.createKVPair( String.class, String.class); public String getId() { return id; } public void setId(String id) { this.id = id; } public KVPair<String, String> getPairs() { return pairs; } public void setPairs(KVPair<String, String> pairs) { this.pairs = pairs; } public void addPair(String key, String value) { this.pairs.add(key, value); } @Override public String toString() { return "ConfigBlock [id=" + id + ", pairs=" + pairs + "]"; } }
apache-2.0
shaolinwu/uimaster
modules/uipage/src/main/java/org/shaolin/uimaster/page/od/rules/UITextWithCurrency.java
8325
/* * Copyright 2015 The UIMaster Project * * The UIMaster Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.shaolin.uimaster.page.od.rules; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.shaolin.bmdp.json.JSONObject; import org.shaolin.uimaster.page.UserRequestContext; import org.shaolin.uimaster.page.exception.UIConvertException; import org.shaolin.uimaster.page.od.IODMappingConverter; import org.shaolin.uimaster.page.od.formats.FormatUtil; import org.shaolin.uimaster.page.widgets.HTMLLabelType; import org.shaolin.uimaster.page.widgets.HTMLTextWidgetType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UITextWithCurrency implements IODMappingConverter { private HTMLTextWidgetType uiText; private String uiid; private double currency; private String localeConfig; private Map<String, Object> propValues; private boolean displayZero; private boolean displaySymbol; public static UITextWithCurrency createRule() { return new UITextWithCurrency(); } public UITextWithCurrency() { this.displaySymbol = true; } public String getRuleName() { return this.getClass().getName(); } public HTMLTextWidgetType getUIText() { return this.uiText; } public void setUIText(HTMLTextWidgetType UIText) { this.uiText = UIText; } private HTMLTextWidgetType getUIHTML() { return this.uiText; } public double getCurrency() { return this.currency; } public void setCurrency(double Currency) { this.currency = Currency; } public String getLocaleConfig() { return this.localeConfig; } public void setLocaleConfig(String LocaleConfig) { this.localeConfig = LocaleConfig; } public Map<String, Object> getPropValues() { return this.propValues; } public void setPropValues(Map<String, Object> PropValues) { this.propValues = PropValues; } public boolean getDisplayZero() { return this.displayZero; } public void setDisplayZero(boolean displayZero) { this.displayZero = displayZero; } public boolean getDisplaySymbol() { return this.displaySymbol; } public void setDisplaySymbol(boolean displaySymbol) { this.displaySymbol = displaySymbol; } public Map<String, Class<?>> getDataEntityClassInfo() { HashMap<String, Class<?>> dataClassInfo = new LinkedHashMap<String, Class<?>>(); dataClassInfo.put("Currency", Double.TYPE); dataClassInfo.put("DisplayStringData", String.class); dataClassInfo.put("CurrencyFormat", String.class); dataClassInfo.put("LocaleConfig", String.class); dataClassInfo.put("PropValues", Map.class); dataClassInfo.put("displayZero", Boolean.TYPE); dataClassInfo.put("StringData", String.class); dataClassInfo.put("NumberObject", Object.class); dataClassInfo.put("StyleMap", Map.class); dataClassInfo.put("displaySymbol", Boolean.TYPE); return dataClassInfo; } public Map<String, Class<?>> getUIEntityClassInfo() { HashMap<String, Class<?>> uiClassInfo = new HashMap<String, Class<?>>(); uiClassInfo.put(UI_WIDGET_TYPE, HTMLTextWidgetType.class); return uiClassInfo; } public static Map<String, String> getRequiredUIParameter(String param) { HashMap<String, String> dataClassInfo = new LinkedHashMap<String, String>(); dataClassInfo.put(UI_WIDGET_TYPE, param); return dataClassInfo; } public static Map<String, String> getRequiredDataParameters(String value) { HashMap<String, String> dataClassInfo = new LinkedHashMap<String, String>(); dataClassInfo.put("Currency", value); return dataClassInfo; } public void setInputData(Map<String, Object> paramValue) throws UIConvertException { try { if (paramValue.containsKey(UI_WIDGET_TYPE)) { this.uiText = ((HTMLTextWidgetType) paramValue.get(UI_WIDGET_TYPE)); } if (paramValue.containsKey(UI_WIDGET_ID)) { this.uiid = (String) paramValue.get(UI_WIDGET_ID); } if (paramValue.containsKey("Currency")) { this.currency = ((Number) paramValue.get("Currency")) .doubleValue(); } // options if (paramValue.containsKey("PropValues")) { this.propValues = ((Map) paramValue.get("PropValues")); } if (paramValue.containsKey("LocaleConfig")) { this.localeConfig = ((String) paramValue .get("LocaleConfig")); } if (paramValue.containsKey("displayZero")) { this.displayZero = ((Boolean) paramValue.get("displayZero")) .booleanValue(); } if (paramValue.containsKey("displaySymbol")) { this.displaySymbol = ((Boolean) paramValue .get("displaySymbol")).booleanValue(); } } catch (Throwable t) { if (t instanceof UIConvertException) { throw ((UIConvertException) t); } throw new UIConvertException("EBOS_ODMAPPER_070", t, new Object[] { getUIHTML().getUIID() }); } } public Map<String, Object> getOutputData() throws UIConvertException { Map<String, Object> paramValue = new HashMap<String, Object>(); try { paramValue.put(UI_WIDGET_TYPE, this.uiText); paramValue.put("Currency", Double.valueOf(this.currency)); paramValue.put("PropValues", this.propValues); paramValue.put("LocaleConfig", this.localeConfig); paramValue.put("displayZero", Boolean.valueOf(this.displayZero)); paramValue.put("displaySymbol",Boolean.valueOf(this.displaySymbol)); } catch (Throwable t) { if (t instanceof UIConvertException) { throw ((UIConvertException) t); } throw new UIConvertException("EBOS_ODMAPPER_071", t, new Object[] { getUIHTML().getUIID() }); } return paramValue; } public String[] getImplementInterfaceName() { return new String[0]; } public void pushDataToWidget(UserRequestContext htmlContext) throws UIConvertException { try { if (this.displaySymbol) { Map<String, Object> styleMap = FormatUtil.getCurrencyStyle(this.localeConfig); this.uiText.setLocale(this.localeConfig); this.uiText.setCurrencySymbol((String) styleMap.get("currencySymbol")); this.uiText.setCurrencyFormat((String) styleMap.get("currencyFormat")); this.uiText.setIsSymbolLeft((Boolean) styleMap.get("isLeft")); } if ((this.displayZero) || (this.currency != 0.0D)) { String value = FormatUtil.convertDataToUI(FormatUtil.CURRENCY, new Double( this.currency), this.localeConfig, this.propValues); this.uiText.setValue(value); if (this.uiText instanceof HTMLLabelType) { ((HTMLLabelType) this.uiText).setDisplayValue(value); } } this.uiText.setIsCurrency(true); } catch (Throwable t) { if (t instanceof UIConvertException) { throw ((UIConvertException) t); } throw new UIConvertException("EBOS_ODMAPPER_072", t, new Object[] { getUIHTML().getUIID() }); } } public void pullDataFromWidget(UserRequestContext htmlContext) throws UIConvertException { try { // TextWidget textComp = (TextWidget) AjaxActionHelper // .getCachedAjaxWidget(this.uiid, htmlContext); // String value = textComp.getValue(); JSONObject textComp = htmlContext.getAjaxWidget(this.uiid); if (textComp == null) { logger.warn(this.uiid + " does not exist for data to ui mapping!"); return; } String value = textComp.getJSONObject("attrMap").getString("value"); if (value == null || "".equals(value.trim())) { this.currency = 0.0D; } else { Object numberObject = FormatUtil.convertUIToData(FormatUtil.CURRENCY, value, this.localeConfig, this.propValues); this.currency = ((Number) numberObject).doubleValue(); } } catch (Throwable t) { if (t instanceof UIConvertException) { throw ((UIConvertException) t); } throw new UIConvertException("EBOS_ODMAPPER_073", t, new Object[] { this.uiid }); } } public void callAllMappings(boolean isDataToUI) throws UIConvertException { } private static final Logger logger = LoggerFactory.getLogger(UIText.class); }
apache-2.0
artyomkorzun/efix
src/main/java/org/efix/message/field/ExecAckStatus.java
220
package org.efix.message.field; public class ExecAckStatus { public static final byte RECEIVED_NOT_YET_PROCESSED = '0'; public static final byte ACCEPTED = '1'; public static final byte DONT_KNOW = '2'; }
apache-2.0
kubernetes-client/java
kubernetes/src/main/java/io/kubernetes/client/openapi/models/V1ServerAddressByClientCIDR.java
4101
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package io.kubernetes.client.openapi.models; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Objects; /** * ServerAddressByClientCIDR helps the client to determine the server address that they should use, * depending on the clientCIDR that they match. */ @ApiModel( description = "ServerAddressByClientCIDR helps the client to determine the server address that they should use, depending on the clientCIDR that they match.") @javax.annotation.Generated( value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-12-10T19:11:23.904Z[Etc/UTC]") public class V1ServerAddressByClientCIDR { public static final String SERIALIZED_NAME_CLIENT_C_I_D_R = "clientCIDR"; @SerializedName(SERIALIZED_NAME_CLIENT_C_I_D_R) private String clientCIDR; public static final String SERIALIZED_NAME_SERVER_ADDRESS = "serverAddress"; @SerializedName(SERIALIZED_NAME_SERVER_ADDRESS) private String serverAddress; public V1ServerAddressByClientCIDR clientCIDR(String clientCIDR) { this.clientCIDR = clientCIDR; return this; } /** * The CIDR with which clients can match their IP to figure out the server address that they * should use. * * @return clientCIDR */ @ApiModelProperty( required = true, value = "The CIDR with which clients can match their IP to figure out the server address that they should use.") public String getClientCIDR() { return clientCIDR; } public void setClientCIDR(String clientCIDR) { this.clientCIDR = clientCIDR; } public V1ServerAddressByClientCIDR serverAddress(String serverAddress) { this.serverAddress = serverAddress; return this; } /** * Address of this server, suitable for a client that matches the above CIDR. This can be a * hostname, hostname:port, IP or IP:port. * * @return serverAddress */ @ApiModelProperty( required = true, value = "Address of this server, suitable for a client that matches the above CIDR. This can be a hostname, hostname:port, IP or IP:port.") public String getServerAddress() { return serverAddress; } public void setServerAddress(String serverAddress) { this.serverAddress = serverAddress; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } V1ServerAddressByClientCIDR v1ServerAddressByClientCIDR = (V1ServerAddressByClientCIDR) o; return Objects.equals(this.clientCIDR, v1ServerAddressByClientCIDR.clientCIDR) && Objects.equals(this.serverAddress, v1ServerAddressByClientCIDR.serverAddress); } @Override public int hashCode() { return Objects.hash(clientCIDR, serverAddress); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class V1ServerAddressByClientCIDR {\n"); sb.append(" clientCIDR: ").append(toIndentedString(clientCIDR)).append("\n"); sb.append(" serverAddress: ").append(toIndentedString(serverAddress)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
apache-2.0
davidsky11/DesignMode
src/main/java/com/kv/structural/decorator/ConcreteTarget.java
195
package com.kv.structural.decorator; // 被装饰的类 public class ConcreteTarget implements Target { @Override public void operation() { System.out.println("Original operation."); } }
apache-2.0
breakpoint-au/Hedron
hedron-daogen/src/main/java/au/com/breakpoint/hedron/daogen/DaoGen.java
26492
// __________________________________ // ______| Copyright 2008-2015 |______ // \ | Breakpoint Pty Limited | / // \ | http://www.breakpoint.com.au | / // / |__________________________________| \ // /_________/ \_________\ // // 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 au.com.breakpoint.hedron.daogen; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Callable; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.kohsuke.args4j.Option; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import au.com.breakpoint.hedron.core.GenericFactory; import au.com.breakpoint.hedron.core.HcUtil; import au.com.breakpoint.hedron.core.JsonUtil; import au.com.breakpoint.hedron.core.SmartFile; import au.com.breakpoint.hedron.core.UserFeedback; import au.com.breakpoint.hedron.core.args4j.HcUtilArgs4j; import au.com.breakpoint.hedron.core.context.ExecutionScopes; import au.com.breakpoint.hedron.core.context.ThreadContext; import au.com.breakpoint.hedron.daogen.strategy.IOverrideStrategy; import au.com.breakpoint.hedron.daogen.strategy.IRelationCodeStrategy; import au.com.breakpoint.hedron.daogen.strategy.SpringJdbcTemplateCodeStrategy; import au.com.breakpoint.hedron.daogen.strategy.StoredProcedureOverrideStrategy; import au.com.breakpoint.hedron.daogen.strategy.TableOverrideStrategy; public class DaoGen { public void generateDaos (final String[] args) { // Check args & prepare usage string (in thrown AssertException). HcUtilArgs4j.getProgramOptions (args, m_commandLine); m_feedback = new UserFeedback (m_commandLine.m_debug); getOptionsFromFile (m_commandLine.m_optionsFile); getSchema (); final List<String> messages = GenericFactory.newArrayList (); // Take any actions prior to generation. messages.addAll (m_options.m_codeStrategy.preGenerate (m_options)); messages.addAll (generateDaos ()); messages.addAll (generateKeywordList ()); // Take any actions after generation. messages.addAll (m_options.m_codeStrategy.postGenerate ()); for (final String s : messages) { if (HcUtil.safeGetLength (s) > 0) { System.out.printf ("%n %s", s); } } // Output any unused filter rules for info only. showUnusedFilterRules (); m_feedback.outputMessage (true, 0, "DAOs generated for %s", m_commandLine.m_optionsFile); } private void addOverrides (final Node parentNode) { final Options options = m_options; final NodeList childNodes = parentNode.getChildNodes (); for (int s = 0; s < childNodes.getLength (); ++s) { final Node node = childNodes.item (s); if (node.getNodeType () == Node.ELEMENT_NODE) { final String nodeName = node.getNodeName (); if (nodeName.equals ("stored-procedure")) { final IOverrideStrategy fo = new StoredProcedureOverrideStrategy (options, node); options.m_overrides.add (fo); } else if (nodeName.equals ("table")) { final IOverrideStrategy fo = new TableOverrideStrategy (options, node); options.m_overrides.add (fo); } else { ThreadContext.assertError (false, "[%s] unknown option element [%s]", getClass ().getSimpleName (), nodeName); } } } } private void applyUserOverrides () { final SchemaObjects schemaObjects = m_schema.getSchemaObjects (); for (final IOverrideStrategy io : m_options.m_overrides) { io.override (schemaObjects); } } private void createCustomViewEntity (final CustomView cv) { final SchemaObjects schemaObjects = m_schema.getSchemaObjects (); final Table e = new Table (cv); final String typeName = cv.getEntityName (); schemaObjects.m_customEntities.put (typeName, e); } private List<String> generateCommandCode (final Command o) { return m_options.m_codeStrategy.generateDao (o, m_schema); } private List<String> generateCustomViewCode (final CustomView o) { return m_options.m_codeStrategy.generateDao (o, m_schema); } private List<String> generateDaos () { final SchemaObjects schemaObjects = m_schema.getSchemaObjects (); // Generate concurrently. final List<Callable<List<String>>> tasks = GenericFactory.newArrayList (); for (final Map.Entry<String, DbEnum> entry : schemaObjects.m_enums.entrySet ()) { final DbEnum en = entry.getValue (); if (shouldGenerateDao (en)) { tasks.add ( () -> generateIRelationCode (en)); } } for (final Map.Entry<String, Table> entry : schemaObjects.m_tables.entrySet ()) { final IRelation ir = entry.getValue (); final List<Capability> capabilities = GenericFactory.newArrayList ();// to be filled in by shouldGenerateDao if (shouldGenerateDao (capabilities, ir)) { tasks.add ( () -> generateIRelationCode (ir, capabilities)); } } for (final Map.Entry<String, Table> entry : schemaObjects.m_customEntities.entrySet ()) { final IRelation ir = entry.getValue (); // Generate entity for this relation. final List<Capability> noCapabilities = GenericFactory.newArrayList ();// to be filled in by shouldGenerateDao tasks.add ( () -> generateIRelationCode (ir, noCapabilities)); } for (final Map.Entry<String, View> entry : schemaObjects.m_views.entrySet ()) { final IRelation ir = entry.getValue (); final List<Capability> capabilities = GenericFactory.newArrayList ();// to be filled in by shouldGenerateDao if (shouldGenerateDao (capabilities, ir)) { tasks.add ( () -> generateIRelationCode (ir, capabilities)); } } for (final Map.Entry<String, StoredProcedure> entry : schemaObjects.m_storedProcedures.entrySet ()) { final StoredProcedure o = entry.getValue (); if (shouldGenerateDao (o)) { tasks.add ( () -> generateStoredProcedureCode (o)); } } for (final Map.Entry<String, CustomView> entry : schemaObjects.m_customViews.entrySet ()) { final CustomView o = entry.getValue (); if (shouldGenerateDao (o)) { tasks.add ( () -> generateCustomViewCode (o)); } } for (final Map.Entry<String, Command> entry : schemaObjects.m_commands.entrySet ()) { final Command o = entry.getValue (); if (shouldGenerateDao (o)) { tasks.add ( () -> generateCommandCode (o)); } } // Execute all the code generation concurrently. final int nrThreads = 20; final List<List<String>> results = HcUtil.executeConcurrently (tasks, nrThreads, true); // // Execute and gather output using fork-join. // final Function<Callable<List<String>>, List<String>> work = // new Function<Callable<List<String>>, List<String>> () // { // @Override // public List<String> getValue (final Callable<List<String>> a) // { // List<String> v = null; // try // { // v = a.call (); // } // catch (final Exception e) // { // // Propagate exception as unchecked fault up to the fault barrier. // ThreadContext.throwFault (e); // } // return v; // } // }; // final List<List<String>> results = HcUtil.executeConcurrently (tasks, work); final List<String> feedback = HcUtil.mergeLists (results); return feedback; } private List<String> generateIRelationCode (final DbEnum en) { final List<String> results = GenericFactory.newArrayList (); results.addAll (m_options.m_codeStrategy.generateDao (en, m_schema)); return results; } private List<String> generateIRelationCode (final IRelation ir, final List<Capability> capabilities) { final List<String> results = GenericFactory.newArrayList (); // Entity first. If the relation shares another relation's entity, don't // generate an entity here. if (!EntityUtil.mapsToAnotherEntity (ir)) { // Generate entity for this relation. results.addAll (m_options.m_codeStrategy.generateEntity (ir, m_schema)); } // Then DAO. results.addAll (m_options.m_codeStrategy.generateDao (ir, m_schema, capabilities)); return results; } private List<String> generateKeywordList () { final List<String> feedback = GenericFactory.newArrayList (); final String filepath = HcUtil.formFilepath (".", "keywords.generated.json"); final Map<String, String[]> keywordMap = getSchemaKeywords (); final String json = JsonUtil.toJson (keywordMap); try (final SmartFile pw = new SmartFileShowingProgress (filepath)) { pw.print (json); } return feedback; } private List<String> generateStoredProcedureCode (final StoredProcedure o) { return m_options.m_codeStrategy.generateStoredProcDao (o, m_schema); } private IRelation getIRelation (final String typeName) { final IRelation ir = m_schema.getIRelationNoThrow (typeName); ThreadContext.assertError (ir != null, "Unknown typeName [%s]", typeName); return ir; } private void getOptionsFromFile (final String optionsFilename) { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance (); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder (); } catch (final ParserConfigurationException e) { ThreadContext.assertFault (false, "XML parser error [%s]", e.getMessage ()); } Document doc = null; try { final File file = new File (optionsFilename); doc = db.parse (file); } catch (final SAXException e) { ThreadContext.assertFault (false, "XML error [%s]", e.getMessage ()); } catch (final IOException e) { ThreadContext.assertFault (false, "Cannot read file [%s]:%n%s", optionsFilename, e.getMessage ()); } doc.getDocumentElement ().normalize (); final NodeList topLevelNodes = doc.getDocumentElement ().getChildNodes (); m_options.m_optionsFilename = optionsFilename; for (int s = 0; s < topLevelNodes.getLength (); ++s) { final Node node = topLevelNodes.item (s); if (node.getNodeType () == Node.ELEMENT_NODE) { final String nodeName = node.getNodeName (); final String value = HcUtil.getTrimmedText (node); if (nodeName.equals ("output-base-filepath")) { m_options.m_outputBaseFilepath = value; } else if (nodeName.equals ("output-package")) { m_options.m_outputPackage = value; } else if (nodeName.equals ("database-type")) { try { m_options.m_databaseType = DatabaseType.valueOf (value); } catch (final IllegalArgumentException e) { ThreadContext.assertError (false, "Unsupported database type value [%s]", value); } } else if (nodeName.equals ("database-version")) { m_options.m_databaseVersion = value; } else if (nodeName.equals ("schema-filename")) { m_options.m_schemaFilename = value; } else if (nodeName.equals ("additional-schema-filename")) { m_options.m_additionalEntityFilename = value; } else if (nodeName.equals ("filter")) { m_filters.add (new Filter (node)); } else if (nodeName.equals ("bean-style-definitions")) { m_options.m_generateBeanStyleDefinitions = Boolean.valueOf (value); } else if (nodeName.equals ("overrides")) { addOverrides (node); } else if (nodeName.equals ("code-strategy")) { final String strategyClassName = SpringJdbcTemplateCodeStrategy.class.getPackage ().getName () + "." + value + "CodeStrategy"; final Class<?> c = HcUtil.getClassObject (strategyClassName); m_options.m_codeStrategy = (IRelationCodeStrategy) HcUtil.instantiate (c); } else { ThreadContext.assertError (false, "[%s] unknown option element [%s]", getClass ().getSimpleName (), nodeName); } } } // Set database-specific behaviour. switch (m_options.m_databaseType) { case Oracle: { // SpringJdbcTemplateCodeStrategy.setShouldUseSimpleJdbcInsert (false); // SpringJdbcTemplateCodeStrategy.setShouldUseSimpleJdbcCall (false); break; } case Sybase: { // SpringJdbcTemplateCodeStrategy.setShouldUseSimpleJdbcInsert (false); // SpringJdbcTemplateCodeStrategy.setShouldUseSimpleJdbcCall (false); break; } } } private void getSchema () { m_schema = parseSchemaDefinitions (m_options.m_schemaFilename); if (m_options.m_additionalEntityFilename != null) { // Copy in any additional entities. final Schema additionalSchema = parseSchemaDefinitions (m_options.m_additionalEntityFilename); m_schema.addSchemaObjects (additionalSchema); } // Now apply any user-specified overrides. applyUserOverrides (); // Ensure any extra entities required by stored procedures/custom views are // marked to be generated. markEntitiesForGeneration (); } private Map<String, String[]> getSchemaKeywords () { final List<String> enums = GenericFactory.newArrayList (); final List<String> tables = GenericFactory.newArrayList (); final List<String> views = GenericFactory.newArrayList (); final List<String> storedProcedures = GenericFactory.newArrayList (); final SchemaObjects schemaObjects = m_schema.getSchemaObjects (); // Generate concurrently. for (final Map.Entry<String, DbEnum> entry : schemaObjects.m_enums.entrySet ()) { final DbEnum e = entry.getValue (); enums.add (HcUtil.caseBreakToUnderScoreBreak (e.getName ())); } for (final Map.Entry<String, Table> entry : schemaObjects.m_tables.entrySet ()) { final Table e = entry.getValue (); tables.add (e.getPhysicalName ()); } for (final Map.Entry<String, View> entry : schemaObjects.m_views.entrySet ()) { final View e = entry.getValue (); views.add (e.getPhysicalName ()); } for (final Map.Entry<String, StoredProcedure> entry : schemaObjects.m_storedProcedures.entrySet ()) { final StoredProcedure e = entry.getValue (); final String physicalName = e.getPhysicalName (); // Remove any package prefix. final int index = physicalName.lastIndexOf ('.'); final String procName = index == -1 ? physicalName : physicalName.substring (index + 1); storedProcedures.add (procName); } final Map<String, String[]> e = GenericFactory.newTreeMap (); e.put ("enum", toSortedArray (enums)); e.put ("table", toSortedArray (tables)); e.put ("view", toSortedArray (views)); e.put ("storedProcedure", toSortedArray (storedProcedures)); return e; } private void markEntitiesForGeneration () { final SchemaObjects schemaObjects = m_schema.getSchemaObjects (); // Look for tables that map to another entity. for (final Map.Entry<String, Table> entry : schemaObjects.m_tables.entrySet ()) { final IRelation ir = entry.getValue (); if (shouldGenerateDao (ir)) { if (EntityUtil.mapsToAnotherEntity (ir)) { // Shared entity to be generated. m_setAdditionalTypes.add (ir.getEntityName ()); } } } // Look for custom views that reference an existing entity or create a custom entity. for (final Entry<String, CustomView> entry : schemaObjects.m_customViews.entrySet ()) { final CustomView cv = entry.getValue (); if (shouldGenerateDao (cv)) { final String customEntityName = cv.getCustomEntity (); if (customEntityName != null) { final IRelation ir = m_schema.getIRelationNoThrow (customEntityName); ThreadContext.assertError (ir == null, "Custom view %s defines custom entity %s. An entity with the name %s already exists", cv.getName (), customEntityName, customEntityName); // Synthesise the entity now. createCustomViewEntity (cv); m_setAdditionalTypes.add (customEntityName); } else { final String typeName = cv.getEntityName (); final IRelation ir = getIRelation (typeName); if (!shouldGenerateDao (ir)) { // The entity wasn't in use. Generate a readonly version of the entity // for use by the stored proc. m_setAdditionalTypes.add (ir.getEntityName ()); } } } } // Look for stored procedures that reference entities in output result sets. for (final Map.Entry<String, StoredProcedure> entry : schemaObjects.m_storedProcedures.entrySet ()) { final StoredProcedure sp = entry.getValue (); final List<StoredProcedureResultSet> resultSets = sp.getResultSets (); for (final StoredProcedureResultSet sprs : resultSets) { // Here's a referenced type. final String typeName = sprs.getType (); final IRelation ir = getIRelation (typeName); if (!shouldGenerateDao (ir)) { // The entity wasn't in use. Generate a readonly version of the entity // for use by the stored proc. m_setAdditionalTypes.add (typeName); } } } } private Schema parseSchemaDefinitions (final String filename) { final Element documentElement = parseXml (filename); final String documentElementNodeName = documentElement.getNodeName (); ThreadContext.assertError (documentElementNodeName.equals ("schema"), "Document element must be 'schema', not '%s'", documentElementNodeName); return new Schema (documentElement); } private Element parseXml (final String filename) { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance (); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder (); } catch (final ParserConfigurationException e) { ThreadContext.assertFault (false, "XML parser error [%s]", e.getMessage ()); } Document doc = null; try { final File file = new File (filename); doc = db.parse (file); } catch (final SAXException e) { ThreadContext.assertFault (false, "XML error [%s]", e.getMessage ()); } catch (final IOException e) { ThreadContext.assertFault (false, "Cannot read file [%s]%n", filename); } final Element documentElement = doc.getDocumentElement (); documentElement.normalize (); return documentElement; } private boolean shouldGenerateDao (final Command o) { return shouldGenerateDao ("command", o.getName ()); } private boolean shouldGenerateDao (final CustomView o) { return shouldGenerateDao ("customview", o.getName ()); } private boolean shouldGenerateDao (@SuppressWarnings ("unused") final DbEnum en) { // TODO 0 filterable by user input file? return true; } private boolean shouldGenerateDao (final IRelation ir) { final List<Capability> capabilities = GenericFactory.newArrayList ();// to be filled in by shouldGenerateDao; ignored here return shouldGenerateDao (capabilities, ir); } private boolean shouldGenerateDao (final List<Capability> capabilities, final IRelation ir) { final BooleanHolder okHolder = new BooleanHolder (); final String name = ir.getName (); for (final Filter f : m_filters) { f.evaluateFilter (ir.getRelationType (), name, okHolder, capabilities); } boolean ok = okHolder.getValue (); if (!ok) { // No dao generation specified by filter rules. See if one is required // by a stored proc. ok = m_setAdditionalTypes.contains (name); } return ok; } private boolean shouldGenerateDao (final StoredProcedure o) { return shouldGenerateDao ("storedprocedure", o.getName ()); } private boolean shouldGenerateDao (final String type, final String name) { final BooleanHolder ok = new BooleanHolder (); final List<Capability> capabilities = GenericFactory.newArrayList ();// to be filled in by shouldGenerateDao for (final Filter f : m_filters) { f.evaluateFilter (type, name, ok, capabilities); } return ok.getValue (); } private void showUnusedFilterRules () { final List<String> unusedRules = GenericFactory.newArrayList (); for (final Filter f : m_filters) { unusedRules.addAll (f.getUnusedFilterRules ()); } if (m_commandLine.m_debug && unusedRules.size () > 0) { m_feedback.outputMessage (true, 0, "%nWarning - unused filter rules:"); for (final String s : unusedRules) { m_feedback.outputMessage (s, true, 1); } } } private String[] toSortedArray (final List<String> l) { Collections.sort (l); return l.toArray (new String[l.size ()]); } private class CommandLine { @Option (name = "-d", aliases = { "--debug" }, required = false) private boolean m_debug; @Option (name = "-o", aliases = { "--options" }, usage = "Specifies the name of the DAO generation options XML file *REQUIRED*", required = true) private String m_optionsFile; } public static UserFeedback getFeedback () { return m_feedback; } public static void main (final String[] args) { ExecutionScopes.executeProgram ( () -> new DaoGen ().generateDaos (args)); } final CommandLine m_commandLine = new CommandLine (); private final List<Filter> m_filters = GenericFactory.newArrayList (); private final Options m_options = new Options (); private Schema m_schema; private final Set<String> m_setAdditionalTypes = GenericFactory.newHashSet (); private static UserFeedback m_feedback; // private static final List<Capability> m_readonlyCapabilities = GenericFactory.newArrayList (Capability.READ); }
apache-2.0
PearsonEducation/StatsAgg
src/main/java/com/pearson/statsagg/web_ui/Lookup.java
6292
package com.pearson.statsagg.web_ui; import com.pearson.statsagg.database_objects.alerts.AlertsDao; import com.pearson.statsagg.database_objects.metric_group.MetricGroupsDao; import com.pearson.statsagg.database_objects.notifications.NotificationGroupsDao; import com.pearson.statsagg.utilities.core_utils.StackTrace; import java.io.PrintWriter; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; import org.apache.commons.text.StringEscapeUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Jeffrey Schmidt */ @WebServlet(name = "Lookup", urlPatterns = {"/Lookup"}) public class Lookup extends HttpServlet { private static final Logger logger = LoggerFactory.getLogger(Lookup.class.getName()); public static final String PAGE_NAME = "Lookup"; /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) { processGetRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) { processGetRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return PAGE_NAME; } protected void processGetRequest(HttpServletRequest request, HttpServletResponse response) { if ((request == null) || (response == null)) { return; } try { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } PrintWriter out = null; String type = request.getParameter("Type"); String query = request.getParameter("Query"); try { String results = "[]"; if (type != null) { if (type.equals("AlertName")) results = createAlertNamesJson(query); else if (type.equals("MetricGroupName")) results = createMetricGroupNamesJson(query); else if (type.equals("NotificationGroupName")) results = createNotificationGroupNamesJson(query); } out = response.getWriter(); out.println(results); } catch (Exception e) { logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e)); } finally { if (out != null) { out.close(); } } } protected String createAlertNamesJson(String alertNamesQuery) { if (alertNamesQuery == null) { return ""; } AlertsDao alertsDao = new AlertsDao(); List<String> alertNames = alertsDao.getAlertNames(alertNamesQuery, 10); StringBuilder json = new StringBuilder(); json.append("["); int i = 1; for (String name : alertNames) { json.append("{"); json.append("\"HtmlValue\":\"").append(StringEscapeUtils.escapeJson(StatsAggHtmlFramework.htmlEncode(name))).append("\","); json.append("\"Value\":\"").append(StringEscapeUtils.escapeJson(name)).append("\""); json.append("}"); if (i < alertNames.size()) json.append(","); i++; } json.append("]"); return json.toString(); } protected String createMetricGroupNamesJson(String metricGroupNamesQuery) { if (metricGroupNamesQuery == null) { return ""; } MetricGroupsDao metricGroupsDao = new MetricGroupsDao(); List<String> metricGroupsNames = metricGroupsDao.getMetricGroupNames(metricGroupNamesQuery, 10); StringBuilder json = new StringBuilder(); json.append("["); int i = 1; for (String name : metricGroupsNames) { json.append("{"); json.append("\"HtmlValue\":\"").append(StringEscapeUtils.escapeJson(StatsAggHtmlFramework.htmlEncode(name))).append("\","); json.append("\"Value\":\"").append(StringEscapeUtils.escapeJson(name)).append("\""); json.append("}"); if (i < metricGroupsNames.size()) json.append(","); i++; } json.append("]"); return json.toString(); } protected String createNotificationGroupNamesJson(String notificationGroupNamesQuery) { if (notificationGroupNamesQuery == null) { return ""; } NotificationGroupsDao notificationGroupsDao = new NotificationGroupsDao(); List<String> notificationGroupsNames = notificationGroupsDao.getNotificationGroupNames(notificationGroupNamesQuery, 10); StringBuilder json = new StringBuilder(); json.append("["); int i = 1; for (String name : notificationGroupsNames) { json.append("{"); json.append("\"HtmlValue\":\"").append(StringEscapeUtils.escapeJson(StatsAggHtmlFramework.htmlEncode(name))).append("\","); json.append("\"Value\":\"").append(StringEscapeUtils.escapeJson(name)).append("\""); json.append("}"); if (i < notificationGroupsNames.size()) json.append(","); i++; } json.append("]"); return json.toString(); } }
apache-2.0
consulo/consulo
modules/base/lang-api/src/main/java/com/intellij/psi/codeStyle/arrangement/match/ArrangementSectionRule.java
5547
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.codeStyle.arrangement.match; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.codeStyle.arrangement.ArrangementUtil; import com.intellij.psi.codeStyle.arrangement.model.ArrangementAtomMatchCondition; import com.intellij.psi.codeStyle.arrangement.model.ArrangementMatchCondition; import com.intellij.psi.codeStyle.arrangement.std.ArrangementSettingsToken; import com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens; import com.intellij.util.containers.ContainerUtil; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.List; import static com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.Section.END_SECTION; import static com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.Section.START_SECTION; /** * @author Svetlana.Zemlyanskaya */ public class ArrangementSectionRule implements Cloneable { @javax.annotation.Nullable private final String myStartComment; @javax.annotation.Nullable private final String myEndComment; private final List<StdArrangementMatchRule> myMatchRules; private ArrangementSectionRule(@javax.annotation.Nullable String start, @javax.annotation.Nullable String end, @Nonnull List<StdArrangementMatchRule> rules) { myStartComment = start; myEndComment = end; myMatchRules = rules; } public List<StdArrangementMatchRule> getMatchRules() { return myMatchRules; } public static ArrangementSectionRule create(@Nonnull StdArrangementMatchRule... rules) { return create(null, null, rules); } public static ArrangementSectionRule create(@javax.annotation.Nullable String start, @javax.annotation.Nullable String end, @Nonnull StdArrangementMatchRule... rules) { return create(start, end, ContainerUtil.newArrayList(rules)); } public static ArrangementSectionRule create(@javax.annotation.Nullable String start, @Nullable String end, @Nonnull List<StdArrangementMatchRule> rules) { final List<StdArrangementMatchRule> matchRules = ContainerUtil.newArrayList(); if (StringUtil.isNotEmpty(start)) { matchRules.add(createSectionRule(start, START_SECTION)); } matchRules.addAll(rules); if (StringUtil.isNotEmpty(end)) { matchRules.add(createSectionRule(end, END_SECTION)); } return new ArrangementSectionRule(start, end, matchRules); } @javax.annotation.Nullable private static StdArrangementMatchRule createSectionRule(@javax.annotation.Nullable String comment, @Nonnull ArrangementSettingsToken token) { if (StringUtil.isEmpty(comment)) { return null; } final ArrangementAtomMatchCondition type = new ArrangementAtomMatchCondition(token); final ArrangementAtomMatchCondition text = new ArrangementAtomMatchCondition(StdArrangementTokens.Regexp.TEXT, comment); final ArrangementMatchCondition condition = ArrangementUtil.combine(type, text); return new StdArrangementMatchRule(new StdArrangementEntryMatcher(condition)); } @javax.annotation.Nullable public String getStartComment() { return myStartComment; } @javax.annotation.Nullable public String getEndComment() { return myEndComment; } @Override public int hashCode() { int factor = 31; int hash = StringUtil.notNullize(myStartComment).hashCode() + factor * StringUtil.notNullize(myEndComment).hashCode(); for (StdArrangementMatchRule rule : myMatchRules) { factor *= factor; hash += rule.hashCode() * factor; } return hash; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final ArrangementSectionRule section = (ArrangementSectionRule)o; if (!StringUtil.equals(myStartComment, section.myStartComment) || !StringUtil.equals(myEndComment, section.myEndComment) || myMatchRules.size() != section.getMatchRules().size()) { return false; } final List<StdArrangementMatchRule> matchRules = section.getMatchRules(); for (int i = 0; i < myMatchRules.size(); i++) { final StdArrangementMatchRule rule1 = myMatchRules.get(i); final StdArrangementMatchRule rule2 = matchRules.get(i); if (!rule1.equals(rule2)) { return false; } } return true; } @Override public String toString() { if (StringUtil.isEmpty(myStartComment)) { return "Section: [" + StringUtil.join(myMatchRules, ",") + "]"; } return "Section " + "(" + myStartComment + (StringUtil.isEmpty(myEndComment) ? "" : ", " + myEndComment) + ")"; } @Override public ArrangementSectionRule clone() { final List<StdArrangementMatchRule> rules = ContainerUtil.newArrayList(); for (StdArrangementMatchRule myMatchRule : myMatchRules) { rules.add(myMatchRule.clone()); } return new ArrangementSectionRule(myStartComment, myEndComment, rules); } }
apache-2.0
krraghavan/mongodb-aggregate-query-support
mongodb-aggregate-query-support-reactive/src/test/java/com/github/krr/mongodb/aggregate/support/repository/reactive/ReactiveTestAggregateRepositoryMarker.java
814
/* * Copyright (c) 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * */ package com.github.krr.mongodb.aggregate.support.repository.reactive; /** * Created by rkolliva * 9/21/16. */ public interface ReactiveTestAggregateRepositoryMarker { }
apache-2.0
ServiceComb/java-chassis
clients/config-kie-client/src/main/java/org/apache/servicecomb/config/kie/client/model/KieAddressManager.java
1445
/* * 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.servicecomb.config.kie.client.model; import java.util.ArrayList; import java.util.List; public class KieAddressManager { private final List<String> addresses; private int index = 0; public KieAddressManager(List<String> addresses) { this.addresses = new ArrayList<>(addresses.size()); this.addresses.addAll(addresses); } public String address() { synchronized (this) { this.index++; if (this.index >= addresses.size()) { this.index = 0; } return addresses.get(index); } } public boolean sslEnabled() { return address().startsWith("https://"); } }
apache-2.0
JNOSQL/diana
diana/diana-document/src/main/java/org/eclipse/jnosql/diana/document/query/DefaultDocumentQueryParams.java
1713
/* * * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana * */ package org.eclipse.jnosql.diana.document.query; import jakarta.nosql.Params; import jakarta.nosql.document.DocumentQuery; import jakarta.nosql.document.DocumentQueryParams; import java.util.Objects; final class DefaultDocumentQueryParams implements DocumentQueryParams { private final DocumentQuery query; private final Params params; DefaultDocumentQueryParams(DocumentQuery query, Params params) { this.query = query; this.params = params; } @Override public DocumentQuery getQuery() { return query; } @Override public Params getParams() { return params; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultDocumentQueryParams that = (DefaultDocumentQueryParams) o; return Objects.equals(query, that.query) && Objects.equals(params, that.params); } @Override public int hashCode() { return Objects.hash(query, params); } }
apache-2.0
sourcepit/target-platform-maven-plugin
src/main/java/org/sourcepit/tpmp/LocalizeTargetPlatformMojo.java
2903
/* * Copyright 2014 Bernd Vogt and others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sourcepit.tpmp; import java.io.File; import java.io.IOException; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.resolver.ArtifactResolutionRequest; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.project.MavenProject; import org.sourcepit.common.utils.lang.Exceptions; import org.sourcepit.common.utils.zip.ZipProcessingRequest; import org.sourcepit.common.utils.zip.ZipProcessor; /** * @author Bernd Vogt <bernd.vogt@sourcepit.org> */ @Mojo(name = "localize", requiresProject = true, aggregator = true) public class LocalizeTargetPlatformMojo extends AbstractTargetPlatformMojo { @Override protected void doExecute() { final MavenProject project = getSession().getCurrentProject(); final File platformDir = downloadTargetPlatformOnDemand(project); updateTargetPlatform(project, platformDir); } protected File downloadTargetPlatformOnDemand(MavenProject project) { final File platformDir = getPlatformDir(project); if (!platformDir.exists() && getResolver().isRelyingOnCachedFiles()) { download(getSession(), project, platformDir.getParentFile()); } return platformDir; } private void download(MavenSession session, MavenProject project, File parentDir) { final Artifact platformArtifact = createPlatformArtifact(project); final ArtifactResolutionRequest request = new ArtifactResolutionRequest(); request.setArtifact(platformArtifact); request.setResolveRoot(true); request.setResolveTransitively(false); request.setLocalRepository(session.getLocalRepository()); request.setRemoteRepositories(project.getRemoteArtifactRepositories()); request.setManagedVersionMap(project.getManagedVersionMap()); request.setOffline(session.isOffline()); repositorySystem.resolve(request); if (platformArtifact.getFile().exists()) { final ZipProcessingRequest unzipRequest = ZipProcessingRequest.newUnzipRequest(platformArtifact.getFile(), parentDir); try { new ZipProcessor().process(unzipRequest); } catch (IOException e) { throw Exceptions.pipe(e); } } } }
apache-2.0
lessthanoptimal/BoofCV
demonstrations/src/main/java/boofcv/demonstrations/shapes/DetectBlackShapeAppBase.java
6480
/* * Copyright (c) 2021, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.demonstrations.shapes; import boofcv.abst.filter.binary.InputToBinary; import boofcv.gui.BoofSwingUtil; import boofcv.gui.DemonstrationBase; import boofcv.gui.binary.VisualizeBinaryData; import boofcv.gui.image.ImageZoomPanel; import boofcv.io.image.ConvertBufferedImage; import boofcv.io.image.UtilImageIO; import boofcv.struct.image.GrayU8; import boofcv.struct.image.ImageBase; import boofcv.struct.image.ImageGray; import boofcv.struct.image.ImageType; import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.util.List; @SuppressWarnings({"NullAway.Init"}) public abstract class DetectBlackShapeAppBase<T extends ImageGray<T>> extends DemonstrationBase implements ThresholdControlPanel.Listener { protected Class<T> imageClass; protected DetectBlackShapePanel controls; protected ImageZoomPanel guiImage; protected InputToBinary<T> inputToBinary; // Lock provided for the BufferedImagesbelow protected final Object bufferedImageLock = new Object(); protected BufferedImage original; protected BufferedImage work; protected GrayU8 binary = new GrayU8(1, 1); // how many input images have been saved to disk protected int saveCounter = 0; protected boolean saveRequested = false; protected DetectBlackShapeAppBase( List<String> examples, Class<T> imageType ) { super(examples, ImageType.single(imageType)); this.imageClass = imageType; JMenuItem menuSaveInput = new JMenuItem("Save Input"); menuSaveInput.addActionListener(e -> requestSaveInputImage()); BoofSwingUtil.setMenuItemKeys(menuSaveInput, KeyEvent.VK_S, KeyEvent.VK_Y); JMenu menu = new JMenu("Data"); menu.setMnemonic(KeyEvent.VK_D); menu.add(menuSaveInput); menuBar.add(menu); } protected void setupGui( ImageZoomPanel guiImage, DetectBlackShapePanel controls ) { this.guiImage = guiImage; this.controls = controls; this.guiImage.autoScaleCenterOnSetImage = false; guiImage.setPreferredSize(new Dimension(800, 800)); add(BorderLayout.WEST, controls); add(BorderLayout.CENTER, guiImage); createDetector(true); guiImage.setListener(scale -> { DetectBlackShapeAppBase.this.controls.setZoom(scale); }); guiImage.getImagePanel().addMouseListener(new MouseAdapter() { @Override public void mousePressed( MouseEvent e ) { if (SwingUtilities.isLeftMouseButton(e)) { if (inputMethod == InputMethod.VIDEO) { streamPaused = !streamPaused; } } } }); } protected abstract void createDetector( boolean initializing ); @Override protected void handleInputChange( int source, InputMethod method, final int width, final int height ) { // reset the scaling and ensure the entire new image is visible BoofSwingUtil.invokeNowOrLater(() -> { double zoom = BoofSwingUtil.selectZoomToShowAll(guiImage, width, height); controls.setImageSize(width, height); controls.setZoom(zoom); milliBinary = 0; guiImage.setScale(zoom); guiImage.updateSize(width, height); guiImage.getHorizontalScrollBar().setValue(0); guiImage.getVerticalScrollBar().setValue(0); }); } double milliBinary = 0; @Override public void processImage( int sourceID, long frameID, final BufferedImage buffered, ImageBase input ) { System.out.flush(); synchronized (bufferedImageLock) { original = ConvertBufferedImage.checkCopy(buffered, original); work = ConvertBufferedImage.checkDeclare(buffered, work); } if (saveRequested) { saveInputImage(); saveRequested = false; } binary.reshape(work.getWidth(), work.getHeight()); final double timeInSeconds; synchronized (this) { long before = System.nanoTime(); inputToBinary.process((T)input, binary); long middle = System.nanoTime(); double a = (middle - before)*1e-6; if (milliBinary == 0) { milliBinary = a; } else { milliBinary = 0.95*milliBinary + 0.05*a; } // System.out.printf(" binary %7.2f ",milliBinary); detectorProcess((T)input, binary); long after = System.nanoTime(); timeInSeconds = (after - before)*1e-9; } SwingUtilities.invokeLater(() -> { controls.setProcessingTimeS(timeInSeconds); viewUpdated(); }); } protected abstract void detectorProcess( T input, GrayU8 binary ); /** * Makes a request that the input image be saved. This request might be carried out immediately * or when then next image is processed. */ public void requestSaveInputImage() { saveRequested = false; switch (inputMethod) { case IMAGE: new Thread(() -> saveInputImage()).start(); break; case VIDEO: case WEBCAM: if (streamPaused) { saveInputImage(); } else { saveRequested = true; } break; default: break; } } protected void saveInputImage() { synchronized (bufferedImageLock) { String fileName = String.format("saved_input%03d.png", saveCounter++); System.out.println("Input image saved to " + fileName); UtilImageIO.saveImage(original, fileName); } } /** * Called when how the data is visualized has changed */ public void viewUpdated() { BufferedImage active; synchronized (bufferedImageLock) { if (controls.selectedView == 0) { active = original; } else if (controls.selectedView == 1) { VisualizeBinaryData.renderBinary(binary, false, work); active = work; work.setRGB(0, 0, work.getRGB(0, 0)); // hack so that Swing knows it's been modified } else { Graphics2D g2 = work.createGraphics(); g2.setColor(Color.BLACK); g2.fillRect(0, 0, work.getWidth(), work.getHeight()); active = work; } } if (active != guiImage.getImage()) guiImage.setImage(active); guiImage.setScale(controls.zoom); guiImage.repaint(); } }
apache-2.0
ahsancse/contactManager
src/com/example/contactmanager/Utility.java
607
package com.example.contactmanager; import java.io.ByteArrayOutputStream; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; public class Utility { // convert from bitmap to byte array public static byte[] getBytes(Bitmap bitmap) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 0, stream); return stream.toByteArray(); } // convert from byte array to bitmap public static Bitmap getPhoto(byte[] image) { return BitmapFactory.decodeByteArray(image, 0, image.length); } }
apache-2.0
tolbertam/java-driver
driver-extras/src/test/java/com/datastax/driver/extras/codecs/guava/OptionalCodecTest.java
8851
/* * Copyright (C) 2012-2017 DataStax Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datastax.driver.extras.codecs.guava; import com.datastax.driver.core.*; import com.datastax.driver.core.querybuilder.BuiltStatement; import com.datastax.driver.core.utils.CassandraVersion; import com.google.common.base.Optional; import com.google.common.collect.Lists; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.math.BigDecimal; import java.util.List; import static com.datastax.driver.core.TypeCodec.*; import static com.datastax.driver.core.querybuilder.QueryBuilder.*; import static org.assertj.core.api.Assertions.assertThat; public class OptionalCodecTest extends CCMTestsSupport { private final OptionalCodec<List<String>> optionalCodec = new OptionalCodec<List<String>>(list(varchar())); private final CodecRegistry registry = new CodecRegistry().register(optionalCodec); private BuiltStatement insertStmt; private BuiltStatement selectStmt; @Override public void onTestContextInitialized() { execute("CREATE TABLE foo (c1 text, c2 text, c3 list<text>, c4 bigint, c5 decimal, PRIMARY KEY (c1, c2))"); } @Override public Cluster.Builder createClusterBuilder() { return Cluster.builder().withCodecRegistry(registry); } @BeforeMethod(groups = "short") public void createBuiltStatements() throws Exception { insertStmt = insertInto("foo").value("c1", bindMarker()).value("c2", bindMarker()).value("c3", bindMarker()); selectStmt = select("c2", "c3").from("foo").where(eq("c1", bindMarker())); } /** * <p> * Validates that if a column is unset, that retrieving the value using {@link OptionalCodec} should return * an {@link Optional#absent()} value. Since CQL Lists can't differentiate between null and empty lists, the * OptionalCodec should be smart enough to map an empty list to absent. * </p> * * @test_category data_types:serialization * @expected_result an absent value. * @jira_ticket JAVA-846 * @since 2.2.0 */ @Test(groups = "short") @CassandraVersion("2.2.0") public void should_map_unset_value_to_absent() { PreparedStatement insertPrep = session().prepare(this.insertStmt); PreparedStatement selectPrep = session().prepare(this.selectStmt); BoundStatement bs = insertPrep.bind(); bs.setString(0, "should_map_unset_value_to_absent"); bs.setString(1, "1"); session().execute(bs); ResultSet results = session().execute(selectPrep.bind("should_map_unset_value_to_absent")); assertThat(results.getAvailableWithoutFetching()).isEqualTo(1); Row row = results.one(); assertThat(row.getString("c2")).isEqualTo("1"); assertThat(row.get("c3", optionalCodec.getJavaType())).isEqualTo(Optional.absent()); } /** * <p> * Validates that if a column is set to {@link Optional#absent()} using {@link OptionalCodec} that it should be * stored as null and that retrieving it should return {@link Optional#absent()} using {@link OptionalCodec}. * </p> * * @test_category data_types:serialization * @expected_result an absent value. * @jira_ticket JAVA-846 * @since 2.2.0 */ @Test(groups = "short") public void should_map_absent_null_value_to_absent() { PreparedStatement insertPrep = session().prepare(this.insertStmt); PreparedStatement selectPrep = session().prepare(this.selectStmt); BoundStatement bs = insertPrep.bind(); bs.setString(0, "should_map_absent_null_value_to_absent"); bs.setString(1, "1"); bs.set(2, Optional.<List<String>>absent(), optionalCodec.getJavaType()); session().execute(bs); ResultSet results = session().execute(selectPrep.bind("should_map_absent_null_value_to_absent")); assertThat(results.getAvailableWithoutFetching()).isEqualTo(1); Row row = results.one(); assertThat(row.getString("c2")).isEqualTo("1"); assertThat(row.getList("c3", String.class)).isEmpty(); assertThat(row.get("c3", optionalCodec.getJavaType())).isEqualTo(Optional.absent()); } /** * <p> * Validates that if a column is set to an {@link Optional} value using {@link OptionalCodec} that it should be * stored as the option's value and that retrieving it should return an {@link Optional} using {@link OptionalCodec} * and its actual value without using it. * </p> * * @test_category data_types:serialization * @expected_result The options value is stored appropriately and is retrievable with and without OptionalCodec. * @jira_ticket JAVA-846 * @since 2.2.0 */ @Test(groups = "short") public void should_map_some_back_to_itself() { PreparedStatement insertPrep = session().prepare(this.insertStmt); PreparedStatement selectPrep = session().prepare(this.selectStmt); List<String> data = Lists.newArrayList("1", "2", "3"); BoundStatement bs = insertPrep.bind(); bs.setString(0, "should_map_some_back_to_itself"); bs.setString(1, "1"); bs.set(2, Optional.of(data), optionalCodec.getJavaType()); session().execute(bs); ResultSet results = session().execute(selectPrep.bind("should_map_some_back_to_itself")); assertThat(results.getAvailableWithoutFetching()).isEqualTo(1); Row row = results.one(); assertThat(row.getString("c2")).isEqualTo("1"); // Ensure data stored correctly. assertThat(row.getList("c3", String.class)).isEqualTo(data); // Ensure data retrievable using Option codec. Optional<List<String>> returnData = row.get("c3", optionalCodec.getJavaType()); assertThat(returnData.isPresent()).isTrue(); assertThat(returnData.get()).isEqualTo(data); } @Test(groups = "short") public void should_map_a_primitive_type_to_absent() { OptionalCodec<Long> optionalLongCodec = new OptionalCodec<Long>(bigint()); cluster().getConfiguration().getCodecRegistry().register(optionalLongCodec); PreparedStatement stmt = session().prepare("insert into foo (c1, c2, c4) values (?,?,?)"); BoundStatement bs = stmt.bind(); bs.setString(0, "should_map_a_primitive_type_to_absent"); bs.setString(1, "1"); bs.set(2, Optional.<Long>absent(), optionalLongCodec.getJavaType()); session().execute(bs); PreparedStatement selectBigint = session().prepare("select c1, c4 from foo where c1=?"); ResultSet results = session().execute(selectBigint.bind("should_map_a_primitive_type_to_absent")); assertThat(results.getAvailableWithoutFetching()).isEqualTo(1); Row row = results.one(); assertThat(row.get("c4", optionalLongCodec.getJavaType())).isEqualTo(Optional.<Long>absent()); assertThat(row.getLong("c4")).isEqualTo(0L); // This will return a 0L since it returns the primitive value. assertThat(row.get("c4", Long.class)).isNull(); } @Test(groups = "short") public void should_map_a_nullable_type_to_absent() { OptionalCodec<BigDecimal> optionalDecimalCodec = new OptionalCodec<BigDecimal>(decimal()); cluster().getConfiguration().getCodecRegistry().register(optionalDecimalCodec); PreparedStatement stmt = session().prepare("insert into foo (c1, c2, c5) values (?,?,?)"); BoundStatement bs = stmt.bind(); bs.setString(0, "should_map_a_nullable_type_to_absent"); bs.setString(1, "1"); bs.set(2, Optional.<BigDecimal>absent(), optionalDecimalCodec.getJavaType()); session().execute(bs); PreparedStatement selectDecimal = session().prepare("select c1, c5 from foo where c1=?"); ResultSet results = session().execute(selectDecimal.bind("should_map_a_nullable_type_to_absent")); assertThat(results.getAvailableWithoutFetching()).isEqualTo(1); Row row = results.one(); assertThat(row.get("c5", optionalDecimalCodec.getJavaType())).isEqualTo(Optional.<BigDecimal>absent()); assertThat(row.getDecimal("c5")).isNull(); // Since BigDecimal is not a primitive it is nullable so expect null. } }
apache-2.0
tadayosi/camel
components/camel-minio/src/main/java/org/apache/camel/component/minio/MinioProducer.java
21780
/* * 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.component.minio; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.List; import java.util.Map; import io.minio.CopyObjectArgs; import io.minio.CopySource; import io.minio.GetObjectArgs; import io.minio.ListObjectsArgs; import io.minio.MinioClient; import io.minio.ObjectWriteResponse; import io.minio.PutObjectArgs; import io.minio.RemoveBucketArgs; import io.minio.RemoveObjectArgs; import io.minio.RemoveObjectsArgs; import io.minio.Result; import io.minio.errors.ErrorResponseException; import io.minio.errors.InsufficientDataException; import io.minio.errors.InternalException; import io.minio.errors.InvalidResponseException; import io.minio.errors.ServerException; import io.minio.errors.XmlParserException; import io.minio.messages.Bucket; import io.minio.messages.Item; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.InvalidPayloadException; import org.apache.camel.Message; import org.apache.camel.WrappedFile; import org.apache.camel.support.DefaultProducer; import org.apache.camel.util.FileUtil; import org.apache.camel.util.IOHelper; import org.apache.camel.util.URISupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.camel.util.ObjectHelper.isEmpty; import static org.apache.camel.util.ObjectHelper.isNotEmpty; /** * A Producer which sends messages to the Minio Simple Storage */ public class MinioProducer extends DefaultProducer { private static final Logger LOG = LoggerFactory.getLogger(MinioProducer.class); private transient String minioProducerToString; public MinioProducer(final Endpoint endpoint) { super(endpoint); } public static Message getMessageForResponse(final Exchange exchange) { return exchange.getMessage(); } @Override public void process(final Exchange exchange) throws Exception { MinioOperations operation = determineOperation(exchange); MinioClient minioClient = getEndpoint().getMinioClient(); if (isEmpty(operation)) { putObject(minioClient, exchange); } else { switch (operation) { case copyObject: copyObject(minioClient, exchange); break; case deleteObject: deleteObject(minioClient, exchange); break; case deleteObjects: deleteObjects(minioClient, exchange); break; case listBuckets: listBuckets(minioClient, exchange); break; case deleteBucket: deleteBucket(minioClient, exchange); break; case listObjects: listObjects(minioClient, exchange); break; case getObject: getObject(minioClient, exchange); break; case getPartialObject: getPartialObject(minioClient, exchange); break; default: throw new IllegalArgumentException("Unsupported operation"); } } } public void putObject(MinioClient minioClient, final Exchange exchange) throws Exception { if (getConfiguration().isPojoRequest()) { PutObjectArgs.Builder payload = exchange.getIn().getMandatoryBody(PutObjectArgs.Builder.class); if (isNotEmpty(payload)) { ObjectWriteResponse putObjectResult = minioClient.putObject(payload.build()); Message message = getMessageForResponse(exchange); message.setHeader(MinioConstants.E_TAG, putObjectResult.etag()); if (isNotEmpty(putObjectResult.versionId())) { message.setHeader(MinioConstants.VERSION_ID, putObjectResult.versionId()); } } } else { final String bucketName = determineBucketName(exchange); final String objectName = determineObjectName(exchange); Map<String, String> objectMetadata = determineMetadata(exchange); Map<String, String> extraHeaders = determineExtraHeaders(exchange); File filePayload = null; Object object = exchange.getIn().getMandatoryBody(); // Need to check if the message body is WrappedFile if (object instanceof WrappedFile) { object = ((WrappedFile<?>) object).getFile(); } InputStream inputStream = null; try { if (object instanceof File) { filePayload = (File) object; inputStream = new FileInputStream(filePayload); } else { inputStream = getInputStreamFromExchange(exchange, objectMetadata); } doPutObject(exchange, bucketName, objectName, objectMetadata, extraHeaders, inputStream); } finally { IOHelper.close(inputStream); } if (getConfiguration().isDeleteAfterWrite() && isNotEmpty(filePayload)) { FileUtil.deleteFile(filePayload); } } } private void doPutObject( Exchange exchange, String bucketName, String objectName, Map<String, String> objectMetadata, Map<String, String> extraHeaders, InputStream inputStream) throws IOException, ErrorResponseException, InsufficientDataException, InternalException, InvalidKeyException, InvalidResponseException, NoSuchAlgorithmException, ServerException, XmlParserException { PutObjectArgs.Builder putObjectRequest = PutObjectArgs.builder() .stream(inputStream, inputStream.available(), -1) .bucket(bucketName) .object(objectName) .userMetadata(objectMetadata); if (!extraHeaders.isEmpty()) { putObjectRequest.extraHeaders(extraHeaders); } LOG.trace("Put object from exchange..."); ObjectWriteResponse putObjectResult = getEndpoint().getMinioClient().putObject(putObjectRequest.build()); LOG.trace("Received result..."); Message message = getMessageForResponse(exchange); message.setHeader(MinioConstants.E_TAG, putObjectResult.etag()); if (isNotEmpty(putObjectResult.versionId())) { message.setHeader(MinioConstants.VERSION_ID, putObjectResult.versionId()); } } private InputStream getInputStreamFromExchange(Exchange exchange, Map<String, String> objectMetadata) throws InvalidPayloadException, IOException { InputStream inputStream = exchange.getIn().getMandatoryBody(InputStream.class); if (objectMetadata.containsKey(Exchange.CONTENT_LENGTH)) { if (objectMetadata.get("Content-Length").equals("0") && isEmpty(exchange.getProperty(Exchange.CONTENT_LENGTH))) { LOG.debug( "The content length is not defined. It needs to be determined by reading the data into memory"); ByteArrayOutputStream baos = determineLengthInputStream(inputStream); objectMetadata.put("Content-Length", String.valueOf(baos.size())); inputStream = new ByteArrayInputStream(baos.toByteArray()); } else { if (isNotEmpty(exchange.getProperty(Exchange.CONTENT_LENGTH))) { objectMetadata.put("Content-Length", exchange.getProperty(Exchange.CONTENT_LENGTH, String.class)); } } } return inputStream; } private Map<String, String> determineExtraHeaders(Exchange exchange) { Map<String, String> extraHeaders = new HashMap<>(); String storageClass = determineStorageClass(exchange); if (isNotEmpty(storageClass)) { extraHeaders.put("X-Amz-Storage-Class", storageClass); } String cannedAcl = exchange.getIn().getHeader(MinioConstants.CANNED_ACL, String.class); if (isNotEmpty(cannedAcl)) { extraHeaders.put("x-amz-acl", cannedAcl); } return extraHeaders; } private void copyObject(MinioClient minioClient, Exchange exchange) throws Exception { if (getConfiguration().isPojoRequest()) { CopyObjectArgs.Builder payload = exchange.getIn().getMandatoryBody(CopyObjectArgs.Builder.class); if (isNotEmpty(payload)) { ObjectWriteResponse result = minioClient.copyObject(payload.build()); Message message = getMessageForResponse(exchange); message.setBody(result); } } else { final String bucketName = determineBucketName(exchange); final String sourceKey = determineObjectName(exchange); final String destinationKey = exchange.getIn().getHeader(MinioConstants.DESTINATION_OBJECT_NAME, String.class); final String destinationBucketName = exchange.getIn().getHeader(MinioConstants.DESTINATION_BUCKET_NAME, String.class); if (isEmpty(destinationBucketName)) { throw new IllegalArgumentException("Bucket Name Destination must be specified for copyObject Operation"); } if (isEmpty(destinationKey)) { throw new IllegalArgumentException("Destination Key must be specified for copyObject Operation"); } CopySource.Builder copySourceBuilder = CopySource.builder() .bucket(bucketName) .object(sourceKey); CopyObjectArgs.Builder copyObjectRequest = CopyObjectArgs.builder() .bucket(destinationBucketName) .object(destinationKey) .source(copySourceBuilder.build()); ObjectWriteResponse copyObjectResult = minioClient.copyObject(copyObjectRequest.build()); Message message = getMessageForResponse(exchange); if (isNotEmpty(copyObjectResult.versionId())) { message.setHeader(MinioConstants.VERSION_ID, copyObjectResult.versionId()); } } } private void deleteObject(MinioClient minioClient, Exchange exchange) throws Exception { if (getConfiguration().isPojoRequest()) { RemoveObjectArgs.Builder payload = exchange.getIn().getMandatoryBody(RemoveObjectArgs.Builder.class); if (isNotEmpty(payload)) { minioClient.removeObject(payload.build()); Message message = getMessageForResponse(exchange); message.setBody(true); } } else { final String bucketName = determineBucketName(exchange); final String sourceKey = determineObjectName(exchange); minioClient.removeObject(RemoveObjectArgs.builder() .bucket(bucketName) .object(sourceKey).build()); Message message = getMessageForResponse(exchange); message.setBody(true); } } private void deleteObjects(MinioClient minioClient, Exchange exchange) throws Exception { if (getConfiguration().isPojoRequest()) { RemoveObjectsArgs.Builder payload = exchange.getIn().getMandatoryBody(RemoveObjectsArgs.Builder.class); if (isNotEmpty(payload)) { minioClient.removeObjects(payload.build()); Message message = getMessageForResponse(exchange); message.setBody(true); } } else { throw new IllegalArgumentException("Cannot delete multiple objects without a POJO request"); } } private void listBuckets(MinioClient minioClient, Exchange exchange) throws Exception { List<Bucket> bucketsList = minioClient.listBuckets(); Message message = getMessageForResponse(exchange); //returns iterator of bucketList message.setBody(bucketsList.iterator()); } private void deleteBucket(MinioClient minioClient, Exchange exchange) throws Exception { final String bucketName = determineBucketName(exchange); if (getConfiguration().isPojoRequest()) { RemoveBucketArgs.Builder payload = exchange.getIn().getMandatoryBody(RemoveBucketArgs.Builder.class); if (isNotEmpty(payload)) { minioClient.removeBucket(payload.build()); Message message = getMessageForResponse(exchange); message.setBody("ok"); } } else { minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build()); Message message = getMessageForResponse(exchange); message.setBody("ok"); } } private void getObject(MinioClient minioClient, Exchange exchange) throws Exception { if (getConfiguration().isPojoRequest()) { GetObjectArgs.Builder payload = exchange.getIn().getMandatoryBody(GetObjectArgs.Builder.class); if (isNotEmpty(payload)) { InputStream respond = minioClient.getObject(payload.build()); Message message = getMessageForResponse(exchange); message.setBody(respond); } } else { final String bucketName = determineBucketName(exchange); final String sourceKey = determineObjectName(exchange); InputStream respond = minioClient.getObject(GetObjectArgs.builder() .bucket(bucketName) .object(sourceKey) .build()); Message message = getMessageForResponse(exchange); message.setBody(respond); } } private void getPartialObject(MinioClient minioClient, Exchange exchange) throws Exception { if (getConfiguration().isPojoRequest()) { GetObjectArgs.Builder payload = exchange.getIn().getMandatoryBody(GetObjectArgs.Builder.class); if (isNotEmpty(payload)) { InputStream respond = minioClient.getObject(payload.build()); Message message = getMessageForResponse(exchange); message.setBody(respond); } } else { final String bucketName = determineBucketName(exchange); final String sourceKey = determineObjectName(exchange); final String offset = exchange.getIn().getHeader(MinioConstants.OFFSET, String.class); final String length = exchange.getIn().getHeader(MinioConstants.LENGTH, String.class); if (isEmpty(offset) || isEmpty(length)) { throw new IllegalArgumentException( "A Offset and length header must be configured to perform a partial get operation."); } InputStream respond = minioClient.getObject(GetObjectArgs.builder() .bucket(bucketName) .object(sourceKey) .offset(Long.parseLong(offset)) .length(Long.parseLong(length)) .build()); Message message = getMessageForResponse(exchange); message.setBody(respond); } } private void listObjects(MinioClient minioClient, Exchange exchange) throws InvalidPayloadException { if (getConfiguration().isPojoRequest()) { ListObjectsArgs.Builder payload = exchange.getIn().getMandatoryBody(ListObjectsArgs.Builder.class); if (isNotEmpty(payload)) { Iterable<Result<Item>> objectList = minioClient.listObjects(payload.build()); Message message = getMessageForResponse(exchange); message.setBody(objectList); } } else { final String bucketName = determineBucketName(exchange); Iterable<Result<Item>> objectList = minioClient.listObjects(ListObjectsArgs.builder() .bucket(bucketName) .build()); Message message = getMessageForResponse(exchange); message.setBody(objectList); } } private MinioOperations determineOperation(Exchange exchange) { MinioOperations operation = exchange.getIn().getHeader(MinioConstants.MINIO_OPERATION, MinioOperations.class); if (isEmpty(operation)) { operation = getConfiguration().getOperation(); } return operation; } private Map<String, String> determineMetadata(final Exchange exchange) { Map<String, String> objectMetadata = new HashMap<>(); Long contentLength = exchange.getIn().getHeader(MinioConstants.CONTENT_LENGTH, Long.class); if (isNotEmpty(contentLength)) { objectMetadata.put("Content-Length", String.valueOf(contentLength)); } String contentType = exchange.getIn().getHeader(MinioConstants.CONTENT_TYPE, String.class); if (isNotEmpty(contentType)) { objectMetadata.put("Content-Type", contentType); } String cacheControl = exchange.getIn().getHeader(MinioConstants.CACHE_CONTROL, String.class); if (isNotEmpty(cacheControl)) { objectMetadata.put("Cache-Control", cacheControl); } String contentDisposition = exchange.getIn().getHeader(MinioConstants.CONTENT_DISPOSITION, String.class); if (isNotEmpty(contentDisposition)) { objectMetadata.put("Content-Disposition", contentDisposition); } String contentEncoding = exchange.getIn().getHeader(MinioConstants.CONTENT_ENCODING, String.class); if (isNotEmpty(contentEncoding)) { objectMetadata.put("Content-Encoding", contentEncoding); } String contentMD5 = exchange.getIn().getHeader(MinioConstants.CONTENT_MD5, String.class); if (isNotEmpty(contentMD5)) { objectMetadata.put("Content-Md5", contentMD5); } return objectMetadata; } /** * Reads the bucket name from the header of the given exchange. If not provided, it's read from the endpoint * configuration. * * @param exchange The exchange to read the header from. * @return The bucket name. * @throws IllegalArgumentException if the header could not be determined. */ private String determineBucketName(final Exchange exchange) { String bucketName = exchange.getIn().getHeader(MinioConstants.BUCKET_NAME, String.class); if (isEmpty(bucketName)) { if (isNotEmpty(getConfiguration().getBucketName())) { bucketName = getConfiguration().getBucketName(); LOG.trace("Minio Bucket name header is missing, using default one {}", bucketName); } else { throw new IllegalArgumentException("Minio Bucket name header is missing or not configured."); } } return bucketName; } private String determineObjectName(final Exchange exchange) { String objectName = exchange.getIn().getHeader(MinioConstants.OBJECT_NAME, String.class); if (isEmpty(objectName)) { objectName = getConfiguration().getKeyName(); } if (isEmpty(objectName)) { throw new IllegalArgumentException("Minio Key header is missing."); } return objectName; } private String determineStorageClass(final Exchange exchange) { String storageClass = exchange.getIn().getHeader(MinioConstants.STORAGE_CLASS, String.class); if (isEmpty(storageClass)) { storageClass = getConfiguration().getStorageClass(); } return storageClass; } private ByteArrayOutputStream determineLengthInputStream(InputStream inputStream) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] bytes = new byte[MinioConstants.BYTE_ARRAY_LENGTH]; int count; while ((count = inputStream.read(bytes)) > 0) { out.write(bytes, 0, count); } return out; } protected MinioConfiguration getConfiguration() { return getEndpoint().getConfiguration(); } @Override public String toString() { if (isEmpty(minioProducerToString)) { minioProducerToString = "MinioProducer[" + URISupport.sanitizeUri(getEndpoint().getEndpointUri()) + "]"; } return minioProducerToString; } @Override public MinioEndpoint getEndpoint() { return (MinioEndpoint) super.getEndpoint(); } }
apache-2.0
dagnir/aws-sdk-java
aws-java-sdk-rds/src/main/java/com/amazonaws/services/rds/model/OptionGroupNotFoundException.java
1217
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.rds.model; import javax.annotation.Generated; /** * <p> * The specified option group could not be found. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class OptionGroupNotFoundException extends com.amazonaws.services.rds.model.AmazonRDSException { private static final long serialVersionUID = 1L; /** * Constructs a new OptionGroupNotFoundException with the specified error message. * * @param message * Describes the error encountered. */ public OptionGroupNotFoundException(String message) { super(message); } }
apache-2.0
camachohoracio/Armadillo.Core
Communication/src/main/java/Armadillo/Communication/zmq/zmq/Push.java
2096
/* Copyright (c) 2009-2011 250bpm s.r.o. Copyright (c) 2007-2010 iMatix Corporation Copyright (c) 2007-2011 Other contributors as noted in the AUTHORS file This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package Armadillo.Communication.zmq.zmq; public class Push extends SocketBase { public static class PushSession extends SessionBase { public PushSession(IOThread io_thread_, boolean connect_, SocketBase socket_, final Options options_, final Address addr_) { super(io_thread_, connect_, socket_, options_, addr_); } } // Load balancer managing the outbound pipes. private final LB lb; public Push(Ctx parent_, int tid_, int sid_) { super(parent_, tid_, sid_); options.type = ZMQ.ZMQ_PUSH; lb = new LB(); } @Override protected void xattach_pipe(Pipe pipe_, boolean icanhasall_) { assert (pipe_ != null); lb.attach (pipe_); } @Override protected void xwrite_activated (Pipe pipe_) { lb.activated (pipe_); } @Override protected void xterminated(Pipe pipe_) { lb.terminated (pipe_); } @Override public boolean xsend(Msg msg_) { return lb.send(msg_, errno); } @Override protected boolean xhas_out () { return lb.has_out (); } }
apache-2.0
ilya-moskovtsev/imoskovtsev
intern/chapter_003_collections_light/src/main/java/ru/job4j/sortdepartments/SortedDepartments.java
1263
package ru.job4j.sortdepartments; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.TreeSet; import java.util.stream.IntStream; public class SortedDepartments { private TreeSet<String> departmentNames = new TreeSet<>(); public void addDepartment(String departmentName) { List<String> subdivisions = Arrays.asList(departmentName.split("\\\\")); IntStream.range(0, subdivisions.size()).forEach(i -> this.departmentNames.add(String.join("\\", subdivisions.subList(0, i + 1)))); } public List<Department> getAscendingDepartments() { List<Department> departments = new ArrayList<>(); this.departmentNames.forEach(department -> departments.add(new Department(department))); AscendingComparator comparator = new AscendingComparator(); departments.sort(comparator); return departments; } public List<Department> getDescendingDepartments() { List<Department> departments = new ArrayList<>(); this.departmentNames.forEach(department -> departments.add(new Department(department))); DescendingComparator comparator = new DescendingComparator(); departments.sort(comparator); return departments; } }
apache-2.0
aedelmann/jiva
jiva-workflow/src/main/java/de/aedelmann/jiva/workflow/internal/script/TimeLiteralExpression.java
586
package de.aedelmann.jiva.workflow.internal.script; import de.aedelmann.jiva.workflow.extensionpoints.WorkflowContext; import de.aedelmann.jiva.workflow.script.Script; import java.util.Date; /** * @author Alexander Edelmann */ public class TimeLiteralExpression implements Script<Date> { private static final String LANG_KEY = "literal"; public TimeLiteralExpression(String value) { } @Override public String getLanguage() { return LANG_KEY; } @Override public Date evaluate(WorkflowContext context) { return new Date(); } }
apache-2.0
dennisxu1014/dennisxu-sample-android
core/src/main/java/com/dennisxu/lib/core/exception/ApiException.java
802
package com.dennisxu.lib.core.exception; /** * 处理服务器返回的错误信息 * * @author: xuyang * @date: 2014-8-24 上午10:24:50 */ public class ApiException extends Exception { private static final long serialVersionUID = 6501425440406106625L; public APiErrorMessage APiErrorMessage; public ApiException() { super(); } public ApiException(String detailMessage) { super(detailMessage); } public ApiException(APiErrorMessage APiErrorMessage) { super(APiErrorMessage.errorMsg); this.APiErrorMessage = APiErrorMessage; } public ApiException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); } public ApiException(Throwable throwable) { super(throwable); } }
apache-2.0
jasobrown/barker
src/main/java/jmh/barker/CWestinForLoop.java
1791
package jmh.barker; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; /** * benchmark, in java, of Chris Westin's for loop optimization in c: * https://www.bookofbrilliantthings.com/blog/revisiting-some-old-for-loop-lore */ @State(Scope.Thread) @Warmup(iterations = 4, time = 1, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 8, time = 2, timeUnit = TimeUnit.SECONDS) @Fork(4) @OutputTimeUnit(TimeUnit.NANOSECONDS) @BenchmarkMode(Mode.SampleTime) public class CWestinForLoop { private static final int MAX = 100000000; private static final int MAX_BUF = 1 << 20; private final byte[] buf; public CWestinForLoop() { buf = new byte[MAX_BUF]; for (int i = 0; i < MAX_BUF; i++) buf[i] = (byte)i; } @Benchmark public int standardLoop() { int x = 0; for (int i = 0; i < MAX; i++) x = i; return x; } @Benchmark public int westinLoop() { int x = 0; for (int i = MAX; i > 0; --i) x = i; return x; } @Benchmark public int standardArrayLoop() { int x = 0; for (int i = 0; i < MAX_BUF; i++) x = buf[i]; return x; } @Benchmark public int westinArrayLoop() { int x = 0; for (int i = MAX_BUF - 1; i > 0; --i) x = buf[i]; return x; } }
apache-2.0
oehme/analysing-gradle-performance
my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p253/Production5063.java
1891
package org.gradle.test.performance.mediummonolithicjavaproject.p253; public class Production5063 { private String property0; public String getProperty0() { return property0; } public void setProperty0(String value) { property0 = value; } private String property1; public String getProperty1() { return property1; } public void setProperty1(String value) { property1 = value; } private String property2; public String getProperty2() { return property2; } public void setProperty2(String value) { property2 = value; } private String property3; public String getProperty3() { return property3; } public void setProperty3(String value) { property3 = value; } private String property4; public String getProperty4() { return property4; } public void setProperty4(String value) { property4 = value; } private String property5; public String getProperty5() { return property5; } public void setProperty5(String value) { property5 = value; } private String property6; public String getProperty6() { return property6; } public void setProperty6(String value) { property6 = value; } private String property7; public String getProperty7() { return property7; } public void setProperty7(String value) { property7 = value; } private String property8; public String getProperty8() { return property8; } public void setProperty8(String value) { property8 = value; } private String property9; public String getProperty9() { return property9; } public void setProperty9(String value) { property9 = value; } }
apache-2.0
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/iothub/model/Operation.java
839
/* * Copyright 2016 Baidu, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.baidubce.services.iothub.model; /** * Represent the kind of operation. */ public enum Operation { PUBLISH("PUBLISH"), SUBSCRIBE("PUBLISH"); private String name; private Operation(String name) { this.name = name; } }
apache-2.0
dermotte/CountingGame
html/src/at/juggle/games/counting/client/HtmlLauncher.java
1046
/* * This project and its source code is licensed under * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * Copyright (c) 2017 Mathias Lux, mathias@juggle.at */ package at.juggle.games.counting.client; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.backends.gwt.GwtApplication; import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration; import at.juggle.games.counting.CountingGame; import at.juggle.games.counting.SpeechInterface; public class HtmlLauncher extends GwtApplication { @Override public GwtApplicationConfiguration getConfig () { return new GwtApplicationConfiguration(480, 320); } @Override public ApplicationListener createApplicationListener () { return new CountingGame(new SpeechInterface() { @Override public void speakOut(String text) { return; } }); } }
apache-2.0
shayhatsor/zookeeper
src/java/main/org/apache/zookeeper/ClientCnxn.java
61199
/** * 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.zookeeper; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.lang.Thread.UncaughtExceptionHandler; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingQueue; import javax.security.auth.login.LoginException; import javax.security.sasl.SaslException; import org.apache.jute.BinaryInputArchive; import org.apache.jute.BinaryOutputArchive; import org.apache.jute.Record; import org.apache.zookeeper.AsyncCallback.ACLCallback; import org.apache.zookeeper.AsyncCallback.Children2Callback; import org.apache.zookeeper.AsyncCallback.ChildrenCallback; import org.apache.zookeeper.AsyncCallback.DataCallback; import org.apache.zookeeper.AsyncCallback.MultiCallback; import org.apache.zookeeper.AsyncCallback.StatCallback; import org.apache.zookeeper.AsyncCallback.StringCallback; import org.apache.zookeeper.AsyncCallback.VoidCallback; import org.apache.zookeeper.OpResult.ErrorResult; import org.apache.zookeeper.Watcher.Event; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.Watcher.Event.KeeperState; import org.apache.zookeeper.ZooDefs.OpCode; import org.apache.zookeeper.ZooKeeper.States; import org.apache.zookeeper.ZooKeeper.WatchRegistration; import org.apache.zookeeper.client.HostProvider; import org.apache.zookeeper.client.ZooKeeperSaslClient; import org.apache.zookeeper.common.Time; import org.apache.zookeeper.proto.AuthPacket; import org.apache.zookeeper.proto.ConnectRequest; import org.apache.zookeeper.proto.CreateResponse; import org.apache.zookeeper.proto.ExistsResponse; import org.apache.zookeeper.proto.GetACLResponse; import org.apache.zookeeper.proto.GetChildren2Response; import org.apache.zookeeper.proto.GetChildrenResponse; import org.apache.zookeeper.proto.GetDataResponse; import org.apache.zookeeper.proto.GetSASLRequest; import org.apache.zookeeper.proto.ReplyHeader; import org.apache.zookeeper.proto.RequestHeader; import org.apache.zookeeper.proto.SetACLResponse; import org.apache.zookeeper.proto.SetDataResponse; import org.apache.zookeeper.proto.SetWatches; import org.apache.zookeeper.proto.WatcherEvent; import org.apache.zookeeper.server.ByteBufferInputStream; import org.apache.zookeeper.server.ZooKeeperThread; import org.apache.zookeeper.server.ZooTrace; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class manages the socket i/o for the client. ClientCnxn maintains a list * of available servers to connect to and "transparently" switches servers it is * connected to as needed. * */ public class ClientCnxn { private static final Logger LOG = LoggerFactory.getLogger(ClientCnxn.class); private static final String ZK_SASL_CLIENT_USERNAME = "zookeeper.sasl.client.username"; /* ZOOKEEPER-706: If a session has a large number of watches set then * attempting to re-establish those watches after a connection loss may * fail due to the SetWatches request exceeding the server's configured * jute.maxBuffer value. To avoid this we instead split the watch * re-establishement across multiple SetWatches calls. This constant * controls the size of each call. It is set to 128kB to be conservative * with respect to the server's 1MB default for jute.maxBuffer. */ private static final int SET_WATCHES_MAX_LENGTH = 128 * 1024; /** This controls whether automatic watch resetting is enabled. * Clients automatically reset watches during session reconnect, this * option allows the client to turn off this behavior by setting * the environment variable "zookeeper.disableAutoWatchReset" to "true" */ private static boolean disableAutoWatchReset; static { // this var should not be public, but otw there is no easy way // to test disableAutoWatchReset = Boolean.getBoolean("zookeeper.disableAutoWatchReset"); if (LOG.isDebugEnabled()) { LOG.debug("zookeeper.disableAutoWatchReset is " + disableAutoWatchReset); } } static class AuthData { AuthData(String scheme, byte data[]) { this.scheme = scheme; this.data = data; } String scheme; byte data[]; } private final CopyOnWriteArraySet<AuthData> authInfo = new CopyOnWriteArraySet<AuthData>(); /** * These are the packets that have been sent and are waiting for a response. */ private final LinkedList<Packet> pendingQueue = new LinkedList<Packet>(); /** * These are the packets that need to be sent. */ private final LinkedList<Packet> outgoingQueue = new LinkedList<Packet>(); private int connectTimeout; /** * The timeout in ms the client negotiated with the server. This is the * "real" timeout, not the timeout request by the client (which may have * been increased/decreased by the server which applies bounds to this * value. */ private volatile int negotiatedSessionTimeout; private int readTimeout; private final int sessionTimeout; private final ZooKeeper zooKeeper; private final ClientWatchManager watcher; private long sessionId; private byte sessionPasswd[] = new byte[16]; /** * If true, the connection is allowed to go to r-o mode. This field's value * is sent, besides other data, during session creation handshake. If the * server on the other side of the wire is partitioned it'll accept * read-only clients only. */ private boolean readOnly; final String chrootPath; final SendThread sendThread; final EventThread eventThread; /** * Set to true when close is called. Latches the connection such that we * don't attempt to re-connect to the server if in the middle of closing the * connection (client sends session disconnect to server as part of close * operation) */ private volatile boolean closing = false; /** * A set of ZooKeeper hosts this client could connect to. */ private final HostProvider hostProvider; /** * Is set to true when a connection to a r/w server is established for the * first time; never changed afterwards. * <p> * Is used to handle situations when client without sessionId connects to a * read-only server. Such client receives "fake" sessionId from read-only * server, but this sessionId is invalid for other servers. So when such * client finds a r/w server, it sends 0 instead of fake sessionId during * connection handshake and establishes new, valid session. * <p> * If this field is false (which implies we haven't seen r/w server before) * then non-zero sessionId is fake, otherwise it is valid. */ volatile boolean seenRwServerBefore = false; public ZooKeeperSaslClient zooKeeperSaslClient; public long getSessionId() { return sessionId; } public byte[] getSessionPasswd() { return sessionPasswd; } public int getSessionTimeout() { return negotiatedSessionTimeout; } @Override public String toString() { StringBuilder sb = new StringBuilder(); SocketAddress local = sendThread.getClientCnxnSocket().getLocalSocketAddress(); SocketAddress remote = sendThread.getClientCnxnSocket().getRemoteSocketAddress(); sb .append("sessionid:0x").append(Long.toHexString(getSessionId())) .append(" local:").append(local) .append(" remoteserver:").append(remote) .append(" lastZxid:").append(lastZxid) .append(" xid:").append(xid) .append(" sent:").append(sendThread.getClientCnxnSocket().getSentCount()) .append(" recv:").append(sendThread.getClientCnxnSocket().getRecvCount()) .append(" queuedpkts:").append(outgoingQueue.size()) .append(" pendingresp:").append(pendingQueue.size()) .append(" queuedevents:").append(eventThread.waitingEvents.size()); return sb.toString(); } /** * This class allows us to pass the headers and the relevant records around. */ static class Packet { RequestHeader requestHeader; ReplyHeader replyHeader; Record request; Record response; ByteBuffer bb; /** Client's view of the path (may differ due to chroot) **/ String clientPath; /** Servers's view of the path (may differ due to chroot) **/ String serverPath; boolean finished; AsyncCallback cb; Object ctx; WatchRegistration watchRegistration; public boolean readOnly; /** Convenience ctor */ Packet(RequestHeader requestHeader, ReplyHeader replyHeader, Record request, Record response, WatchRegistration watchRegistration) { this(requestHeader, replyHeader, request, response, watchRegistration, false); } Packet(RequestHeader requestHeader, ReplyHeader replyHeader, Record request, Record response, WatchRegistration watchRegistration, boolean readOnly) { this.requestHeader = requestHeader; this.replyHeader = replyHeader; this.request = request; this.response = response; this.readOnly = readOnly; this.watchRegistration = watchRegistration; } public void createBB() { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos); boa.writeInt(-1, "len"); // We'll fill this in later if (requestHeader != null) { requestHeader.serialize(boa, "header"); } if (request instanceof ConnectRequest) { request.serialize(boa, "connect"); // append "am-I-allowed-to-be-readonly" flag boa.writeBool(readOnly, "readOnly"); } else if (request != null) { request.serialize(boa, "request"); } baos.close(); this.bb = ByteBuffer.wrap(baos.toByteArray()); this.bb.putInt(this.bb.capacity() - 4); this.bb.rewind(); } catch (IOException e) { LOG.warn("Ignoring unexpected exception", e); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("clientPath:" + clientPath); sb.append(" serverPath:" + serverPath); sb.append(" finished:" + finished); sb.append(" header:: " + requestHeader); sb.append(" replyHeader:: " + replyHeader); sb.append(" request:: " + request); sb.append(" response:: " + response); // jute toString is horrible, remove unnecessary newlines return sb.toString().replaceAll("\r*\n+", " "); } } /** * Creates a connection object. The actual network connect doesn't get * established until needed. The start() instance method must be called * subsequent to construction. * * @param chrootPath - the chroot of this client. Should be removed from this Class in ZOOKEEPER-838 * @param hostProvider * the list of ZooKeeper servers to connect to * @param sessionTimeout * the timeout for connections. * @param zooKeeper * the zookeeper object that this connection is related to. * @param watcher watcher for this connection * @param clientCnxnSocket * the socket implementation used (e.g. NIO/Netty) * @param canBeReadOnly * whether the connection is allowed to go to read-only * mode in case of partitioning * @throws IOException */ public ClientCnxn(String chrootPath, HostProvider hostProvider, int sessionTimeout, ZooKeeper zooKeeper, ClientWatchManager watcher, ClientCnxnSocket clientCnxnSocket, boolean canBeReadOnly) throws IOException { this(chrootPath, hostProvider, sessionTimeout, zooKeeper, watcher, clientCnxnSocket, 0, new byte[16], canBeReadOnly); } /** * Creates a connection object. The actual network connect doesn't get * established until needed. The start() instance method must be called * subsequent to construction. * * @param chrootPath - the chroot of this client. Should be removed from this Class in ZOOKEEPER-838 * @param hostProvider * the list of ZooKeeper servers to connect to * @param sessionTimeout * the timeout for connections. * @param zooKeeper * the zookeeper object that this connection is related to. * @param watcher watcher for this connection * @param clientCnxnSocket * the socket implementation used (e.g. NIO/Netty) * @param sessionId session id if re-establishing session * @param sessionPasswd session passwd if re-establishing session * @param canBeReadOnly * whether the connection is allowed to go to read-only * mode in case of partitioning * @throws IOException */ public ClientCnxn(String chrootPath, HostProvider hostProvider, int sessionTimeout, ZooKeeper zooKeeper, ClientWatchManager watcher, ClientCnxnSocket clientCnxnSocket, long sessionId, byte[] sessionPasswd, boolean canBeReadOnly) { this.zooKeeper = zooKeeper; this.watcher = watcher; this.sessionId = sessionId; this.sessionPasswd = sessionPasswd; this.sessionTimeout = sessionTimeout; this.hostProvider = hostProvider; this.chrootPath = chrootPath; connectTimeout = sessionTimeout / hostProvider.size(); readTimeout = sessionTimeout * 2 / 3; readOnly = canBeReadOnly; sendThread = new SendThread(clientCnxnSocket); eventThread = new EventThread(); } /** * tests use this to check on reset of watches * @return if the auto reset of watches are disabled */ public static boolean getDisableAutoResetWatch() { return disableAutoWatchReset; } /** * tests use this to set the auto reset * @param b the value to set disable watches to */ public static void setDisableAutoResetWatch(boolean b) { disableAutoWatchReset = b; } public void start() { sendThread.start(); eventThread.start(); } private Object eventOfDeath = new Object(); private static class WatcherSetEventPair { private final Set<Watcher> watchers; private final WatchedEvent event; public WatcherSetEventPair(Set<Watcher> watchers, WatchedEvent event) { this.watchers = watchers; this.event = event; } } /** * Guard against creating "-EventThread-EventThread-EventThread-..." thread * names when ZooKeeper object is being created from within a watcher. * See ZOOKEEPER-795 for details. */ private static String makeThreadName(String suffix) { String name = Thread.currentThread().getName(). replaceAll("-EventThread", ""); return name + suffix; } class EventThread extends ZooKeeperThread { private final LinkedBlockingQueue<Object> waitingEvents = new LinkedBlockingQueue<Object>(); /** This is really the queued session state until the event * thread actually processes the event and hands it to the watcher. * But for all intents and purposes this is the state. */ private volatile KeeperState sessionState = KeeperState.Disconnected; private volatile boolean wasKilled = false; private volatile boolean isRunning = false; EventThread() { super(makeThreadName("-EventThread")); setDaemon(true); } public void queueEvent(WatchedEvent event) { if (event.getType() == EventType.None && sessionState == event.getState()) { return; } sessionState = event.getState(); // materialize the watchers based on the event WatcherSetEventPair pair = new WatcherSetEventPair( watcher.materialize(event.getState(), event.getType(), event.getPath()), event); // queue the pair (watch set & event) for later processing waitingEvents.add(pair); } public void queuePacket(Packet packet) { if (wasKilled) { synchronized (waitingEvents) { if (isRunning) waitingEvents.add(packet); else processEvent(packet); } } else { waitingEvents.add(packet); } } public void queueEventOfDeath() { waitingEvents.add(eventOfDeath); } @Override public void run() { try { isRunning = true; while (true) { Object event = waitingEvents.take(); if (event == eventOfDeath) { wasKilled = true; } else { processEvent(event); } if (wasKilled) synchronized (waitingEvents) { if (waitingEvents.isEmpty()) { isRunning = false; break; } } } } catch (InterruptedException e) { LOG.error("Event thread exiting due to interruption", e); } LOG.info("EventThread shut down for session: 0x{}", Long.toHexString(getSessionId())); } private void processEvent(Object event) { try { if (event instanceof WatcherSetEventPair) { // each watcher will process the event WatcherSetEventPair pair = (WatcherSetEventPair) event; for (Watcher watcher : pair.watchers) { try { watcher.process(pair.event); } catch (Throwable t) { LOG.error("Error while calling watcher ", t); } } } else { Packet p = (Packet) event; int rc = 0; String clientPath = p.clientPath; if (p.replyHeader.getErr() != 0) { rc = p.replyHeader.getErr(); } if (p.cb == null) { LOG.warn("Somehow a null cb got to EventThread!"); } else if (p.response instanceof ExistsResponse || p.response instanceof SetDataResponse || p.response instanceof SetACLResponse) { StatCallback cb = (StatCallback) p.cb; if (rc == 0) { if (p.response instanceof ExistsResponse) { cb.processResult(rc, clientPath, p.ctx, ((ExistsResponse) p.response) .getStat()); } else if (p.response instanceof SetDataResponse) { cb.processResult(rc, clientPath, p.ctx, ((SetDataResponse) p.response) .getStat()); } else if (p.response instanceof SetACLResponse) { cb.processResult(rc, clientPath, p.ctx, ((SetACLResponse) p.response) .getStat()); } } else { cb.processResult(rc, clientPath, p.ctx, null); } } else if (p.response instanceof GetDataResponse) { DataCallback cb = (DataCallback) p.cb; GetDataResponse rsp = (GetDataResponse) p.response; if (rc == 0) { cb.processResult(rc, clientPath, p.ctx, rsp .getData(), rsp.getStat()); } else { cb.processResult(rc, clientPath, p.ctx, null, null); } } else if (p.response instanceof GetACLResponse) { ACLCallback cb = (ACLCallback) p.cb; GetACLResponse rsp = (GetACLResponse) p.response; if (rc == 0) { cb.processResult(rc, clientPath, p.ctx, rsp .getAcl(), rsp.getStat()); } else { cb.processResult(rc, clientPath, p.ctx, null, null); } } else if (p.response instanceof GetChildrenResponse) { ChildrenCallback cb = (ChildrenCallback) p.cb; GetChildrenResponse rsp = (GetChildrenResponse) p.response; if (rc == 0) { cb.processResult(rc, clientPath, p.ctx, rsp .getChildren()); } else { cb.processResult(rc, clientPath, p.ctx, null); } } else if (p.response instanceof GetChildren2Response) { Children2Callback cb = (Children2Callback) p.cb; GetChildren2Response rsp = (GetChildren2Response) p.response; if (rc == 0) { cb.processResult(rc, clientPath, p.ctx, rsp .getChildren(), rsp.getStat()); } else { cb.processResult(rc, clientPath, p.ctx, null, null); } } else if (p.response instanceof CreateResponse) { StringCallback cb = (StringCallback) p.cb; CreateResponse rsp = (CreateResponse) p.response; if (rc == 0) { cb.processResult(rc, clientPath, p.ctx, (chrootPath == null ? rsp.getPath() : rsp.getPath() .substring(chrootPath.length()))); } else { cb.processResult(rc, clientPath, p.ctx, null); } } else if (p.response instanceof MultiResponse) { MultiCallback cb = (MultiCallback) p.cb; MultiResponse rsp = (MultiResponse) p.response; if (rc == 0) { List<OpResult> results = rsp.getResultList(); int newRc = rc; for (OpResult result : results) { if (result instanceof ErrorResult && KeeperException.Code.OK.intValue() != (newRc = ((ErrorResult) result).getErr())) { break; } } cb.processResult(newRc, clientPath, p.ctx, results); } else { cb.processResult(rc, clientPath, p.ctx, null); } } else if (p.cb instanceof VoidCallback) { VoidCallback cb = (VoidCallback) p.cb; cb.processResult(rc, clientPath, p.ctx); } } } catch (Throwable t) { LOG.error("Caught unexpected throwable", t); } } } private void finishPacket(Packet p) { if (p.watchRegistration != null) { p.watchRegistration.register(p.replyHeader.getErr()); } if (p.cb == null) { synchronized (p) { p.finished = true; p.notifyAll(); } } else { p.finished = true; eventThread.queuePacket(p); } } private void conLossPacket(Packet p) { if (p.replyHeader == null) { return; } switch (state) { case AUTH_FAILED: p.replyHeader.setErr(KeeperException.Code.AUTHFAILED.intValue()); break; case CLOSED: p.replyHeader.setErr(KeeperException.Code.SESSIONEXPIRED.intValue()); break; default: p.replyHeader.setErr(KeeperException.Code.CONNECTIONLOSS.intValue()); } finishPacket(p); } private volatile long lastZxid; public long getLastZxid() { return lastZxid; } static class EndOfStreamException extends IOException { private static final long serialVersionUID = -5438877188796231422L; public EndOfStreamException(String msg) { super(msg); } @Override public String toString() { return "EndOfStreamException: " + getMessage(); } } private static class SessionTimeoutException extends IOException { private static final long serialVersionUID = 824482094072071178L; public SessionTimeoutException(String msg) { super(msg); } } private static class SessionExpiredException extends IOException { private static final long serialVersionUID = -1388816932076193249L; public SessionExpiredException(String msg) { super(msg); } } private static class RWServerFoundException extends IOException { private static final long serialVersionUID = 90431199887158758L; public RWServerFoundException(String msg) { super(msg); } } public static final int packetLen = Integer.getInteger("jute.maxbuffer", 4096 * 1024); /** * This class services the outgoing request queue and generates the heart * beats. It also spawns the ReadThread. */ class SendThread extends ZooKeeperThread { private long lastPingSentNs; private final ClientCnxnSocket clientCnxnSocket; private Random r = new Random(System.nanoTime()); private boolean isFirstConnect = true; void readResponse(ByteBuffer incomingBuffer) throws IOException { ByteBufferInputStream bbis = new ByteBufferInputStream( incomingBuffer); BinaryInputArchive bbia = BinaryInputArchive.getArchive(bbis); ReplyHeader replyHdr = new ReplyHeader(); replyHdr.deserialize(bbia, "header"); if (replyHdr.getXid() == -2) { // -2 is the xid for pings if (LOG.isDebugEnabled()) { LOG.debug("Got ping response for sessionid: 0x" + Long.toHexString(sessionId) + " after " + ((System.nanoTime() - lastPingSentNs) / 1000000) + "ms"); } return; } if (replyHdr.getXid() == -4) { // -4 is the xid for AuthPacket if(replyHdr.getErr() == KeeperException.Code.AUTHFAILED.intValue()) { state = States.AUTH_FAILED; eventThread.queueEvent( new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.AuthFailed, null) ); } if (LOG.isDebugEnabled()) { LOG.debug("Got auth sessionid:0x" + Long.toHexString(sessionId)); } return; } if (replyHdr.getXid() == -1) { // -1 means notification if (LOG.isDebugEnabled()) { LOG.debug("Got notification sessionid:0x" + Long.toHexString(sessionId)); } WatcherEvent event = new WatcherEvent(); event.deserialize(bbia, "response"); // convert from a server path to a client path if (chrootPath != null) { String serverPath = event.getPath(); if(serverPath.compareTo(chrootPath)==0) event.setPath("/"); else if (serverPath.length() > chrootPath.length()) event.setPath(serverPath.substring(chrootPath.length())); else { LOG.warn("Got server path " + event.getPath() + " which is too short for chroot path " + chrootPath); } } WatchedEvent we = new WatchedEvent(event); if (LOG.isDebugEnabled()) { LOG.debug("Got " + we + " for sessionid 0x" + Long.toHexString(sessionId)); } eventThread.queueEvent( we ); return; } // If SASL authentication is currently in progress, construct and // send a response packet immediately, rather than queuing a // response as with other packets. if (clientTunneledAuthenticationInProgress()) { GetSASLRequest request = new GetSASLRequest(); request.deserialize(bbia,"token"); zooKeeperSaslClient.respondToServer(request.getToken(), ClientCnxn.this); return; } Packet packet; synchronized (pendingQueue) { if (pendingQueue.size() == 0) { throw new IOException("Nothing in the queue, but got " + replyHdr.getXid()); } packet = pendingQueue.remove(); } /* * Since requests are processed in order, we better get a response * to the first request! */ try { if (packet.requestHeader.getXid() != replyHdr.getXid()) { packet.replyHeader.setErr( KeeperException.Code.CONNECTIONLOSS.intValue()); throw new IOException("Xid out of order. Got Xid " + replyHdr.getXid() + " with err " + + replyHdr.getErr() + " expected Xid " + packet.requestHeader.getXid() + " for a packet with details: " + packet ); } packet.replyHeader.setXid(replyHdr.getXid()); packet.replyHeader.setErr(replyHdr.getErr()); packet.replyHeader.setZxid(replyHdr.getZxid()); if (replyHdr.getZxid() > 0) { lastZxid = replyHdr.getZxid(); } if (packet.response != null && replyHdr.getErr() == 0) { packet.response.deserialize(bbia, "response"); } if (LOG.isDebugEnabled()) { LOG.debug("Reading reply sessionid:0x" + Long.toHexString(sessionId) + ", packet:: " + packet); } } finally { finishPacket(packet); } } SendThread(ClientCnxnSocket clientCnxnSocket) { super(makeThreadName("-SendThread()")); state = States.CONNECTING; this.clientCnxnSocket = clientCnxnSocket; setDaemon(true); } // TODO: can not name this method getState since Thread.getState() // already exists // It would be cleaner to make class SendThread an implementation of // Runnable /** * Used by ClientCnxnSocket * * @return */ ZooKeeper.States getZkState() { return state; } ClientCnxnSocket getClientCnxnSocket() { return clientCnxnSocket; } void primeConnection() throws IOException { LOG.info("Socket connection established to " + clientCnxnSocket.getRemoteSocketAddress() + ", initiating session"); isFirstConnect = false; long sessId = (seenRwServerBefore) ? sessionId : 0; ConnectRequest conReq = new ConnectRequest(0, lastZxid, sessionTimeout, sessId, sessionPasswd); synchronized (outgoingQueue) { // We add backwards since we are pushing into the front // Only send if there's a pending watch // TODO: here we have the only remaining use of zooKeeper in // this class. It's to be eliminated! if (!disableAutoWatchReset) { List<String> dataWatches = zooKeeper.getDataWatches(); List<String> existWatches = zooKeeper.getExistWatches(); List<String> childWatches = zooKeeper.getChildWatches(); if (!dataWatches.isEmpty() || !existWatches.isEmpty() || !childWatches.isEmpty()) { Iterator<String> dataWatchesIter = prependChroot(dataWatches).iterator(); Iterator<String> existWatchesIter = prependChroot(existWatches).iterator(); Iterator<String> childWatchesIter = prependChroot(childWatches).iterator(); long setWatchesLastZxid = lastZxid; while (dataWatchesIter.hasNext() || existWatchesIter.hasNext() || childWatchesIter.hasNext()) { List<String> dataWatchesBatch = new ArrayList<String>(); List<String> existWatchesBatch = new ArrayList<String>(); List<String> childWatchesBatch = new ArrayList<String>(); int batchLength = 0; // Note, we may exceed our max length by a bit when we add the last // watch in the batch. This isn't ideal, but it makes the code simpler. while (batchLength < SET_WATCHES_MAX_LENGTH) { final String watch; if (dataWatchesIter.hasNext()) { watch = dataWatchesIter.next(); dataWatchesBatch.add(watch); } else if (existWatchesIter.hasNext()) { watch = existWatchesIter.next(); existWatchesBatch.add(watch); } else if (childWatchesIter.hasNext()) { watch = childWatchesIter.next(); childWatchesBatch.add(watch); } else { break; } batchLength += watch.length(); } SetWatches sw = new SetWatches(setWatchesLastZxid, dataWatchesBatch, existWatchesBatch, childWatchesBatch); RequestHeader h = new RequestHeader(); h.setType(ZooDefs.OpCode.setWatches); h.setXid(-8); Packet packet = new Packet(h, new ReplyHeader(), sw, null, null); outgoingQueue.addFirst(packet); } } } for (AuthData id : authInfo) { outgoingQueue.addFirst(new Packet(new RequestHeader(-4, OpCode.auth), null, new AuthPacket(0, id.scheme, id.data), null, null)); } outgoingQueue.addFirst(new Packet(null, null, conReq, null, null, readOnly)); } clientCnxnSocket.enableReadWriteOnly(); if (LOG.isDebugEnabled()) { LOG.debug("Session establishment request sent on " + clientCnxnSocket.getRemoteSocketAddress()); } } private List<String> prependChroot(List<String> paths) { if (chrootPath != null && !paths.isEmpty()) { for (int i = 0; i < paths.size(); ++i) { String clientPath = paths.get(i); String serverPath; // handle clientPath = "/" if (clientPath.length() == 1) { serverPath = chrootPath; } else { serverPath = chrootPath + clientPath; } paths.set(i, serverPath); } } return paths; } private void sendPing() { lastPingSentNs = System.nanoTime(); RequestHeader h = new RequestHeader(-2, OpCode.ping); queuePacket(h, null, null, null, null, null, null, null, null); } private InetSocketAddress rwServerAddress = null; private final static int minPingRwTimeout = 100; private final static int maxPingRwTimeout = 60000; private int pingRwTimeout = minPingRwTimeout; // Set to true if and only if constructor of ZooKeeperSaslClient // throws a LoginException: see startConnect() below. private boolean saslLoginFailed = false; private void startConnect(InetSocketAddress addr) throws IOException { // initializing it for new connection saslLoginFailed = false; state = States.CONNECTING; setName(getName().replaceAll("\\(.*\\)", "(" + addr.getHostName() + ":" + addr.getPort() + ")")); if (ZooKeeperSaslClient.isEnabled()) { try { String principalUserName = System.getProperty( ZK_SASL_CLIENT_USERNAME, "zookeeper"); zooKeeperSaslClient = new ZooKeeperSaslClient( principalUserName+"/"+addr.getHostName()); } catch (LoginException e) { // An authentication error occurred when the SASL client tried to initialize: // for Kerberos this means that the client failed to authenticate with the KDC. // This is different from an authentication error that occurs during communication // with the Zookeeper server, which is handled below. LOG.warn("SASL configuration failed: " + e + " Will continue connection to Zookeeper server without " + "SASL authentication, if Zookeeper server allows it."); eventThread.queueEvent(new WatchedEvent( Watcher.Event.EventType.None, Watcher.Event.KeeperState.AuthFailed, null)); saslLoginFailed = true; } } logStartConnect(addr); clientCnxnSocket.connect(addr); } private void logStartConnect(InetSocketAddress addr) { String msg = "Opening socket connection to server " + addr; if (zooKeeperSaslClient != null) { msg += ". " + zooKeeperSaslClient.getConfigStatus(); } LOG.info(msg); } private static final String RETRY_CONN_MSG = ", closing socket connection and attempting reconnect"; @Override public void run() { clientCnxnSocket.introduce(this,sessionId); clientCnxnSocket.updateNow(); clientCnxnSocket.updateLastSendAndHeard(); int to; long lastPingRwServer = Time.currentElapsedTime(); final int MAX_SEND_PING_INTERVAL = 10000; //10 seconds InetSocketAddress serverAddress = null; while (state.isAlive()) { try { if (!clientCnxnSocket.isConnected()) { if(!isFirstConnect){ try { Thread.sleep(r.nextInt(1000)); } catch (InterruptedException e) { LOG.warn("Unexpected exception", e); } } // don't re-establish connection if we are closing if (closing || !state.isAlive()) { break; } if (rwServerAddress != null) { serverAddress = rwServerAddress; rwServerAddress = null; } else { serverAddress = hostProvider.next(1000); } startConnect(serverAddress); clientCnxnSocket.updateLastSendAndHeard(); } if (state.isConnected()) { // determine whether we need to send an AuthFailed event. if (zooKeeperSaslClient != null) { boolean sendAuthEvent = false; if (zooKeeperSaslClient.getSaslState() == ZooKeeperSaslClient.SaslState.INITIAL) { try { zooKeeperSaslClient.initialize(ClientCnxn.this); } catch (SaslException e) { LOG.error("SASL authentication with Zookeeper Quorum member failed: " + e); state = States.AUTH_FAILED; sendAuthEvent = true; } } KeeperState authState = zooKeeperSaslClient.getKeeperState(); if (authState != null) { if (authState == KeeperState.AuthFailed) { // An authentication error occurred during authentication with the Zookeeper Server. state = States.AUTH_FAILED; sendAuthEvent = true; } else { if (authState == KeeperState.SaslAuthenticated) { sendAuthEvent = true; } } } if (sendAuthEvent == true) { eventThread.queueEvent(new WatchedEvent( Watcher.Event.EventType.None, authState,null)); } } to = readTimeout - clientCnxnSocket.getIdleRecv(); } else { to = connectTimeout - clientCnxnSocket.getIdleRecv(); } if (to <= 0) { String warnInfo; warnInfo = "Client session timed out, have not heard from server in " + clientCnxnSocket.getIdleRecv() + "ms" + " for sessionid 0x" + Long.toHexString(sessionId); LOG.warn(warnInfo); throw new SessionTimeoutException(warnInfo); } if (state.isConnected()) { //1000(1 second) is to prevent race condition missing to send the second ping //also make sure not to send too many pings when readTimeout is small int timeToNextPing = readTimeout / 2 - clientCnxnSocket.getIdleSend() - ((clientCnxnSocket.getIdleSend() > 1000) ? 1000 : 0); //send a ping request either time is due or no packet sent out within MAX_SEND_PING_INTERVAL if (timeToNextPing <= 0 || clientCnxnSocket.getIdleSend() > MAX_SEND_PING_INTERVAL) { sendPing(); clientCnxnSocket.updateLastSend(); } else { if (timeToNextPing < to) { to = timeToNextPing; } } } // If we are in read-only mode, seek for read/write server if (state == States.CONNECTEDREADONLY) { long now = Time.currentElapsedTime(); int idlePingRwServer = (int) (now - lastPingRwServer); if (idlePingRwServer >= pingRwTimeout) { lastPingRwServer = now; idlePingRwServer = 0; pingRwTimeout = Math.min(2*pingRwTimeout, maxPingRwTimeout); pingRwServer(); } to = Math.min(to, pingRwTimeout - idlePingRwServer); } clientCnxnSocket.doTransport(to, pendingQueue, outgoingQueue, ClientCnxn.this); } catch (Throwable e) { if (closing) { if (LOG.isDebugEnabled()) { // closing so this is expected LOG.debug("An exception was thrown while closing send thread for session 0x" + Long.toHexString(getSessionId()) + " : " + e.getMessage()); } break; } else { // this is ugly, you have a better way speak up if (e instanceof SessionExpiredException) { LOG.info(e.getMessage() + ", closing socket connection"); } else if (e instanceof SessionTimeoutException) { LOG.info(e.getMessage() + RETRY_CONN_MSG); } else if (e instanceof EndOfStreamException) { LOG.info(e.getMessage() + RETRY_CONN_MSG); } else if (e instanceof RWServerFoundException) { LOG.info(e.getMessage()); } else if (e instanceof SocketException) { LOG.info("Socket error occurred: {}: {}", serverAddress, e.getMessage()); } else { LOG.warn("Session 0x{} for server {}, unexpected error{}", Long.toHexString(getSessionId()), serverAddress, RETRY_CONN_MSG, e); } cleanup(); if (state.isAlive()) { eventThread.queueEvent(new WatchedEvent( Event.EventType.None, Event.KeeperState.Disconnected, null)); } clientCnxnSocket.updateNow(); clientCnxnSocket.updateLastSendAndHeard(); } } } cleanup(); clientCnxnSocket.close(); if (state.isAlive()) { eventThread.queueEvent(new WatchedEvent(Event.EventType.None, Event.KeeperState.Disconnected, null)); } ZooTrace.logTraceMessage(LOG, ZooTrace.getTextTraceLevel(), "SendThread exited loop for session: 0x" + Long.toHexString(getSessionId())); } private void pingRwServer() throws RWServerFoundException { String result = null; InetSocketAddress addr = hostProvider.next(0); LOG.info("Checking server " + addr + " for being r/w." + " Timeout " + pingRwTimeout); Socket sock = null; BufferedReader br = null; try { sock = new Socket(addr.getHostName(), addr.getPort()); sock.setSoLinger(false, -1); sock.setSoTimeout(1000); sock.setTcpNoDelay(true); sock.getOutputStream().write("isro".getBytes()); sock.getOutputStream().flush(); sock.shutdownOutput(); br = new BufferedReader( new InputStreamReader(sock.getInputStream())); result = br.readLine(); } catch (ConnectException e) { // ignore, this just means server is not up } catch (IOException e) { // some unexpected error, warn about it LOG.warn("Exception while seeking for r/w server " + e.getMessage(), e); } finally { if (sock != null) { try { sock.close(); } catch (IOException e) { LOG.warn("Unexpected exception", e); } } if (br != null) { try { br.close(); } catch (IOException e) { LOG.warn("Unexpected exception", e); } } } if ("rw".equals(result)) { pingRwTimeout = minPingRwTimeout; // save the found address so that it's used during the next // connection attempt rwServerAddress = addr; throw new RWServerFoundException("Majority server found at " + addr.getHostName() + ":" + addr.getPort()); } } private void cleanup() { clientCnxnSocket.cleanup(); synchronized (pendingQueue) { for (Packet p : pendingQueue) { conLossPacket(p); } pendingQueue.clear(); } synchronized (outgoingQueue) { for (Packet p : outgoingQueue) { conLossPacket(p); } outgoingQueue.clear(); } } /** * Callback invoked by the ClientCnxnSocket once a connection has been * established. * * @param _negotiatedSessionTimeout * @param _sessionId * @param _sessionPasswd * @param isRO * @throws IOException */ void onConnected(int _negotiatedSessionTimeout, long _sessionId, byte[] _sessionPasswd, boolean isRO) throws IOException { negotiatedSessionTimeout = _negotiatedSessionTimeout; if (negotiatedSessionTimeout <= 0) { state = States.CLOSED; eventThread.queueEvent(new WatchedEvent( Watcher.Event.EventType.None, Watcher.Event.KeeperState.Expired, null)); eventThread.queueEventOfDeath(); String warnInfo; warnInfo = "Unable to reconnect to ZooKeeper service, session 0x" + Long.toHexString(sessionId) + " has expired"; LOG.warn(warnInfo); throw new SessionExpiredException(warnInfo); } if (!readOnly && isRO) { LOG.error("Read/write client got connected to read-only server"); } readTimeout = negotiatedSessionTimeout * 2 / 3; connectTimeout = negotiatedSessionTimeout / hostProvider.size(); hostProvider.onConnected(); sessionId = _sessionId; sessionPasswd = _sessionPasswd; state = (isRO) ? States.CONNECTEDREADONLY : States.CONNECTED; seenRwServerBefore |= !isRO; LOG.info("Session establishment complete on server " + clientCnxnSocket.getRemoteSocketAddress() + ", sessionid = 0x" + Long.toHexString(sessionId) + ", negotiated timeout = " + negotiatedSessionTimeout + (isRO ? " (READ-ONLY mode)" : "")); KeeperState eventState = (isRO) ? KeeperState.ConnectedReadOnly : KeeperState.SyncConnected; eventThread.queueEvent(new WatchedEvent( Watcher.Event.EventType.None, eventState, null)); } void close() { state = States.CLOSED; clientCnxnSocket.wakeupCnxn(); } void testableCloseSocket() throws IOException { clientCnxnSocket.testableCloseSocket(); } public boolean clientTunneledAuthenticationInProgress() { // 1. SASL client is disabled. if (!ZooKeeperSaslClient.isEnabled()) { return false; } // 2. SASL login failed. if (saslLoginFailed == true) { return false; } // 3. SendThread has not created the authenticating object yet, // therefore authentication is (at the earliest stage of being) in progress. if (zooKeeperSaslClient == null) { return true; } // 4. authenticating object exists, so ask it for its progress. return zooKeeperSaslClient.clientTunneledAuthenticationInProgress(); } public void sendPacket(Packet p) throws IOException { clientCnxnSocket.sendPacket(p); } } /** * Shutdown the send/event threads. This method should not be called * directly - rather it should be called as part of close operation. This * method is primarily here to allow the tests to verify disconnection * behavior. */ public void disconnect() { if (LOG.isDebugEnabled()) { LOG.debug("Disconnecting client for session: 0x" + Long.toHexString(getSessionId())); } sendThread.close(); eventThread.queueEventOfDeath(); } /** * Close the connection, which includes; send session disconnect to the * server, shutdown the send/event threads. * * @throws IOException */ public void close() throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Closing client for session: 0x" + Long.toHexString(getSessionId())); } try { RequestHeader h = new RequestHeader(); h.setType(ZooDefs.OpCode.closeSession); submitRequest(h, null, null, null); } catch (InterruptedException e) { // ignore, close the send/event threads } finally { disconnect(); } } private int xid = 1; private volatile States state = States.NOT_CONNECTED; /* * getXid() is called externally by ClientCnxnNIO::doIO() when packets are sent from the outgoingQueue to * the server. Thus, getXid() must be public. */ synchronized public int getXid() { return xid++; } public ReplyHeader submitRequest(RequestHeader h, Record request, Record response, WatchRegistration watchRegistration) throws InterruptedException { ReplyHeader r = new ReplyHeader(); Packet packet = queuePacket(h, r, request, response, null, null, null, null, watchRegistration); synchronized (packet) { while (!packet.finished) { packet.wait(); } } return r; } public void enableWrite() { sendThread.getClientCnxnSocket().enableWrite(); } public void sendPacket(Record request, Record response, AsyncCallback cb, int opCode) throws IOException { // Generate Xid now because it will be sent immediately, // by call to sendThread.sendPacket() below. int xid = getXid(); RequestHeader h = new RequestHeader(); h.setXid(xid); h.setType(opCode); ReplyHeader r = new ReplyHeader(); r.setXid(xid); Packet p = new Packet(h, r, request, response, null, false); p.cb = cb; sendThread.sendPacket(p); } Packet queuePacket(RequestHeader h, ReplyHeader r, Record request, Record response, AsyncCallback cb, String clientPath, String serverPath, Object ctx, WatchRegistration watchRegistration) { Packet packet = null; // Note that we do not generate the Xid for the packet yet. It is // generated later at send-time, by an implementation of ClientCnxnSocket::doIO(), // where the packet is actually sent. synchronized (outgoingQueue) { packet = new Packet(h, r, request, response, watchRegistration); packet.cb = cb; packet.ctx = ctx; packet.clientPath = clientPath; packet.serverPath = serverPath; if (!state.isAlive() || closing) { conLossPacket(packet); } else { // If the client is asking to close the session then // mark as closing if (h.getType() == OpCode.closeSession) { closing = true; } outgoingQueue.add(packet); } } sendThread.getClientCnxnSocket().wakeupCnxn(); return packet; } public void addAuthInfo(String scheme, byte auth[]) { if (!state.isAlive()) { return; } authInfo.add(new AuthData(scheme, auth)); queuePacket(new RequestHeader(-4, OpCode.auth), null, new AuthPacket(0, scheme, auth), null, null, null, null, null, null); } States getState() { return state; } }
apache-2.0
joshk/presto
presto-main/src/main/java/com/facebook/presto/server/StatementResource.java
29436
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.server; import com.facebook.presto.Session; import com.facebook.presto.client.ClientTypeSignature; import com.facebook.presto.client.Column; import com.facebook.presto.client.FailureInfo; import com.facebook.presto.client.QueryError; import com.facebook.presto.client.QueryResults; import com.facebook.presto.client.StageStats; import com.facebook.presto.client.StatementStats; import com.facebook.presto.execution.BufferInfo; import com.facebook.presto.execution.QueryId; import com.facebook.presto.execution.QueryInfo; import com.facebook.presto.execution.QueryManager; import com.facebook.presto.execution.QueryState; import com.facebook.presto.execution.QueryStats; import com.facebook.presto.execution.SharedBufferInfo; import com.facebook.presto.execution.StageInfo; import com.facebook.presto.execution.StageState; import com.facebook.presto.execution.TaskId; import com.facebook.presto.execution.TaskInfo; import com.facebook.presto.operator.ExchangeClient; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.Page; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.type.StandardTypes; import com.facebook.presto.spi.type.Type; import com.facebook.presto.spi.type.TypeSignature; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.collect.AbstractIterator; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import io.airlift.log.Logger; import io.airlift.units.DataSize; import io.airlift.units.Duration; import javax.annotation.PreDestroy; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import java.io.Closeable; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicLong; import static com.facebook.presto.client.PrestoHeaders.PRESTO_CLEAR_SESSION; import static com.facebook.presto.client.PrestoHeaders.PRESTO_SET_SESSION; import static com.facebook.presto.server.ResourceUtil.assertRequest; import static com.facebook.presto.server.ResourceUtil.createSessionForRequest; import static com.facebook.presto.util.Failures.toFailure; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.collect.Iterables.transform; import static io.airlift.concurrent.Threads.threadsNamed; import static io.airlift.http.client.HttpUriBuilder.uriBuilderFrom; import static io.airlift.units.DataSize.Unit.MEGABYTE; import static java.lang.String.format; import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; @Path("/v1/statement") public class StatementResource { private static final Logger log = Logger.get(StatementResource.class); private static final Duration MAX_WAIT_TIME = new Duration(1, SECONDS); private static final Ordering<Comparable<Duration>> WAIT_ORDERING = Ordering.natural().nullsLast(); private static final long DESIRED_RESULT_BYTES = new DataSize(1, MEGABYTE).toBytes(); private final QueryManager queryManager; private final Supplier<ExchangeClient> exchangeClientSupplier; private final ConcurrentMap<QueryId, Query> queries = new ConcurrentHashMap<>(); private final ScheduledExecutorService queryPurger = newSingleThreadScheduledExecutor(threadsNamed("query-purger")); @Inject public StatementResource(QueryManager queryManager, Supplier<ExchangeClient> exchangeClientSupplier) { this.queryManager = checkNotNull(queryManager, "queryManager is null"); this.exchangeClientSupplier = checkNotNull(exchangeClientSupplier, "exchangeClientSupplier is null"); queryPurger.scheduleWithFixedDelay(new PurgeQueriesRunnable(queries, queryManager), 200, 200, MILLISECONDS); } @PreDestroy public void stop() { queryPurger.shutdownNow(); } @POST @Produces(MediaType.APPLICATION_JSON) public Response createQuery( String statement, @Context HttpServletRequest servletRequest, @Context UriInfo uriInfo) throws InterruptedException { assertRequest(!isNullOrEmpty(statement), "SQL statement is empty"); Session session = createSessionForRequest(servletRequest); ExchangeClient exchangeClient = exchangeClientSupplier.get(); Query query = new Query(session, statement, queryManager, exchangeClient); queries.put(query.getQueryId(), query); return getQueryResults(query, Optional.empty(), uriInfo, new Duration(1, MILLISECONDS)); } @GET @Path("{queryId}/{token}") @Produces(MediaType.APPLICATION_JSON) public Response getQueryResults( @PathParam("queryId") QueryId queryId, @PathParam("token") long token, @QueryParam("maxWait") Duration maxWait, @Context UriInfo uriInfo) throws InterruptedException { Query query = queries.get(queryId); if (query == null) { return Response.status(Status.NOT_FOUND).build(); } Duration wait = WAIT_ORDERING.min(MAX_WAIT_TIME, maxWait); return getQueryResults(query, Optional.of(token), uriInfo, wait); } private static Response getQueryResults(Query query, Optional<Long> token, UriInfo uriInfo, Duration wait) throws InterruptedException { QueryResults queryResults; if (token.isPresent()) { queryResults = query.getResults(token.get(), uriInfo, wait); } else { queryResults = query.getNextResults(uriInfo, wait); } ResponseBuilder response = Response.ok(queryResults); // add set session properties query.getSetSessionProperties().entrySet().stream() .forEach(entry -> response.header(PRESTO_SET_SESSION, entry.getKey() + '=' + entry.getValue())); // add clear session properties query.getResetSessionProperties().stream() .forEach(name -> response.header(PRESTO_CLEAR_SESSION, name)); return response.build(); } @DELETE @Path("{queryId}/{token}") @Produces(MediaType.APPLICATION_JSON) public Response cancelQuery(@PathParam("queryId") QueryId queryId, @PathParam("token") long token) { Query query = queries.get(queryId); if (query == null) { return Response.status(Status.NOT_FOUND).build(); } query.close(); return Response.noContent().build(); } @ThreadSafe public static class Query implements Closeable { private final QueryManager queryManager; private final QueryId queryId; private final ExchangeClient exchangeClient; private final AtomicLong resultId = new AtomicLong(); private final Session session; @GuardedBy("this") private QueryResults lastResult; @GuardedBy("this") private String lastResultPath; @GuardedBy("this") private List<Column> columns; @GuardedBy("this") private Map<String, String> setSessionProperties; @GuardedBy("this") private Set<String> resetSessionProperties; @GuardedBy("this") private Long updateCount; public Query(Session session, String query, QueryManager queryManager, ExchangeClient exchangeClient) { checkNotNull(session, "session is null"); checkNotNull(query, "query is null"); checkNotNull(queryManager, "queryManager is null"); checkNotNull(exchangeClient, "exchangeClient is null"); this.session = session; this.queryManager = queryManager; QueryInfo queryInfo = queryManager.createQuery(session, query); queryId = queryInfo.getQueryId(); this.exchangeClient = exchangeClient; } @Override public void close() { queryManager.cancelQuery(queryId); } public QueryId getQueryId() { return queryId; } public synchronized Map<String, String> getSetSessionProperties() { return setSessionProperties; } public synchronized Set<String> getResetSessionProperties() { return resetSessionProperties; } public synchronized QueryResults getResults(long token, UriInfo uriInfo, Duration maxWaitTime) throws InterruptedException { // is the a repeated request for the last results? String requestedPath = uriInfo.getAbsolutePath().getPath(); if (lastResultPath != null && requestedPath.equals(lastResultPath)) { // tell query manager we are still interested in the query queryManager.getQueryInfo(queryId); return lastResult; } if (token < resultId.get()) { throw new WebApplicationException(Status.GONE); } // if this is not a request for the next results, return not found if (lastResult.getNextUri() == null || !requestedPath.equals(lastResult.getNextUri().getPath())) { // unknown token throw new WebApplicationException(Status.NOT_FOUND); } return getNextResults(uriInfo, maxWaitTime); } public synchronized QueryResults getNextResults(UriInfo uriInfo, Duration maxWaitTime) throws InterruptedException { Iterable<List<Object>> data = getData(maxWaitTime); // get the query info before returning // force update if query manager is closed QueryInfo queryInfo = queryManager.getQueryInfo(queryId); // if we have received all of the output data and the query is not marked as done, wait for the query to finish if (exchangeClient.isClosed() && !queryInfo.getState().isDone()) { queryManager.waitForStateChange(queryId, queryInfo.getState(), maxWaitTime); queryInfo = queryManager.getQueryInfo(queryId); } // TODO: figure out a better way to do this // grab the update count for non-queries if ((data != null) && (queryInfo.getUpdateType() != null) && (updateCount == null) && (columns.size() == 1) && (columns.get(0).getType().equals(StandardTypes.BIGINT))) { Iterator<List<Object>> iterator = data.iterator(); if (iterator.hasNext()) { updateCount = ((Number) iterator.next().get(0)).longValue(); } } // close exchange client if the query has failed if (queryInfo.getState().isDone()) { if (queryInfo.getState() != QueryState.FINISHED) { exchangeClient.close(); } else if (queryInfo.getOutputStage() == null) { // For simple executions (e.g. drop table), there will never be an output stage, // so close the exchange as soon as the query is done. exchangeClient.close(); // Return a single value for clients that require a result. columns = ImmutableList.of(new Column("result", "boolean", new ClientTypeSignature(StandardTypes.BOOLEAN, ImmutableList.<ClientTypeSignature>of(), ImmutableList.<Object>of()))); data = ImmutableSet.<List<Object>>of(ImmutableList.<Object>of(true)); } } // only return a next if the query is not done or there is more data to send (due to buffering) URI nextResultsUri = null; if ((!queryInfo.getState().isDone()) || (!exchangeClient.isClosed())) { nextResultsUri = createNextResultsUri(uriInfo); } // update setSessionProperties setSessionProperties = queryInfo.getSetSessionProperties(); resetSessionProperties = queryInfo.getResetSessionProperties(); // first time through, self is null QueryResults queryResults = new QueryResults( queryId.toString(), uriInfo.getRequestUriBuilder().replaceQuery("").replacePath(queryInfo.getSelf().getPath()).build(), findCancelableLeafStage(queryInfo), nextResultsUri, columns, data, toStatementStats(queryInfo), toQueryError(queryInfo), queryInfo.getUpdateType(), updateCount); // cache the last results if (lastResult != null) { lastResultPath = lastResult.getNextUri().getPath(); } else { lastResultPath = null; } lastResult = queryResults; return queryResults; } private synchronized Iterable<List<Object>> getData(Duration maxWait) throws InterruptedException { // wait for query to start QueryInfo queryInfo = queryManager.getQueryInfo(queryId); while (maxWait.toMillis() > 1 && !isQueryStarted(queryInfo)) { maxWait = queryManager.waitForStateChange(queryId, queryInfo.getState(), maxWait); queryInfo = queryManager.getQueryInfo(queryId); } // if query did not finish starting or does not have output, just return if (!isQueryStarted(queryInfo) || queryInfo.getOutputStage() == null) { return null; } if (columns == null) { columns = createColumnsList(queryInfo); } List<Type> types = queryInfo.getOutputStage().getTypes(); updateExchangeClient(queryInfo.getOutputStage()); ImmutableList.Builder<RowIterable> pages = ImmutableList.builder(); // wait up to max wait for data to arrive; then try to return at least DESIRED_RESULT_BYTES long bytes = 0; while (bytes < DESIRED_RESULT_BYTES) { Page page = exchangeClient.getNextPage(maxWait); if (page == null) { break; } bytes += page.getSizeInBytes(); pages.add(new RowIterable(session.toConnectorSession(), types, page)); // only wait on first call maxWait = new Duration(0, MILLISECONDS); } if (bytes == 0) { return null; } return Iterables.concat(pages.build()); } private static boolean isQueryStarted(QueryInfo queryInfo) { QueryState state = queryInfo.getState(); return state != QueryState.QUEUED && queryInfo.getState() != QueryState.PLANNING && queryInfo.getState() != QueryState.STARTING; } private synchronized void updateExchangeClient(StageInfo outputStage) { // add any additional output locations if (!outputStage.getState().isDone()) { for (TaskInfo taskInfo : outputStage.getTasks()) { SharedBufferInfo outputBuffers = taskInfo.getOutputBuffers(); List<BufferInfo> buffers = outputBuffers.getBuffers(); if (buffers.isEmpty() || outputBuffers.getState().canAddBuffers()) { // output buffer has not been created yet continue; } Preconditions.checkState(buffers.size() == 1, "Expected a single output buffer for task %s, but found %s", taskInfo.getTaskId(), buffers); TaskId bufferId = Iterables.getOnlyElement(buffers).getBufferId(); URI uri = uriBuilderFrom(taskInfo.getSelf()).appendPath("results").appendPath(bufferId.toString()).build(); exchangeClient.addLocation(uri); } } if (allOutputBuffersCreated(outputStage)) { exchangeClient.noMoreLocations(); } } private static boolean allOutputBuffersCreated(StageInfo outputStage) { StageState stageState = outputStage.getState(); // if the stage is already done, then there will be no more buffers if (stageState.isDone()) { return true; } // has the stage finished scheduling? if (stageState == StageState.PLANNED || stageState == StageState.SCHEDULING) { return false; } // have all tasks finished adding buffers return outputStage.getTasks().stream() .allMatch(taskInfo -> !taskInfo.getOutputBuffers().getState().canAddBuffers()); } private synchronized URI createNextResultsUri(UriInfo uriInfo) { return uriInfo.getBaseUriBuilder().replacePath("/v1/statement").path(queryId.toString()).path(String.valueOf(resultId.incrementAndGet())).replaceQuery("").build(); } private static List<Column> createColumnsList(QueryInfo queryInfo) { checkNotNull(queryInfo, "queryInfo is null"); StageInfo outputStage = queryInfo.getOutputStage(); checkNotNull(outputStage, "outputStage is null"); List<String> names = queryInfo.getFieldNames(); List<Type> types = outputStage.getTypes(); checkArgument(names.size() == types.size(), "names and types size mismatch"); ImmutableList.Builder<Column> list = ImmutableList.builder(); for (int i = 0; i < names.size(); i++) { String name = names.get(i); TypeSignature typeSignature = types.get(i).getTypeSignature(); String type = typeSignature.toString(); list.add(new Column(name, type, new ClientTypeSignature(typeSignature))); } return list.build(); } private static StatementStats toStatementStats(QueryInfo queryInfo) { QueryStats queryStats = queryInfo.getQueryStats(); return StatementStats.builder() .setState(queryInfo.getState().toString()) .setScheduled(queryInfo.isScheduled()) .setNodes(globalUniqueNodes(queryInfo.getOutputStage()).size()) .setTotalSplits(queryStats.getTotalDrivers()) .setQueuedSplits(queryStats.getQueuedDrivers()) .setRunningSplits(queryStats.getRunningDrivers()) .setCompletedSplits(queryStats.getCompletedDrivers()) .setUserTimeMillis(queryStats.getTotalUserTime().toMillis()) .setCpuTimeMillis(queryStats.getTotalCpuTime().toMillis()) .setWallTimeMillis(queryStats.getTotalScheduledTime().toMillis()) .setProcessedRows(queryStats.getRawInputPositions()) .setProcessedBytes(queryStats.getRawInputDataSize().toBytes()) .setRootStage(toStageStats(queryInfo.getOutputStage())) .build(); } private static StageStats toStageStats(StageInfo stageInfo) { if (stageInfo == null) { return null; } com.facebook.presto.execution.StageStats stageStats = stageInfo.getStageStats(); ImmutableList.Builder<StageStats> subStages = ImmutableList.builder(); for (StageInfo subStage : stageInfo.getSubStages()) { subStages.add(toStageStats(subStage)); } Set<String> uniqueNodes = new HashSet<>(); for (TaskInfo task : stageInfo.getTasks()) { // todo add nodeId to TaskInfo URI uri = task.getSelf(); uniqueNodes.add(uri.getHost() + ":" + uri.getPort()); } return StageStats.builder() .setStageId(String.valueOf(stageInfo.getStageId().getId())) .setState(stageInfo.getState().toString()) .setDone(stageInfo.getState().isDone()) .setNodes(uniqueNodes.size()) .setTotalSplits(stageStats.getTotalDrivers()) .setQueuedSplits(stageStats.getQueuedDrivers()) .setRunningSplits(stageStats.getRunningDrivers()) .setCompletedSplits(stageStats.getCompletedDrivers()) .setUserTimeMillis(stageStats.getTotalUserTime().toMillis()) .setCpuTimeMillis(stageStats.getTotalCpuTime().toMillis()) .setWallTimeMillis(stageStats.getTotalScheduledTime().toMillis()) .setProcessedRows(stageStats.getRawInputPositions()) .setProcessedBytes(stageStats.getRawInputDataSize().toBytes()) .setSubStages(subStages.build()) .build(); } private static Set<String> globalUniqueNodes(StageInfo stageInfo) { if (stageInfo == null) { return ImmutableSet.of(); } ImmutableSet.Builder<String> nodes = ImmutableSet.builder(); for (TaskInfo task : stageInfo.getTasks()) { // todo add nodeId to TaskInfo URI uri = task.getSelf(); nodes.add(uri.getHost() + ":" + uri.getPort()); } for (StageInfo subStage : stageInfo.getSubStages()) { nodes.addAll(globalUniqueNodes(subStage)); } return nodes.build(); } private static URI findCancelableLeafStage(QueryInfo queryInfo) { if (queryInfo.getOutputStage() == null) { // query is not running yet, cannot cancel leaf stage return null; } // query is running, find the leaf-most running stage return findCancelableLeafStage(queryInfo.getOutputStage()); } private static URI findCancelableLeafStage(StageInfo stage) { // if this stage is already done, we can't cancel it if (stage.getState().isDone()) { return null; } // attempt to find a cancelable sub stage // check in reverse order since build side of a join will be later in the list for (StageInfo subStage : Lists.reverse(stage.getSubStages())) { URI leafStage = findCancelableLeafStage(subStage); if (leafStage != null) { return leafStage; } } // no matching sub stage, so return this stage return stage.getSelf(); } private static QueryError toQueryError(QueryInfo queryInfo) { FailureInfo failure = queryInfo.getFailureInfo(); if (failure == null) { QueryState state = queryInfo.getState(); if ((!state.isDone()) || (state == QueryState.FINISHED)) { return null; } log.warn("Query %s in state %s has no failure info", queryInfo.getQueryId(), state); failure = toFailure(new RuntimeException(format("Query is %s (reason unknown)", state))).toFailureInfo(); } return new QueryError(failure.getMessage(), null, 0, failure.getErrorLocation(), failure); } private static class RowIterable implements Iterable<List<Object>> { private final ConnectorSession session; private final List<Type> types; private final Page page; private RowIterable(ConnectorSession session, List<Type> types, Page page) { this.session = session; this.types = ImmutableList.copyOf(checkNotNull(types, "types is null")); this.page = checkNotNull(page, "page is null"); } @Override public Iterator<List<Object>> iterator() { return new RowIterator(session, types, page); } } private static class RowIterator extends AbstractIterator<List<Object>> { private final ConnectorSession session; private final List<Type> types; private final Page page; private int position = -1; private RowIterator(ConnectorSession session, List<Type> types, Page page) { this.session = session; this.types = types; this.page = page; } @Override protected List<Object> computeNext() { position++; if (position >= page.getPositionCount()) { return endOfData(); } List<Object> values = new ArrayList<>(page.getChannelCount()); for (int channel = 0; channel < page.getChannelCount(); channel++) { Type type = types.get(channel); Block block = page.getBlock(channel); values.add(type.getObjectValue(session, block, position)); } return Collections.unmodifiableList(values); } } } private static class PurgeQueriesRunnable implements Runnable { private final ConcurrentMap<QueryId, Query> queries; private final QueryManager queryManager; public PurgeQueriesRunnable(ConcurrentMap<QueryId, Query> queries, QueryManager queryManager) { this.queries = queries; this.queryManager = queryManager; } @Override public void run() { try { // Queries are added to the query manager before being recorded in queryIds set. // Therefore, we take a snapshot if queryIds before getting the live queries // from the query manager. Then we remove only the queries in the snapshot and // not live queries set. If we did this in the other order, a query could be // registered between fetching the live queries and inspecting the queryIds set. Set<QueryId> queryIdsSnapshot = ImmutableSet.copyOf(queries.keySet()); // do not call queryManager.getQueryInfo() since it updates the heartbeat time Set<QueryId> liveQueries = ImmutableSet.copyOf(transform(queryManager.getAllQueryInfo(), QueryInfo::getQueryId)); Set<QueryId> deadQueries = Sets.difference(queryIdsSnapshot, liveQueries); for (QueryId deadQueryId : deadQueries) { Query query = queries.remove(deadQueryId); if (query != null) { query.close(); log.info("Removed expired query %s", deadQueryId); } } } catch (Throwable e) { log.warn(e, "Error removing old queries"); } } } }
apache-2.0
ViRGiL175/java-git-starship
src/main/java/rape/brutal/gitstarship/parts/engine/SmallEngine.java
300
/* * Copyright 2017 BrutalRape(). * Licensed under the Apache License, Version 2.0 */ package rape.brutal.gitstarship.parts.engine; /** * Created by haze on 30.03.2017. */ public class SmallEngine extends Engine { public SmallEngine() { super(500, 20, "SmallEngine", 10); } }
apache-2.0
leafclick/intellij-community
java/java-impl/src/com/intellij/cyclicDependencies/actions/CyclicDependenciesAction.java
7749
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.cyclicDependencies.actions; import com.intellij.analysis.AnalysisScope; import com.intellij.analysis.AnalysisScopeBundle; import com.intellij.analysis.JavaAnalysisScope; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiPackage; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.ui.IdeBorderFactory; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class CyclicDependenciesAction extends AnAction{ private final String myAnalysisVerb; private final String myAnalysisNoun; private final String myTitle; public CyclicDependenciesAction() { myAnalysisVerb = AnalysisScopeBundle.message("action.analyze.verb"); myAnalysisNoun = AnalysisScopeBundle.message("action.analysis.noun"); myTitle = AnalysisScopeBundle.message("action.cyclic.dependency.title"); } @Override public void update(@NotNull AnActionEvent event) { Presentation presentation = event.getPresentation(); presentation.setEnabled( getInspectionScope(event.getDataContext()) != null || event.getData(CommonDataKeys.PROJECT) != null); } @Override public void actionPerformed(@NotNull AnActionEvent e) { DataContext dataContext = e.getDataContext(); final Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null) { return; } final Module module = LangDataKeys.MODULE.getData(dataContext); AnalysisScope scope = getInspectionScope(dataContext); if (scope == null || scope.getScopeType() != AnalysisScope.MODULES) { ProjectModuleOrPackageDialog dlg = null; if (module != null) { dlg = new ProjectModuleOrPackageDialog( ModuleManager.getInstance(project).getModules().length == 1 ? null : ModuleUtilCore.getModuleNameInReadAction(module), scope); if (!dlg.showAndGet()) { return; } } if (dlg == null || dlg.isProjectScopeSelected()) { scope = getProjectScope(dataContext); } else if (dlg.isModuleScopeSelected()) { scope = getModuleScope(dataContext); } if (scope != null) { scope.setIncludeTestSource(dlg != null && dlg.isIncludeTestSources()); } } FileDocumentManager.getInstance().saveAllDocuments(); new CyclicDependenciesHandler(project, scope).analyze(); } @Nullable private static AnalysisScope getInspectionScope(final DataContext dataContext) { final Project project = CommonDataKeys.PROJECT.getData(dataContext); if (project == null) return null; AnalysisScope scope = getInspectionScopeImpl(dataContext); return scope != null && scope.getScopeType() != AnalysisScope.INVALID ? scope : null; } @Nullable private static AnalysisScope getInspectionScopeImpl(DataContext dataContext) { //Possible scopes: package, project, module. Project projectContext = PlatformDataKeys.PROJECT_CONTEXT.getData(dataContext); if (projectContext != null) { return null; } Module moduleContext = LangDataKeys.MODULE_CONTEXT.getData(dataContext); if (moduleContext != null) { return null; } final Module [] modulesArray = LangDataKeys.MODULE_CONTEXT_ARRAY.getData(dataContext); if (modulesArray != null && modulesArray.length > 0) { return new AnalysisScope(modulesArray); } PsiElement psiTarget = CommonDataKeys.PSI_ELEMENT.getData(dataContext); if (psiTarget instanceof PsiDirectory) { PsiDirectory psiDirectory = (PsiDirectory)psiTarget; if (!psiDirectory.getManager().isInProject(psiDirectory)) return null; return new AnalysisScope(psiDirectory); } if (psiTarget instanceof PsiPackage) { PsiPackage pack = (PsiPackage)psiTarget; PsiDirectory[] dirs = pack.getDirectories(GlobalSearchScope.projectScope(pack.getProject())); if (dirs.length == 0) return null; return new JavaAnalysisScope(pack, LangDataKeys.MODULE.getData(dataContext)); } return null; } @Nullable private static AnalysisScope getProjectScope(@NotNull DataContext dataContext) { final Project data = CommonDataKeys.PROJECT.getData(dataContext); if (data == null) { return null; } return new AnalysisScope(data); } @Nullable private static AnalysisScope getModuleScope(DataContext dataContext) { final Module data = LangDataKeys.MODULE.getData(dataContext); if (data == null) { return null; } return new AnalysisScope(data); } private class ProjectModuleOrPackageDialog extends DialogWrapper { private final String myModuleName; private final AnalysisScope mySelectedScope; private JRadioButton myProjectButton; private JRadioButton myModuleButton; private JRadioButton mySelectedScopeButton; private JPanel myScopePanel; private JPanel myWholePanel; private JCheckBox myIncludeTestSourcesCb; ProjectModuleOrPackageDialog(String moduleName, AnalysisScope selectedScope) { super(true); myModuleName = moduleName; mySelectedScope = selectedScope; init(); setTitle(AnalysisScopeBundle.message("cyclic.dependencies.scope.dialog.title", myTitle)); setHorizontalStretch(1.75f); } boolean isIncludeTestSources() { return myIncludeTestSourcesCb.isSelected(); } @Override protected JComponent createCenterPanel() { myScopePanel.setBorder(IdeBorderFactory.createTitledBorder( AnalysisScopeBundle.message("analysis.scope.title", myAnalysisNoun))); myProjectButton.setText(AnalysisScopeBundle.message("cyclic.dependencies.scope.dialog.project.button", myAnalysisVerb)); ButtonGroup group = new ButtonGroup(); group.add(myProjectButton); if (myModuleName != null) { myModuleButton.setText(AnalysisScopeBundle.message("cyclic.dependencies.scope.dialog.module.button", myAnalysisVerb, myModuleName)); group.add(myModuleButton); } myModuleButton.setVisible(myModuleName != null); mySelectedScopeButton.setVisible(mySelectedScope != null); if (mySelectedScope != null) { mySelectedScopeButton.setText(mySelectedScope.getShortenName()); group.add(mySelectedScopeButton); } if (mySelectedScope != null) { mySelectedScopeButton.setSelected(true); } else if (myModuleName != null) { myModuleButton.setSelected(true); } else { myProjectButton.setSelected(true); } return myWholePanel; } public boolean isProjectScopeSelected() { return myProjectButton.isSelected(); } public boolean isModuleScopeSelected() { return myModuleButton != null && myModuleButton.isSelected(); } } }
apache-2.0
Zahusek/TinyProtocolAPI
com/gmail/zahusek/tinyprotocolapi/listener/PacketEvent.java
886
package com.gmail.zahusek.tinyprotocolapi.listener; import io.netty.channel.Channel; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; public abstract class PacketEvent implements Cancellable { public final Player player; public final Channel channel; public final Object handle; private boolean c; public PacketEvent(Player player, Channel channel, Object handle) { this.player = player; this.channel = channel; this.handle = handle; c = false; } public Player getPlayer() { return player; } public Channel getChannel() { return channel; } public Object getPacket() { return handle; } @Override public boolean isCancelled() { return c; } @Override public void setCancelled(boolean cancel) { c = cancel; } abstract public PacketHandlerList getPacketHandlerList(); }
apache-2.0
emccode/ecs-cf-service-broker
src/main/java/com/emc/ecs/management/sdk/NamespaceQuotaAction.java
1542
package com.emc.ecs.management.sdk; import com.emc.ecs.servicebroker.exception.EcsManagementClientException; import com.emc.ecs.management.sdk.model.NamespaceQuotaDetails; import com.emc.ecs.management.sdk.model.NamespaceQuotaParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import static com.emc.ecs.management.sdk.Constants.*; public final class NamespaceQuotaAction { private NamespaceQuotaAction() { } public static void create(Connection connection, String namespace, NamespaceQuotaParam createParam) throws EcsManagementClientException { UriBuilder uri = connection.getUriBuilder().segment(OBJECT, NAMESPACES, NAMESPACE, namespace, QUOTA); connection.handleRemoteCall(PUT, uri, createParam); } public static NamespaceQuotaDetails get(Connection connection, String namespace) throws EcsManagementClientException { UriBuilder uri = connection.getUriBuilder().segment(OBJECT, NAMESPACES, NAMESPACE, namespace, QUOTA); Response response = connection.handleRemoteCall(GET, uri, null); return response.readEntity(NamespaceQuotaDetails.class); } public static void delete(Connection connection, String namespace) throws EcsManagementClientException { UriBuilder uri = connection.getUriBuilder().segment(OBJECT, NAMESPACES, NAMESPACE, namespace, QUOTA); connection.handleRemoteCall(DELETE, uri, null); } }
apache-2.0
gurbuzali/hazelcast-jet
hazelcast-jet-core/src/main/java/com/hazelcast/jet/pipeline/ServiceFactory.java
15091
/* * Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.jet.pipeline; import com.hazelcast.function.BiFunctionEx; import com.hazelcast.function.ConsumerEx; import com.hazelcast.function.FunctionEx; import com.hazelcast.jet.JetException; import com.hazelcast.jet.core.Processor; import com.hazelcast.jet.core.ProcessorSupplier; import com.hazelcast.jet.core.ProcessorSupplier.Context; import javax.annotation.Nonnull; import java.io.File; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static com.hazelcast.jet.impl.util.Util.checkSerializable; import static java.util.Collections.emptyMap; /** * A holder of functions needed to create and destroy a service object used in * pipeline transforms such as {@link GeneralStage#mapUsingService * stage.mapUsingService()}. * <p> * The lifecycle of this factory object is as follows: * <ol><li> * When you submit a job, Jet serializes {@code ServiceFactory} and sends * it to all the cluster members. * <li> * On each member Jet calls {@link #createContextFn()} to get a context * object that will be shared across all the service instances on that * member. For example, if you are connecting to an external service that * provides a thread-safe client, you can create it here and then create * individual sessions for each service instance. * <li> * Jet repeatedly calls {@link #createServiceFn()} to create as many * service instances on each member as determined by the {@link * GeneralStage#setLocalParallelism(int) localParallelism} of the pipeline * stage. The invocations of {@link #createServiceFn()} receive the context * object. * <li> * When the job is done, Jet calls {@link #destroyServiceFn()} with each * service instance. * <li> * Finally, Jet calls {@link #destroyContextFn()} with the context object. * </ol> * If you don't need the member-wide context object, you can call the simpler * methods {@link ServiceFactories#nonSharedService(FunctionEx, ConsumerEx)} * ServiceFactories.processorLocalService} or {@link * ServiceFactories#sharedService(FunctionEx, ConsumerEx)} * ServiceFactories.memberLocalService}. * <p> * Here's a list of pipeline transforms that require a {@code ServiceFactory}: * <ul> * <li>{@link GeneralStage#mapUsingService} * <li>{@link GeneralStage#filterUsingService} * <li>{@link GeneralStage#flatMapUsingService} * <li>{@link GeneralStage#mapUsingServiceAsync} * <li>{@link GeneralStage#mapUsingServiceAsyncBatched} * <li>{@link GeneralStageWithKey#mapUsingService} * <li>{@link GeneralStageWithKey#filterUsingService} * <li>{@link GeneralStageWithKey#flatMapUsingService} * <li>{@link GeneralStageWithKey#mapUsingServiceAsync} * </ul> * * @param <C> type of the shared context object * @param <S> type of the service object * * @since 4.0 */ public final class ServiceFactory<C, S> implements Serializable, Cloneable { /** * Default value for {@link #isCooperative}. */ public static final boolean COOPERATIVE_DEFAULT = true; private boolean isCooperative = COOPERATIVE_DEFAULT; @Nonnull private final FunctionEx<? super Context, ? extends C> createContextFn; @Nonnull private BiFunctionEx<? super Processor.Context, ? super C, ? extends S> createServiceFn = (ctx, svcContext) -> { throw new IllegalStateException("This ServiceFactory is missing a createServiceFn"); }; @Nonnull private ConsumerEx<? super S> destroyServiceFn = ConsumerEx.noop(); @Nonnull private ConsumerEx<? super C> destroyContextFn = ConsumerEx.noop(); @Nonnull private Map<String, File> attachedFiles = emptyMap(); private ServiceFactory(@Nonnull FunctionEx<? super ProcessorSupplier.Context, ? extends C> createContextFn) { this.createContextFn = createContextFn; } /** * Creates a new {@code ServiceFactory} with the given function that * creates the shared context object. Make sure to also call {@link * #withCreateServiceFn} that creates the service objects. You can use the * shared context as a shared service object as well, by returning it from * {@code createServiceFn}. To achieve this more conveniently, use {@link * ServiceFactories#sharedService} instead of this method. If you don't need * a shared context at all, just independent service instances, you can use * the convenience of {@link ServiceFactories#nonSharedService}. * <p> * <strong>Note:</strong> if your service has a blocking API (e.g., doing * synchronous IO or acquiring locks), you must call {@link * #toNonCooperative()} as a hint to the Jet execution engine to start a * dedicated thread for those calls. Failing to do this can cause severe * performance problems. You should also carefully consider how much local * parallelism you need for this step since each parallel tasklet needs its * own thread. Call {@link GeneralStage#setLocalParallelism * stage.setLocalParallelism()} to set an explicit level, otherwise it will * depend on the number of cores on the Jet machine, which makes no sense * for blocking code. * * @param createContextFn the function to create new context object, given a {@link * ProcessorSupplier.Context}. Called once per Jet member. It must be * stateless. * @param <C> type of the service context instance * * @return a new factory instance, not yet ready to use (needs the {@code * createServiceFn}) */ @Nonnull public static <C> ServiceFactory<C, Void> withCreateContextFn( @Nonnull FunctionEx<? super ProcessorSupplier.Context, ? extends C> createContextFn ) { checkSerializable(createContextFn, "createContextFn"); return new ServiceFactory<>(createContextFn); } /** * Returns a copy of this {@code ServiceFactory} with the {@code * destroyContext} function replaced with the given function. * <p> * Jet calls this function at the end of the job for each shared context * object it created (one on each cluster member). * * @param destroyContextFn the function to destroy the shared service * context. It must be stateless. * @return a copy of this factory with the supplied destroy-function */ @Nonnull public ServiceFactory<C, S> withDestroyContextFn(@Nonnull ConsumerEx<? super C> destroyContextFn) { checkSerializable(destroyContextFn, "destroyContextFn"); ServiceFactory<C, S> copy = clone(); copy.destroyContextFn = destroyContextFn; return copy; } /** * Returns a copy of this {@code ServiceFactory} with the given {@code * createService} function. * <p> * Jet calls this function to create each parallel instance of the service * object (their number on each cluster member is determined by {@link * GeneralStage#setLocalParallelism(int) stage.localParallelism}). Each * invocation gets the {@linkplain #createContextFn() shared context * instance} as the parameter, as well as the lower-level {@link * Processor.Context}. * <p> * Since the call of this method establishes the {@code <S>} type parameter * of the service factory, you must call it before setting the {@link * #withDestroyServiceFn(ConsumerEx) destroyService} function. Calling * this method resets any pre-existing {@code destroyService} function to a * no-op. * * @param createServiceFn the function that creates the service instance. * It must be stateless. * @return a copy of this factory with the supplied create-service-function */ @Nonnull public <S_NEW> ServiceFactory<C, S_NEW> withCreateServiceFn( @Nonnull BiFunctionEx<? super Processor.Context, ? super C, ? extends S_NEW> createServiceFn ) { checkSerializable(createServiceFn, "createServiceFn"); @SuppressWarnings("unchecked") ServiceFactory<C, S_NEW> copy = (ServiceFactory<C, S_NEW>) clone(); copy.createServiceFn = createServiceFn; return copy; } /** * Returns a copy of this {@code ServiceFactory} with the {@code * destroyService} function replaced with the given function. * <p> * The destroy function is called at the end of the job to destroy all * created services objects. * * @param destroyServiceFn the function to destroy the service instance. * This function is called once per processor instance. It must be * stateless. * @return a copy of this factory with the supplied destroy-function */ @Nonnull public ServiceFactory<C, S> withDestroyServiceFn(@Nonnull ConsumerEx<? super S> destroyServiceFn) { checkSerializable(destroyServiceFn, "destroyServiceFn"); ServiceFactory<C, S> copy = clone(); copy.destroyServiceFn = destroyServiceFn; return copy; } /** * Returns a copy of this {@code ServiceFactory} with the {@code * isCooperative} flag set to {@code false}. Call this method if your * service doesn't follow the {@linkplain Processor#isCooperative() * cooperative processor contract}, that is if it waits for IO, blocks for * synchronization, takes too long to complete etc. If the service will * perform async operations, you can typically use a cooperative * processor. Cooperative processors offer higher performance. * * @return a copy of this factory with the {@code isCooperative} flag set * to {@code false}. */ @Nonnull public ServiceFactory<C, S> toNonCooperative() { ServiceFactory<C, S> copy = clone(); copy.isCooperative = false; return copy; } /** * Attaches a file to this service factory under the given ID. It will * become a part of the Jet job and available to {@link #createContextFn()} * as {@link ProcessorSupplier.Context#attachedFile * procSupplierContext.attachedFile(id)}. * * @return a copy of this factory with the file attached * * @since 4.0 */ @Nonnull public ServiceFactory<C, S> withAttachedFile(@Nonnull String id, @Nonnull File file) { if (!file.isFile() || !file.canRead()) { throw new IllegalArgumentException("Not an existing, readable file: " + file); } return attachFileOrDir(id, file); } /** * Attaches a directory to this service factory under the given ID. It will * become a part of the Jet job and available to {@link #createContextFn()} * as {@link ProcessorSupplier.Context#attachedDirectory * procSupplierContext.attachedDirectory(id)}. * * @return a copy of this factory with the directory attached * * @since 4.0 */ @Nonnull public ServiceFactory<C, S> withAttachedDirectory(@Nonnull String id, @Nonnull File directory) { if (!directory.isDirectory() || !directory.canRead()) { throw new IllegalArgumentException("Not an existing, readable directory: " + directory); } return attachFileOrDir(id, directory); } @Nonnull private ServiceFactory<C, S> attachFileOrDir(String id, @Nonnull File file) { ServiceFactory<C, S> copy = clone(); copy.attachedFiles.put(id, file); return copy; } /** * Returns a copy of this {@link ServiceFactory} with any attached files * removed. * * @since 4.0 */ @Nonnull public ServiceFactory<C, S> withoutAttachedFiles() { ServiceFactory<C, S> copy = clone(); copy.attachedFiles = emptyMap(); return copy; } /** * Returns the function that creates the shared context object. Each * Jet member creates one such object and passes it to all the parallel * service instances. * * @see #withCreateContextFn(FunctionEx) */ @Nonnull public FunctionEx<? super ProcessorSupplier.Context, ? extends C> createContextFn() { return createContextFn; } /** * Returns the function that creates the service object. There can be many * parallel service objects on each Jet member serving the same pipeline * stage, their number is determined by {@link * GeneralStage#setLocalParallelism(int) stage.localParallelism}. * * @see #withCreateServiceFn(BiFunctionEx) */ @Nonnull public BiFunctionEx<? super Processor.Context, ? super C, ? extends S> createServiceFn() { return createServiceFn; } /** * Returns the function that destroys the service object at the end of the * Jet job. * * @see #withDestroyServiceFn(ConsumerEx) */ @Nonnull public ConsumerEx<? super S> destroyServiceFn() { return destroyServiceFn; } /** * Returns the function that destroys the shared context object at the end * of the Jet job. * * @see #withDestroyContextFn(ConsumerEx) */ @Nonnull public ConsumerEx<? super C> destroyContextFn() { return destroyContextFn; } /** * Returns the {@code isCooperative} flag, see {@link #toNonCooperative()}. */ public boolean isCooperative() { return isCooperative; } /** * Returns the files and directories attached to this service factory. They * will become a part of the Jet job and available to {@link * #createContextFn()} as {@link ProcessorSupplier.Context#attachedFile * procSupplierContext.attachedFile(file.toString())} or * {@link ProcessorSupplier.Context#attachedDirectory * procSupplierContext.attachedDirectory(directory.toString())}. * * @since 4.0 */ @Nonnull public Map<String, File> attachedFiles() { return Collections.unmodifiableMap(attachedFiles); } @Override @SuppressWarnings("unchecked") protected ServiceFactory<C, S> clone() { try { ServiceFactory<C, S> copy = (ServiceFactory<C, S>) super.clone(); copy.attachedFiles = new HashMap<>(attachedFiles); return copy; } catch (CloneNotSupportedException e) { throw new JetException(getClass() + " is not cloneable", e); } } }
apache-2.0
MrYang/java-web-startup
src/main/java/com/zz/startup/security/SessionListener.java
585
package com.zz.startup.security; import org.apache.shiro.session.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SessionListener implements org.apache.shiro.session.SessionListener { private static Logger logger = LoggerFactory.getLogger(SessionListener.class); public void onStart(Session session) { logger.info("on start:{}" + session.getId()); } public void onStop(Session session) { logger.info("on stop:{}" + session.getId()); } public void onExpiration(Session session) { logger.info("on expiration:{}" + session.getId()); } }
apache-2.0
mkl-software/websuites
src/main/java/com/mkl/websuites/internal/command/impl/check/soft/SoftCheckSelectSelectedValueCommand.java
1654
/** * Copyright 2015 MKL Software * * 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.mkl.websuites.internal.command.impl.check.soft; import java.util.Map; import org.assertj.core.api.AbstractAssert; import com.mkl.websuites.command.CommandDescriptor; import com.mkl.websuites.internal.command.impl.check.AbstractCheck; import com.mkl.websuites.internal.command.impl.check.CheckSelectSelectedValueCommand; @CommandDescriptor(name = "softCheckSelectedValue", argumentTypes = {String.class, String.class}) public class SoftCheckSelectSelectedValueCommand extends CheckSelectSelectedValueCommand { public SoftCheckSelectSelectedValueCommand(Map<String, String> parameterMap) { super(parameterMap); } public SoftCheckSelectSelectedValueCommand(String selector, String expectedText) { super(selector, expectedText); } @Override protected AbstractCheck defineCheckLogic() { return new CheckSelectSelectedValue() { @Override protected AbstractAssert<?, ?> buildAssertion(Object... args) { return soft(args); } }; } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/InputSourceRequest.java
6925
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.medialive.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * Settings for for a PULL type input. * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/InputSourceRequest" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class InputSourceRequest implements Serializable, Cloneable, StructuredPojo { /** The key used to extract the password from EC2 Parameter store. */ private String passwordParam; /** * This represents the customer's source URL where stream is pulled from. */ private String url; /** The username for the input source. */ private String username; /** * The key used to extract the password from EC2 Parameter store. * * @param passwordParam * The key used to extract the password from EC2 Parameter store. */ public void setPasswordParam(String passwordParam) { this.passwordParam = passwordParam; } /** * The key used to extract the password from EC2 Parameter store. * * @return The key used to extract the password from EC2 Parameter store. */ public String getPasswordParam() { return this.passwordParam; } /** * The key used to extract the password from EC2 Parameter store. * * @param passwordParam * The key used to extract the password from EC2 Parameter store. * @return Returns a reference to this object so that method calls can be chained together. */ public InputSourceRequest withPasswordParam(String passwordParam) { setPasswordParam(passwordParam); return this; } /** * This represents the customer's source URL where stream is pulled from. * * @param url * This represents the customer's source URL where stream is pulled from. */ public void setUrl(String url) { this.url = url; } /** * This represents the customer's source URL where stream is pulled from. * * @return This represents the customer's source URL where stream is pulled from. */ public String getUrl() { return this.url; } /** * This represents the customer's source URL where stream is pulled from. * * @param url * This represents the customer's source URL where stream is pulled from. * @return Returns a reference to this object so that method calls can be chained together. */ public InputSourceRequest withUrl(String url) { setUrl(url); return this; } /** * The username for the input source. * * @param username * The username for the input source. */ public void setUsername(String username) { this.username = username; } /** * The username for the input source. * * @return The username for the input source. */ public String getUsername() { return this.username; } /** * The username for the input source. * * @param username * The username for the input source. * @return Returns a reference to this object so that method calls can be chained together. */ public InputSourceRequest withUsername(String username) { setUsername(username); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getPasswordParam() != null) sb.append("PasswordParam: ").append(getPasswordParam()).append(","); if (getUrl() != null) sb.append("Url: ").append(getUrl()).append(","); if (getUsername() != null) sb.append("Username: ").append(getUsername()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof InputSourceRequest == false) return false; InputSourceRequest other = (InputSourceRequest) obj; if (other.getPasswordParam() == null ^ this.getPasswordParam() == null) return false; if (other.getPasswordParam() != null && other.getPasswordParam().equals(this.getPasswordParam()) == false) return false; if (other.getUrl() == null ^ this.getUrl() == null) return false; if (other.getUrl() != null && other.getUrl().equals(this.getUrl()) == false) return false; if (other.getUsername() == null ^ this.getUsername() == null) return false; if (other.getUsername() != null && other.getUsername().equals(this.getUsername()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getPasswordParam() == null) ? 0 : getPasswordParam().hashCode()); hashCode = prime * hashCode + ((getUrl() == null) ? 0 : getUrl().hashCode()); hashCode = prime * hashCode + ((getUsername() == null) ? 0 : getUsername().hashCode()); return hashCode; } @Override public InputSourceRequest clone() { try { return (InputSourceRequest) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.medialive.model.transform.InputSourceRequestMarshaller.getInstance().marshall(this, protocolMarshaller); } }
apache-2.0
Geomatys/sis
core/sis-utility/src/main/java/org/apache/sis/util/Emptiable.java
2552
/* * 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.sis.util; /** * Interface of classes for which empty instances may exist. * This interface is typically used for filtering empty elements from a collection or a tree of objects. * Some examples of emptiable classes are: * * <ul> * <li>{@link org.apache.sis.measure.Range} when the lower bounds is equals to the upper bounds and at least * one bound is exclusive.</li> * <li>{@link org.apache.sis.metadata.AbstractMetadata} when no property value has been given to the metadata, * or all properties are themselves empty.</li> * <li>{@link org.apache.sis.geometry.AbstractEnvelope} when the span, surface or volume inside the envelope * is zero.</li> * </ul> * * SIS collections do <strong>not</strong> implement this interface even if they provide a {@code isEmpty()} method, * for consistency with collections in {@code java.util} and other libraries. This policy avoid duplicated calls to * {@code isEmpty()} methods when the caller need to check for both {@code Collection} and {@code Emptiable} interfaces. * * @author Martin Desruisseaux (Geomatys) * @version 0.4 * @since 0.4 * @module */ public interface Emptiable { /** * Returns {@code true} if this instance is empty. The definition of "emptiness" may vary between implementations. * For example {@link org.apache.sis.metadata.iso.extent.DefaultGeographicBoundingBox#isEmpty()} returns {@code true} * if all values are {@code NaN} (i.e. uninitialized) while {@link org.apache.sis.geometry.AbstractEnvelope#isEmpty()} * returns {@code true} if the geometric surface is zero. * * @return {@code true} if this instance is empty, or {@code false} otherwise. */ boolean isEmpty(); }
apache-2.0
liulinru13/YunLiao
app/src/main/java/com/mmrx/yunliao/presenter/util/L.java
1419
package com.mmrx.yunliao.presenter.util; import android.util.Log; /** * 创建人: mmrx * 时间: 16/3/7下午4:29 * 描述: 日志工具封装类 */ public class L { private L() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } public static boolean isDebug = true;// 是否需要打印bug,可以在application的onCreate函数里面初始化 private static final String TAG = "YunLiaoLog"; // 下面四个是默认tag的函数 public static void i(String msg) { if (isDebug) Log.i(TAG, msg); } public static void d(String msg) { if (isDebug) Log.d(TAG, msg); } public static void e(String msg) { if (isDebug) Log.e(TAG, msg); } public static void v(String msg) { if (isDebug) Log.v(TAG, msg); } // 下面是传入自定义tag的函数 public static void i(String tag, String msg) { if (isDebug) Log.i(tag, msg); } public static void d(String tag, String msg) { if (isDebug) Log.i(tag, msg); } public static void e(String tag, String msg) { if (isDebug) Log.i(tag, msg); } public static void v(String tag, String msg) { if (isDebug) Log.i(tag, msg); } }
apache-2.0
ryhal/cs263
src/main/java/cs263w16/MainPageServlet.java
442
package cs263w16; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Created by ryanhalbrook on 3/2/16. */ public class MainPageServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.sendRedirect("/html/main.html"); } }
apache-2.0
Nithanim/longbuffer
src/test/java/me/nithanim/longbuffer/IntegrationTest.java
75
package me.nithanim.longbuffer; public interface IntegrationTest { }
apache-2.0
codecentric/spring-boot-starter-batch-web
batch-web-spring-boot-autoconfigure/src/test/java/de/codecentric/batch/metrics/Item.java
1815
/* * Copyright 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 * * 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 de.codecentric.batch.metrics; import java.util.HashSet; import java.util.Set; /** * @author Tobias Flohre */ public class Item { private Action firstAction; private Action secondAction; private String description; private Long id; public Set<Action> getActions() { Set<Action> actions = new HashSet<>(); if (firstAction != null) { actions.add(firstAction); } if (secondAction != null) { actions.add(secondAction); } return actions; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Action getFirstAction() { return firstAction; } public void setFirstAction(Action firstAction) { this.firstAction = firstAction; } public Action getSecondAction() { return secondAction; } public void setSecondAction(Action secondAction) { this.secondAction = secondAction; } @Override public String toString() { return "Item [firstAction=" + firstAction + ", secondAction=" + secondAction + ", description=" + description + ", id=" + id + "]"; } }
apache-2.0
itachi1706/DroidEggs
app/src/main/java/com/itachi1706/droideggs/KitKatEgg/PlatLogoActivityKITKAT.java
6948
/* * Copyright (C) 2013 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.itachi1706.droideggs.KitKatEgg; import android.annotation.TargetApi; import android.content.ActivityNotFoundException; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.text.AllCapsTransformationMethod; import android.util.DisplayMetrics; import android.view.Gravity; import android.view.View; import android.view.animation.AccelerateInterpolator; import android.view.animation.AnticipateOvershootInterpolator; import android.view.animation.DecelerateInterpolator; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.itachi1706.droideggs.R; @TargetApi(19) public class PlatLogoActivityKITKAT extends AppCompatActivity { FrameLayout mContent; int mCount; final Handler mHandler = new Handler(); static final int BGCOLOR = 0xffed1d24; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Get the shard prefs SharedPreferences sp = this.getSharedPreferences("com.itachi1706.droideggs_preferences", MODE_MULTI_PROCESS); boolean currentBuild = sp.getBoolean("current_num", true); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); Typeface bold = Typeface.create("sans-serif", Typeface.BOLD); Typeface light = Typeface.create("sans-serif-light", Typeface.NORMAL); mContent = new FrameLayout(this); mContent.setBackgroundColor(0xC0000000); final FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); lp.gravity = Gravity.CENTER; final ImageView logo = new ImageView(this); logo.setImageResource(R.drawable.kk_platlogo); logo.setScaleType(ImageView.ScaleType.CENTER_INSIDE); logo.setVisibility(View.INVISIBLE); final View bg = new View(this); bg.setBackgroundColor(BGCOLOR); bg.setAlpha(0f); final TextView letter = new TextView(this); letter.setTypeface(bold); letter.setTextSize(200); letter.setTextColor(0xFFFFFFFF); letter.setGravity(Gravity.CENTER); if (currentBuild) letter.setText(String.valueOf(Build.ID).substring(0, 1)); else letter.setText("K"); final int p = (int)(4 * metrics.density); final TextView tv = new TextView(this); if (light != null) tv.setTypeface(light); tv.setTextSize(30); tv.setPadding(p, p, p, p); tv.setTextColor(0xFFFFFFFF); tv.setGravity(Gravity.CENTER); tv.setTransformationMethod(new AllCapsTransformationMethod(this)); if (currentBuild) tv.setText("Android " + Build.VERSION.RELEASE); else tv.setText("Android 4.4.4"); tv.setVisibility(View.INVISIBLE); mContent.addView(bg); mContent.addView(letter, lp); mContent.addView(logo, lp); final FrameLayout.LayoutParams lp2 = new FrameLayout.LayoutParams(lp); lp2.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL; lp2.bottomMargin = 10*p; mContent.addView(tv, lp2); mContent.setOnClickListener(new View.OnClickListener() { int clicks; @Override public void onClick(View v) { clicks++; if (clicks >= 6) { mContent.performLongClick(); return; } letter.animate().cancel(); final float offset = (int)letter.getRotation() % 360; letter.animate() .rotationBy((Math.random() > 0.5f ? 360 : -360) - offset) .setInterpolator(new DecelerateInterpolator()) .setDuration(700).start(); } }); mContent.setOnLongClickListener(v -> { if (logo.getVisibility() != View.VISIBLE) { bg.setScaleX(0.01f); bg.animate().alpha(1f).scaleX(1f).setStartDelay(500).start(); letter.animate().alpha(0f).scaleY(0.5f).scaleX(0.5f) .rotationBy(360) .setInterpolator(new AccelerateInterpolator()) .setDuration(1000) .start(); logo.setAlpha(0f); logo.setVisibility(View.VISIBLE); logo.setScaleX(0.5f); logo.setScaleY(0.5f); logo.animate().alpha(1f).scaleX(1f).scaleY(1f) .setDuration(1000).setStartDelay(500) .setInterpolator(new AnticipateOvershootInterpolator()) .start(); tv.setAlpha(0f); tv.setVisibility(View.VISIBLE); tv.animate().alpha(1f).setDuration(1000).setStartDelay(1000).start(); return true; } return false; }); logo.setOnLongClickListener(v -> { SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(PlatLogoActivityKITKAT.this); if (pref.getLong("K_EGG_MODE", 0) == 0){ // For posterity: the moment this user unlocked the easter egg pref.edit().putLong("K_EGG_MODE", System.currentTimeMillis()).apply(); } try { Intent dessertcase = new Intent(PlatLogoActivityKITKAT.this, DessertCase.class); dessertcase.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivity(dessertcase); } catch (ActivityNotFoundException ex) { android.util.Log.e("PlatLogoActivity", "Couldn't catch a break."); } finish(); return true; }); setContentView(mContent); } }
apache-2.0
WildanGarviandi/Bararaga
app/src/main/java/com/ragamania/bararaga/view/fragment/coaches/CoachesFragment.java
2888
package com.ragamania.bararaga.view.fragment.coaches; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import com.jcodecraeer.xrecyclerview.XRecyclerView; import com.ragamania.bararaga.R; import com.ragamania.bararaga.model.CoachesList; import com.ragamania.bararaga.view.activity.detail_list.DetailListActivity; import net.derohimat.baseapp.ui.fragment.BaseFragment; import net.derohimat.baseapp.ui.view.BaseRecyclerView; import java.util.List; import butterknife.Bind; /** * Created by wildangarviandi on 10/8/16. */ public class CoachesFragment extends BaseFragment implements CoachesMvpView { private static final String TAB_POSITION = "tab_position"; @Bind(R.id.recyclerview) BaseRecyclerView mRecyclerView; private CoachesPresenter mPresenter; private CoachesRecyclerAdapter mAdapter; public static CoachesFragment newInstance(int tabPosition) { CoachesFragment fragment = new CoachesFragment(); Bundle args = new Bundle(); args.putInt(TAB_POSITION, tabPosition); fragment.setArguments(args); return fragment; } @Override protected int getResourceLayout() { return R.layout.coaches_fragment; } @Override protected void onViewReady(@Nullable Bundle savedInstanceState) { setUpAdapter(); setUpRecyclerView(); setUpPresenter(); setHasOptionsMenu(true); } private void setUpAdapter() { mAdapter = new CoachesRecyclerAdapter(mContext); mAdapter.setOnItemClickListener((view, position) -> { gotoDetail(); }); } private void setUpRecyclerView() { LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setAdapter(mAdapter); mRecyclerView.setPullRefreshEnabled(true); mRecyclerView.setLoadingMoreEnabled(false); mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() { @Override public void onRefresh() { } @Override public void onLoadMore() { } }); } private void setUpPresenter() { mPresenter = new CoachesPresenter(getActivity()); mPresenter.attachView(this); mPresenter.loadCoachesList(); } @Override public void loadCoachesList(List<CoachesList> coachesList) { mAdapter.addAll(coachesList); mRecyclerView.refreshComplete(); } private void gotoDetail() { Intent i = new Intent(getActivity(), DetailListActivity.class); startActivity(i); getActivity().overridePendingTransition(0,0); } }
apache-2.0
wyona/yanel
src/resources/yanel-user/src/java/org/wyona/yanel/impl/resources/yaneluser/EditYanelUserProfileResource.java
16341
/* * Copyright 2010 - 2017 Wyona */ package org.wyona.yanel.impl.resources.yaneluser; import org.wyona.yanel.core.ResourceConfiguration; import org.wyona.yanel.core.util.MailUtil; import org.wyona.yanel.impl.resources.BasicXMLResource; import org.wyona.security.core.api.Identity; import org.wyona.security.core.api.User; import org.wyona.yanel.servlet.YanelServlet; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.wyona.commons.xml.XMLHelper; /** * A resource to edit/update the profile of a user */ public class EditYanelUserProfileResource extends BasicXMLResource { private static Logger log = LogManager.getLogger(EditYanelUserProfileResource.class); private String transformerParameterName; private String transformerParameterValue; private static final String USER_PROP_NAME = "user"; /* * @see org.wyona.yanel.impl.resources.BasicXMLResource#getContentXML(String) */ protected InputStream getContentXML(String viewId) throws Exception { if (log.isDebugEnabled()) { log.debug("requested viewId: " + viewId); } String oldPassword = getEnvironment().getRequest().getParameter("oldPassword"); if (oldPassword != null) { String newPassword = getEnvironment().getRequest().getParameter("newPassword"); String newPasswordConfirmed = getEnvironment().getRequest().getParameter("newPasswordConfirmation"); updatePassword(oldPassword, newPassword, newPasswordConfirmed); } String email = getEnvironment().getRequest().getParameter("email"); boolean emailUpdated = false; if (email != null) { emailUpdated = updateProfile(email); log.info("Email '" + email + "' has been updated: " + emailUpdated); } try { return getXMLAsStream(emailUpdated); } catch(Exception e) { log.error(e, e); return null; } } /** * Get user profile as XML as stream * @param emailUpdated Flag whether email got updated successfully */ private java.io.InputStream getXMLAsStream(boolean emailUpdated) throws Exception { String userId = getUserId(); if (userId != null) { Document doc = getUserProfile(userId, emailUpdated); return XMLHelper.getInputStream(doc, false, true, null); } else { return new java.io.StringBufferInputStream("<no-user-id/>"); } } /** * Get user profile as DOM XML * @param userID ID of user * @param emailUpdated Flag whether email got updated successfully */ protected Document getUserProfile(String userId, boolean emailUpdated) throws Exception { User user = realm.getIdentityManager().getUserManager().getUser(userId); Document doc = XMLHelper.createDocument(null, "user"); Element rootEl = doc.getDocumentElement(); rootEl.setAttribute("id", userId); rootEl.setAttribute("email", user.getEmail()); rootEl.setAttribute("lamguage", user.getLanguage()); // DEPRECATED rootEl.setAttribute("language", user.getLanguage()); if (emailUpdated) { rootEl.setAttribute("email-saved-successfully", "true"); } Element nameEl = doc.createElement("name"); nameEl.setTextContent(user.getName()); rootEl.appendChild(nameEl); Element realmEl = doc.createElement("realm"); rootEl.appendChild(realmEl); String[] languages = getRealm().getLanguages(); if (languages != null && languages.length > 0) { Element supportedLanguagesEl = doc.createElement("languages"); // TODO: Set default language String defaultLanguage = getRealm().getDefaultLanguage(); realmEl.appendChild(supportedLanguagesEl); for (int i = 0; i < languages.length; i++) { Element languageEl = doc.createElement("language"); languageEl.setTextContent(languages[i]); supportedLanguagesEl.appendChild(languageEl); } } Element expirationDateEl = doc.createElement("expiration-date"); expirationDateEl.setTextContent("" + user.getExpirationDate()); rootEl.appendChild(expirationDateEl); Element descEl = doc.createElement("description"); descEl.setTextContent("" + user.getDescription()); rootEl.appendChild(descEl); org.wyona.security.core.api.Group[] groups = user.getGroups(); if (groups != null && groups.length > 0) { Element groupsEl = doc.createElement("groups"); rootEl.appendChild(groupsEl); for (int i = 0; i < groups.length; i++) { Element groupEl = doc.createElement("group"); groupEl.setAttribute("id", groups[i].getID()); groupsEl.appendChild(groupEl); } } String[] aliases = user.getAliases(); if (aliases != null && aliases.length > 0) { Element aliasesEl = (Element) rootEl.appendChild(doc.createElement("aliases")); for (int i = 0; i < aliases.length; i++) { Element aliasEl = (Element) aliasesEl.appendChild(doc.createElement("alias")); aliasEl.appendChild(doc.createTextNode(aliases[i])); } } else { rootEl.appendChild(doc.createElement("no-aliases")); } org.wyona.security.core.UserHistory history = user.getHistory(); if (history != null) { java.util.List<org.wyona.security.core.UserHistory.HistoryEntry> entries = history.getHistory(); if (entries != null) { for (org.wyona.security.core.UserHistory.HistoryEntry entry: entries) { Element historyEl = (Element) rootEl.appendChild(doc.createElement("history")); Element eventEl = (Element) historyEl.appendChild(doc.createElement("event")); eventEl.setAttribute("usecase", entry.getUsecase()); eventEl.setAttribute("description", entry.getDescription()); eventEl.setAttribute("date", "" + entry.getDate()); } } } return doc; } /** * Get user ID, whereas check various options, such as 1) query string, 2) resource configuration, 3) URL and 4) session */ protected String getUserId() throws Exception { String userId = null; // 1) userId = getEnvironment().getRequest().getParameter("id"); if (userId != null) { return userId; /* if (getRealm().getPolicyManager().authorize("/yanel/users/" + userId + ".html", getEnvironment().getIdentity(), new org.wyona.security.core.api.Usecase("view"))) { // INFO: Because the policymanager has no mean to check (or interpret) query strings we need to recheck programmatically return userId; } else { //throw new Exception("User '" + getEnvironment().getIdentity().getUsername() + "' tries to access user profile '" + userId + "', but is not authorized!"); log.warn("User '" + getEnvironment().getIdentity().getUsername() + "' tries to access user profile '" + userId + "', but is not authorized!"); } */ } else { log.debug("User ID is not part of query string."); } // 2) userId = getResourceConfigProperty(USER_PROP_NAME); if (userId != null) { return userId; } else { log.debug("User ID is not configured inside resource configuration."); } // 3) userId = getPath().substring(getPath().lastIndexOf("/") + 1, getPath().lastIndexOf(".html")); if (userId != null && getRealm().getIdentityManager().getUserManager().existsUser(userId)) { return userId; } else { log.debug("Could not retrieve user ID from URL."); } // 4) userId = getEnvironment().getIdentity().getUsername(); if (userId != null) { return userId; } else { log.warn("User does not seem to be signed in!"); } throw new Exception("Cannot retrieve user ID!"); } /** * Change user password * @param oldPassword Existing current password */ protected void updatePassword(String oldPassword, String newPassword, String newPasswordConfirmed) throws Exception { String userId = getUserId(); if (!getRealm().getIdentityManager().getUserManager().getUser(userId).authenticate(oldPassword)) { setTransformerParameter("error", "Authentication of user '" +userId + "' failed!"); log.error("Authentication of user '" + userId + "' failed!"); return; } if (newPassword != null && !newPassword.equals("")) { if (newPassword.equals(newPasswordConfirmed)) { User user = getRealm().getIdentityManager().getUserManager().getUser(userId); user.setPassword(newPassword); user.save(); setTransformerParameter("success", "Password updated successfully"); } else { setTransformerParameter("error", "New password and its confirmation do not match!"); } } else { setTransformerParameter("error", "No new password was specified!"); } } /** * Update the email address (and possibly also the alias) inside user profile * @param email New email address of user (and possibly also alias) * @return true if update was successful and false otherwise */ protected boolean updateProfile(String email) throws Exception { if (email == null || ("").equals(email)) { setTransformerParameter("error", "emailNotSet"); log.warn("No email (or empty email) specified, hence do not update email address!"); return false; } else if (!validateEmail(email)) { setTransformerParameter("error", "emailNotValid"); log.warn("Email '" + email + "' is not valid!"); return false; } else { try { String userId = getUserId(); org.wyona.security.core.api.UserManager userManager = realm.getIdentityManager().getUserManager(); User user = userManager.getUser(userId); user.setName(getEnvironment().getRequest().getParameter("userName")); user.setLanguage(getEnvironment().getRequest().getParameter("user-profile-language")); user.save(); updateSession(user); String previousEmailAddress = user.getEmail(); if (!previousEmailAddress.equals(email)) { user.setEmail(email); user.save(); if (userManager.existsAlias(previousEmailAddress)) { if (!userManager.existsAlias(email)) { userManager.createAlias(email, userId); } else { if (hasAlias(user, email)) { log.warn("DEBUG: User '" + userId + "' already has alias '" + email + "'."); } else { throw new Exception("Alias '" + email + "' already exists, but is not associated with user '" + userId + "'!"); } } if (hasAlias(user, previousEmailAddress)) { userManager.removeAlias(previousEmailAddress); log.warn("Previous alias '" + previousEmailAddress + "' removed, which means user needs to use new email '" + email + "' to login."); sendNotification(previousEmailAddress, email); // TODO/TBD: Logout user and tell user why he/she was signed out } } else { log.warn("Previous email '" + previousEmailAddress + "' was not used as alias, hence we also use new email '" + email + "' not as alias."); } } else { log.warn("DEBUG: Current email and new email are the same."); if (!userManager.existsAlias(email)) { log.warn("Email '" + email + "' is not used as alias yet!"); } } setTransformerParameter("success", "E-Mail (and alias) updated successfully"); return true; } catch (Exception e) { log.error(e, e); setTransformerParameter("error", e.getMessage()); return false; } } } /** * Send notifications to previous and new emails that login alias has changed */ private void sendNotification(String previousEmail, String newEmail) throws Exception { String from = getResourceConfigProperty("fromEmail"); if (from != null) { String subject = "[" + getRealm().getName() + "] Username changed"; String body = "Please note that you must use '" + newEmail + "' instead '" + previousEmail + "' to login."; try { MailUtil.send(from, previousEmail, subject, body); } catch(Exception e) { log.error(e, e); } try { MailUtil.send(from, newEmail, subject, body); } catch(Exception e) { log.error(e, e); } } else { log.warn("No 'from' email address inside resource configuration set, hence no notifications about changed username will be sent!"); } } /** * Update identity attached to session */ private void updateSession(User user) throws Exception { YanelServlet.setIdentity(new Identity(user, user.getEmail()), getEnvironment().getRequest().getSession(true), getRealm()); } /** * Check whether user has a specific alias * @return true when user has a specific alias */ private boolean hasAlias(User user, String alias) throws Exception { String[] aliases = user.getAliases(); for (int i = 0; i < aliases.length; i++) { if (aliases[i].equals(alias)) { return true; } } return false; } /** * */ private void setTransformerParameter(String name, String value) { transformerParameterName = name; transformerParameterValue = value; } /** * @see org.wyona.yanel.impl.resources.BasicXMLResource#passTransformerParameters(Transformer) */ @Override protected void passTransformerParameters(javax.xml.transform.Transformer transformer) throws Exception { super.passTransformerParameters(transformer); try { if (transformerParameterName != null && transformerParameterValue != null) { transformer.setParameter(transformerParameterName, transformerParameterValue); transformerParameterName = null; transformerParameterValue = null; } } catch (Exception e) { log.error(e, e); } } /** * This method checks if the specified email is valid against a regex * * @param email * @return true if email is valid */ private boolean validateEmail(String email) { String emailRegEx = "(\\w+)@(\\w+\\.)(\\w+)(\\.\\w+)*"; Pattern pattern = Pattern.compile(emailRegEx); Matcher matcher = pattern.matcher(email); return matcher.find(); } }
apache-2.0
glomie/xcuber-boot
src/main/java/com/xcuber/dao/StudentDao.java
123
package com.xcuber.dao; import com.xcuber.model.Student; public interface StudentDao { Student findById(Long id); }
apache-2.0
dsarlis/datix
streamnet/src/main/java/gr/ntua/cslab/streamnet/kdtree/KdTree.java
4972
package gr.ntua.cslab.streamnet.kdtree; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; /** * */ public class KdTree<T> extends KdNode<T> { private static final long serialVersionUID = -4403464702046042517L; public KdTree(int dimensions) { this(dimensions, 24); } public KdTree(int dimensions, int bucketCapacity) { super(dimensions, bucketCapacity); } public KdTree(BufferedReader br) throws IOException { super(br); } public NearestNeighborIterator<T> getNearestNeighborIterator(double[] searchPoint, int maxPointsReturned, DistanceFunction distanceFunction) { return new NearestNeighborIterator<T>(this, searchPoint, maxPointsReturned, distanceFunction); } public MaxHeap<T> findNearestNeighbors(double[] searchPoint, int maxPointsReturned, DistanceFunction distanceFunction) { BinaryHeap.Min<KdNode<T>> pendingPaths = new BinaryHeap.Min<KdNode<T>>(); BinaryHeap.Max<T> evaluatedPoints = new BinaryHeap.Max<T>(); int pointsRemaining = Math.min(maxPointsReturned, size()); pendingPaths.offer(0, this); while (pendingPaths.size() > 0 && (evaluatedPoints.size() < pointsRemaining || (pendingPaths.getMinKey() < evaluatedPoints.getMaxKey()))) { nearestNeighborSearchStep(pendingPaths, evaluatedPoints, pointsRemaining, distanceFunction, searchPoint); } return evaluatedPoints; } @SuppressWarnings("unchecked") protected static <T> void nearestNeighborSearchStep ( MinHeap<KdNode<T>> pendingPaths, MaxHeap<T> evaluatedPoints, int desiredPoints, DistanceFunction distanceFunction, double[] searchPoint) { // If there are pending paths possibly closer than the nearest evaluated point, check it out KdNode<T> cursor = pendingPaths.getMin(); pendingPaths.removeMin(); // Descend the tree, recording paths not taken while (!cursor.isLeaf()) { KdNode<T> pathNotTaken; if (searchPoint[cursor.splitDimension] > cursor.splitValue) { pathNotTaken = cursor.left; cursor = cursor.right; } else { pathNotTaken = cursor.right; cursor = cursor.left; } double otherDistance = distanceFunction.distanceToRect(searchPoint, pathNotTaken.minBound, pathNotTaken.maxBound); // Only add a path if we either need more points or it's closer than furthest point on list so far if (evaluatedPoints.size() < desiredPoints || otherDistance <= evaluatedPoints.getMaxKey()) { pendingPaths.offer(otherDistance, pathNotTaken); } } if (cursor.singlePoint) { double nodeDistance = distanceFunction.distance(cursor.points[0], searchPoint); // Only add a point if either need more points or it's closer than furthest on list so far if (evaluatedPoints.size() < desiredPoints || nodeDistance <= evaluatedPoints.getMaxKey()) { for (int i = 0; i < cursor.size(); i++) { T value = (T) cursor.data[i]; // If we don't need any more, replace max if (evaluatedPoints.size() == desiredPoints) { evaluatedPoints.replaceMax(nodeDistance, value); } else { evaluatedPoints.offer(nodeDistance, value); } } } } else { // Add the points at the cursor for (int i = 0; i < cursor.size(); i++) { double[] point = cursor.points[i]; T value = (T) cursor.data[i]; double distance = distanceFunction.distance(point, searchPoint); // Only add a point if either need more points or it's closer than furthest on list so far if (evaluatedPoints.size() < desiredPoints) { evaluatedPoints.offer(distance, value); } else if (distance < evaluatedPoints.getMaxKey()) { evaluatedPoints.replaceMax(distance, value); } } } } public int find(double[] point) { /*System.out.print("Finding point: "); for (int i = 0; i < point.length; i++) { System.out.print(point[i]+" "); } System.out.println();*/ return find1(point); } public boolean isLeaf(int id) { return isLeaf1(id); } public synchronized double[] performSplit(int id) { KdNode<T> cursor = calculateSplit(id); if (cursor != null) return splitLeafNode(cursor); else return new double[]{-1, -1, -1, -1, -1}; } public void printTree(BufferedWriter writer) throws IOException { writer.write(this.dimensions +" "+this.bucketCapacity+"\n"); this.printTree1(writer); writer.close(); } }
apache-2.0
piggsoft/school
school-webapp/src/main/java/com/piggsoft/school/web/spring/intercepter/ExecuteTimeInterceptor.java
1875
package com.piggsoft.school.web.spring.intercepter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class ExecuteTimeInterceptor implements HandlerInterceptor { private static final Logger logger = LoggerFactory .getLogger(ExecuteTimeInterceptor.class); private static final String REQUEST_START_TIME = ExecuteTimeInterceptor.class.getName() + "." + "startTime"; // before the actual handler will be executed @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { long startTime = System.currentTimeMillis(); request.setAttribute(REQUEST_START_TIME, startTime); return true; } // after the handler is executed @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { long startTime = (Long) request.getAttribute(REQUEST_START_TIME); long endTime = System.currentTimeMillis(); long executeTime = endTime - startTime; // log it if (logger.isDebugEnabled()) { logger.debug("[" + handler + "] executeTime : " + executeTime + "ms"); } } /* (non-Javadoc) * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception) */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { if (null != ex) { logger.error(ex.getMessage(), ex); } } }
apache-2.0
kdgregory/pathfinder
lib-spring/src/test/java/com/kdgregory/pathfinder/spring/AbstractSpringTestcase.java
1657
// Copyright (c) Keith D Gregory // // 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.kdgregory.pathfinder.spring; import org.apache.log4j.Logger; import com.kdgregory.pathfinder.core.PathRepo; import com.kdgregory.pathfinder.core.WarMachine; import com.kdgregory.pathfinder.core.impl.PathRepoImpl; import com.kdgregory.pathfinder.servlet.ServletInspector; import com.kdgregory.pathfinder.util.TestHelpers; /** * Common functionality and data for the Spring tests. */ public abstract class AbstractSpringTestcase { protected Logger logger = Logger.getLogger(getClass()); protected static WarMachine machine; protected PathRepo pathRepo; //---------------------------------------------------------------------------- // Support code //---------------------------------------------------------------------------- protected void processWar(String warName) throws Exception { machine = TestHelpers.createWarMachine(warName); pathRepo = new PathRepoImpl(); new ServletInspector().inspect(machine, pathRepo); new SpringInspector().inspect(machine, pathRepo); } }
apache-2.0
OpenUniversity/ovirt-engine
backend/manager/modules/restapi/jaxrs/src/main/java/org/ovirt/engine/api/restapi/resource/BackendStorageDomainServerConnectionsResource.java
2648
package org.ovirt.engine.api.restapi.resource; import java.util.List; import javax.ws.rs.core.Response; import org.ovirt.engine.api.model.StorageConnection; import org.ovirt.engine.api.model.StorageConnections; import org.ovirt.engine.api.resource.StorageDomainServerConnectionResource; import org.ovirt.engine.api.resource.StorageDomainServerConnectionsResource; import org.ovirt.engine.core.common.action.AttachDetachStorageConnectionParameters; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.businessentities.StorageServerConnections; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.common.queries.VdcQueryType; import org.ovirt.engine.core.compat.Guid; public class BackendStorageDomainServerConnectionsResource extends AbstractBackendCollectionResource<StorageConnection, StorageServerConnections> implements StorageDomainServerConnectionsResource { Guid storageDomainId = null; public BackendStorageDomainServerConnectionsResource(Guid storageDomainId) { super(StorageConnection.class, StorageServerConnections.class); this.storageDomainId = storageDomainId; } @Override public StorageConnections list() { List<StorageServerConnections> connections = getConnections(); return mapCollection(connections); } protected List<StorageServerConnections> getConnections() { return getEntity(List.class, VdcQueryType.GetStorageServerConnectionsForDomain, new IdQueryParameters(storageDomainId), "storage domain: id=" + storageDomainId); } private StorageConnections mapCollection(List<StorageServerConnections> entities) { StorageConnections collection = new StorageConnections(); for (StorageServerConnections entity : entities) { StorageConnection connection = map(entity); if (connection != null) { collection.getStorageConnections().add(addLinks(populate(connection, entity))); } } return collection; } @Override public Response add(StorageConnection storageConnection) { validateParameters(storageConnection, "id"); return performAction(VdcActionType.AttachStorageConnectionToStorageDomain, new AttachDetachStorageConnectionParameters(storageDomainId, storageConnection.getId())); } @Override public StorageDomainServerConnectionResource getConnectionResource(String id) { return inject(new BackendStorageDomainServerConnectionResource(id, this)); } }
apache-2.0
uchoice/exf
exf-core/src/main/java/net/uchoice/exf/core/runtime/resolver/advisor/SpringVariableAdvisor.java
1721
package net.uchoice.exf.core.runtime.resolver.advisor; import net.uchoice.exf.client.exception.ErrorMessage; import net.uchoice.exf.client.exception.ExfRuntimeException; import net.uchoice.exf.core.trace.ExfTracker; import net.uchoice.exf.core.trace.Record; import net.uchoice.exf.core.trace.RecordType; import net.uchoice.exf.core.util.SpringApplicationContextHolder; import net.uchoice.exf.model.variable.Variable; import net.uchoice.exf.model.variable.VariableAdvisor; import org.apache.commons.lang.StringUtils; public class SpringVariableAdvisor implements VariableAdvisor { private static final String PARTTEN = "spring:"; private static SpringVariableAdvisor instance; @Override public Object evaluate(Variable variable) { ExfTracker.start(Record.create(RecordType.VARIABLE, getClass().getName()).addInput(variable)); try { Object result = SpringApplicationContextHolder.getSpringBean(variable.getValue().replace(PARTTEN, ""), variable.getVariableSpec().getType()); ExfTracker.stop(result); return result; } catch (Throwable e) { ErrorMessage error = ErrorMessage.code("C-EXF-02-01-008", variable.getVariableSpec(), variable.getValue()); ExfTracker.success(false, error.getErrorMessage()); ExfTracker.stop(); throw new ExfRuntimeException(error, e); } } @Override public boolean accept(Variable variable) { if (null == variable || StringUtils.isBlank(variable.getValue()) || null == variable.getVariableSpec()) { return false; } if (variable.getValue().startsWith(PARTTEN)) { return true; } return false; } public static SpringVariableAdvisor get() { if (null == instance) { instance = new SpringVariableAdvisor(); } return instance; } }
apache-2.0
velsubra/Tamil
ezhuththu/src/main/java/my/interest/lang/tamil/impl/rx/asai2/TheamaRx.java
403
package my.interest.lang.tamil.impl.rx.asai2; import my.interest.lang.tamil.impl.FeatureSet; import my.interest.lang.tamil.impl.yaappu.YaappuBaseRx; /** * <p> * </p> * * @author velsubra */ public class TheamaRx extends YaappuBaseRx { public TheamaRx() { super("தேமா"); } public String generate(FeatureSet featureSet) { return "(?:(?:${ntear}){2})"; } }
apache-2.0
danaklein142/ml-temp
src/main/java/org/moonlightcontroller/blocks/RegexClassifier.java
1902
package org.moonlightcontroller.blocks; import org.moonlightcontroller.processing.ProcessingBlock; import org.openboxprotocol.protocol.Priority; import java.util.List; import java.util.Map; import org.moonlightcontroller.aggregator.Tupple.Pair; import org.moonlightcontroller.exceptions.MergeException; import org.moonlightcontroller.processing.BlockClass; import org.moonlightcontroller.processing.IProcessingGraph; public class RegexClassifier extends ProcessingBlock implements IClassifierProcessingBlock{ private String[] pattern; private boolean payload_only; private Priority priority; public RegexClassifier(String id, String[] pattern, Priority priority) { super(id); this.pattern = pattern; this.priority = priority; } public RegexClassifier(String id, String[] pattern, boolean payload_only, Priority priority) { super(id); this.pattern = pattern; this.payload_only = payload_only; } public String[] getPattern() { return pattern; } public boolean getPayload_only() { return payload_only; } @Override public BlockClass getBlockClass() { return BlockClass.BLOCK_CLASS_CLASSIFIER; } @Override protected void putConfiguration(Map<String, String> config) { config.put("pattern", this.pattern.toString()); config.put("payload_only", this.payload_only? "true" : "false"); } @Override protected ProcessingBlock spawn(String id) { return new RegexClassifier(id, pattern, payload_only, priority); } @Override public Priority getPriority() { return priority; } @Override public boolean canMergeWith(IClassifierProcessingBlock other) { // TODO Auto-generated method stub return false; } @Override public IClassifierProcessingBlock mergeWith(IClassifierProcessingBlock other, IProcessingGraph containingGraph, List<Pair<Integer>> outPortSources) throws MergeException { // TODO Auto-generated method stub return null; } }
apache-2.0
CChengz/dot.r
workspace/fits/demo/src/main/java/ac/uk/abdn/fits/demo/gmap/model/polygon/stdlib/StdDraw.java
41726
package ac.uk.abdn.fits.demo.gmap.model.polygon.stdlib; /************************************************************************* * Compilation: javac StdDraw.java * Execution: java StdDraw * * Standard drawing library. This class provides a basic capability for * creating drawings with your programs. It uses a simple graphics model that * allows you to create drawings consisting of points, lines, and curves * in a window on your computer and to save the drawings to a file. * * Todo * ---- * - Add support for gradient fill, etc. * * Remarks * ------- * - don't use AffineTransform for rescaling since it inverts * images and strings * - careful using setFont in inner loop within an animation - * it can cause flicker * *************************************************************************/ import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.awt.image.*; import java.io.*; import java.net.*; import java.util.LinkedList; import java.util.TreeSet; import javax.imageio.ImageIO; import javax.swing.*; /** * <i>Standard draw</i>. This class provides a basic capability for * creating drawings with your programs. It uses a simple graphics model that * allows you to create drawings consisting of points, lines, and curves * in a window on your computer and to save the drawings to a file. * <p> * For additional documentation, see <a href="http://introcs.cs.princeton.edu/15inout">Section 1.5</a> of * <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public final class StdDraw implements ActionListener, MouseListener, MouseMotionListener, KeyListener { // pre-defined colors public static final Color BLACK = Color.BLACK; public static final Color BLUE = Color.BLUE; public static final Color CYAN = Color.CYAN; public static final Color DARK_GRAY = Color.DARK_GRAY; public static final Color GRAY = Color.GRAY; public static final Color GREEN = Color.GREEN; public static final Color LIGHT_GRAY = Color.LIGHT_GRAY; public static final Color MAGENTA = Color.MAGENTA; public static final Color ORANGE = Color.ORANGE; public static final Color PINK = Color.PINK; public static final Color RED = Color.RED; public static final Color WHITE = Color.WHITE; public static final Color YELLOW = Color.YELLOW; /** * Shade of blue used in Introduction to Programming in Java. * It is Pantone 300U. The RGB values are approximately (9, 90, 166). */ public static final Color BOOK_BLUE = new Color( 9, 90, 166); public static final Color BOOK_LIGHT_BLUE = new Color(103, 198, 243); /** * Shade of red used in Algorithms 4th edition. * It is Pantone 1805U. The RGB values are approximately (150, 35, 31). */ public static final Color BOOK_RED = new Color(150, 35, 31); // default colors private static final Color DEFAULT_PEN_COLOR = BLACK; private static final Color DEFAULT_CLEAR_COLOR = WHITE; // current pen color private static Color penColor; // default canvas size is DEFAULT_SIZE-by-DEFAULT_SIZE private static final int DEFAULT_SIZE = 512; private static int width = DEFAULT_SIZE; private static int height = DEFAULT_SIZE; // default pen radius private static final double DEFAULT_PEN_RADIUS = 0.002; // current pen radius private static double penRadius; // show we draw immediately or wait until next show? private static boolean defer = false; // boundary of drawing canvas, 5% border private static final double BORDER = 0.05; private static final double DEFAULT_XMIN = 0.0; private static final double DEFAULT_XMAX = 1.0; private static final double DEFAULT_YMIN = 0.0; private static final double DEFAULT_YMAX = 1.0; private static double xmin, ymin, xmax, ymax; // for synchronization private static Object mouseLock = new Object(); private static Object keyLock = new Object(); // default font private static final Font DEFAULT_FONT = new Font("SansSerif", Font.PLAIN, 16); // current font private static Font font; // double buffered graphics private static BufferedImage offscreenImage, onscreenImage; private static Graphics2D offscreen, onscreen; // singleton for callbacks: avoids generation of extra .class files private static StdDraw std = new StdDraw(); // the frame for drawing to the screen private static JFrame frame; // mouse state private static boolean mousePressed = false; private static double mouseX = 0; private static double mouseY = 0; // queue of typed key characters private static LinkedList<Character> keysTyped = new LinkedList<Character>(); // set of key codes currently pressed down private static TreeSet<Integer> keysDown = new TreeSet<Integer>(); // singleton pattern: client can't instantiate private StdDraw() { } // static initializer static { init(); } /** * Set the window size to the default size 512-by-512 pixels. */ public static void setCanvasSize() { setCanvasSize(DEFAULT_SIZE, DEFAULT_SIZE); } /** * Set the window size to w-by-h pixels. * * @param w the width as a number of pixels * @param h the height as a number of pixels * @throws a IllegalArgumentException if the width or height is 0 or negative */ public static void setCanvasSize(int w, int h) { if (w < 1 || h < 1) throw new IllegalArgumentException("width and height must be positive"); width = w; height = h; init(); } // init private static void init() { if (frame != null) frame.setVisible(false); frame = new JFrame(); offscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); onscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); offscreen = offscreenImage.createGraphics(); onscreen = onscreenImage.createGraphics(); setXscale(); setYscale(); offscreen.setColor(DEFAULT_CLEAR_COLOR); offscreen.fillRect(0, 0, width, height); setPenColor(); setPenRadius(); setFont(); clear(); // add antialiasing RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); offscreen.addRenderingHints(hints); // frame stuff ImageIcon icon = new ImageIcon(onscreenImage); JLabel draw = new JLabel(icon); draw.addMouseListener(std); draw.addMouseMotionListener(std); frame.setContentPane(draw); frame.addKeyListener(std); // JLabel cannot get keyboard focus frame.setResizable(false); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // closes all windows // frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // closes only current window frame.setTitle("Standard Draw"); frame.setJMenuBar(createMenuBar()); frame.pack(); frame.requestFocusInWindow(); frame.setVisible(true); } // create the menu bar (changed to private) private static JMenuBar createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("File"); menuBar.add(menu); JMenuItem menuItem1 = new JMenuItem(" Save... "); menuItem1.addActionListener(std); menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); menu.add(menuItem1); return menuBar; } /************************************************************************* * User and screen coordinate systems *************************************************************************/ /** * Set the x-scale to be the default (between 0.0 and 1.0). */ public static void setXscale() { setXscale(DEFAULT_XMIN, DEFAULT_XMAX); } /** * Set the y-scale to be the default (between 0.0 and 1.0). */ public static void setYscale() { setYscale(DEFAULT_YMIN, DEFAULT_YMAX); } /** * Set the x-scale (a 10% border is added to the values) * @param min the minimum value of the x-scale * @param max the maximum value of the x-scale */ public static void setXscale(double min, double max) { double size = max - min; synchronized (mouseLock) { xmin = min - BORDER * size; xmax = max + BORDER * size; } } /** * Set the y-scale (a 10% border is added to the values). * @param min the minimum value of the y-scale * @param max the maximum value of the y-scale */ public static void setYscale(double min, double max) { double size = max - min; synchronized (mouseLock) { ymin = min - BORDER * size; ymax = max + BORDER * size; } } /** * Set the x-scale and y-scale (a 10% border is added to the values) * @param min the minimum value of the x- and y-scales * @param max the maximum value of the x- and y-scales */ public static void setScale(double min, double max) { double size = max - min; synchronized (mouseLock) { xmin = min - BORDER * size; xmax = max + BORDER * size; ymin = min - BORDER * size; ymax = max + BORDER * size; } } // helper functions that scale from user coordinates to screen coordinates and back private static double scaleX(double x) { return width * (x - xmin) / (xmax - xmin); } private static double scaleY(double y) { return height * (ymax - y) / (ymax - ymin); } private static double factorX(double w) { return w * width / Math.abs(xmax - xmin); } private static double factorY(double h) { return h * height / Math.abs(ymax - ymin); } private static double userX(double x) { return xmin + x * (xmax - xmin) / width; } private static double userY(double y) { return ymax - y * (ymax - ymin) / height; } /** * Clear the screen to the default color (white). */ public static void clear() { clear(DEFAULT_CLEAR_COLOR); } /** * Clear the screen to the given color. * @param color the Color to make the background */ public static void clear(Color color) { offscreen.setColor(color); offscreen.fillRect(0, 0, width, height); offscreen.setColor(penColor); draw(); } /** * Get the current pen radius. */ public static double getPenRadius() { return penRadius; } /** * Set the pen size to the default (.002). */ public static void setPenRadius() { setPenRadius(DEFAULT_PEN_RADIUS); } /** * Set the radius of the pen to the given size. * @param r the radius of the pen * @throws IllegalArgumentException if r is negative */ public static void setPenRadius(double r) { if (r < 0) throw new IllegalArgumentException("pen radius must be nonnegative"); penRadius = r; float scaledPenRadius = (float) (r * DEFAULT_SIZE); BasicStroke stroke = new BasicStroke(scaledPenRadius, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); // BasicStroke stroke = new BasicStroke(scaledPenRadius); offscreen.setStroke(stroke); } /** * Get the current pen color. */ public static Color getPenColor() { return penColor; } /** * Set the pen color to the default color (black). */ public static void setPenColor() { setPenColor(DEFAULT_PEN_COLOR); } /** * Set the pen color to the given color. The available pen colors are * BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA, * ORANGE, PINK, RED, WHITE, and YELLOW. * @param color the Color to make the pen */ public static void setPenColor(Color color) { penColor = color; offscreen.setColor(penColor); } /** * Set the pen color to the given RGB color. * @param red the amount of red (between 0 and 255) * @param green the amount of green (between 0 and 255) * @param blue the amount of blue (between 0 and 255) * @throws IllegalArgumentException if the amount of red, green, or blue are outside prescribed range */ public static void setPenColor(int red, int green, int blue) { if (red < 0 || red >= 256) throw new IllegalArgumentException("amount of red must be between 0 and 255"); if (green < 0 || green >= 256) throw new IllegalArgumentException("amount of red must be between 0 and 255"); if (blue < 0 || blue >= 256) throw new IllegalArgumentException("amount of red must be between 0 and 255"); setPenColor(new Color(red, green, blue)); } /** * Get the current font. */ public static Font getFont() { return font; } /** * Set the font to the default font (sans serif, 16 point). */ public static void setFont() { setFont(DEFAULT_FONT); } /** * Set the font to the given value. * @param f the font to make text */ public static void setFont(Font f) { font = f; } /************************************************************************* * Drawing geometric shapes. *************************************************************************/ /** * Draw a line from (x0, y0) to (x1, y1). * @param x0 the x-coordinate of the starting point * @param y0 the y-coordinate of the starting point * @param x1 the x-coordinate of the destination point * @param y1 the y-coordinate of the destination point */ public static void line(double x0, double y0, double x1, double y1) { offscreen.draw(new Line2D.Double(scaleX(x0), scaleY(y0), scaleX(x1), scaleY(y1))); draw(); } /** * Draw one pixel at (x, y). * @param x the x-coordinate of the pixel * @param y the y-coordinate of the pixel */ private static void pixel(double x, double y) { offscreen.fillRect((int) Math.round(scaleX(x)), (int) Math.round(scaleY(y)), 1, 1); } /** * Draw a point at (x, y). * @param x the x-coordinate of the point * @param y the y-coordinate of the point */ public static void point(double x, double y) { double xs = scaleX(x); double ys = scaleY(y); double r = penRadius; float scaledPenRadius = (float) (r * DEFAULT_SIZE); // double ws = factorX(2*r); // double hs = factorY(2*r); // if (ws <= 1 && hs <= 1) pixel(x, y); if (scaledPenRadius <= 1) pixel(x, y); else offscreen.fill(new Ellipse2D.Double(xs - scaledPenRadius/2, ys - scaledPenRadius/2, scaledPenRadius, scaledPenRadius)); draw(); } /** * Draw a circle of radius r, centered on (x, y). * @param x the x-coordinate of the center of the circle * @param y the y-coordinate of the center of the circle * @param r the radius of the circle * @throws IllegalArgumentException if the radius of the circle is negative */ public static void circle(double x, double y, double r) { if (r < 0) throw new IllegalArgumentException("circle radius must be nonnegative"); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*r); double hs = factorY(2*r); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.draw(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs)); draw(); } /** * Draw filled circle of radius r, centered on (x, y). * @param x the x-coordinate of the center of the circle * @param y the y-coordinate of the center of the circle * @param r the radius of the circle * @throws IllegalArgumentException if the radius of the circle is negative */ public static void filledCircle(double x, double y, double r) { if (r < 0) throw new IllegalArgumentException("circle radius must be nonnegative"); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*r); double hs = factorY(2*r); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.fill(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs)); draw(); } /** * Draw an ellipse with given semimajor and semiminor axes, centered on (x, y). * @param x the x-coordinate of the center of the ellipse * @param y the y-coordinate of the center of the ellipse * @param semiMajorAxis is the semimajor axis of the ellipse * @param semiMinorAxis is the semiminor axis of the ellipse * @throws IllegalArgumentException if either of the axes are negative */ public static void ellipse(double x, double y, double semiMajorAxis, double semiMinorAxis) { if (semiMajorAxis < 0) throw new IllegalArgumentException("ellipse semimajor axis must be nonnegative"); if (semiMinorAxis < 0) throw new IllegalArgumentException("ellipse semiminor axis must be nonnegative"); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*semiMajorAxis); double hs = factorY(2*semiMinorAxis); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.draw(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs)); draw(); } /** * Draw an ellipse with given semimajor and semiminor axes, centered on (x, y). * @param x the x-coordinate of the center of the ellipse * @param y the y-coordinate of the center of the ellipse * @param semiMajorAxis is the semimajor axis of the ellipse * @param semiMinorAxis is the semiminor axis of the ellipse * @throws IllegalArgumentException if either of the axes are negative */ public static void filledEllipse(double x, double y, double semiMajorAxis, double semiMinorAxis) { if (semiMajorAxis < 0) throw new IllegalArgumentException("ellipse semimajor axis must be nonnegative"); if (semiMinorAxis < 0) throw new IllegalArgumentException("ellipse semiminor axis must be nonnegative"); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*semiMajorAxis); double hs = factorY(2*semiMinorAxis); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.fill(new Ellipse2D.Double(xs - ws/2, ys - hs/2, ws, hs)); draw(); } /** * Draw an arc of radius r, centered on (x, y), from angle1 to angle2 (in degrees). * @param x the x-coordinate of the center of the circle * @param y the y-coordinate of the center of the circle * @param r the radius of the circle * @param angle1 the starting angle. 0 would mean an arc beginning at 3 o'clock. * @param angle2 the angle at the end of the arc. For example, if * you want a 90 degree arc, then angle2 should be angle1 + 90. * @throws IllegalArgumentException if the radius of the circle is negative */ public static void arc(double x, double y, double r, double angle1, double angle2) { if (r < 0) throw new IllegalArgumentException("arc radius must be nonnegative"); while (angle2 < angle1) angle2 += 360; double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*r); double hs = factorY(2*r); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.draw(new Arc2D.Double(xs - ws/2, ys - hs/2, ws, hs, angle1, angle2 - angle1, Arc2D.OPEN)); draw(); } /** * Draw a square of side length 2r, centered on (x, y). * @param x the x-coordinate of the center of the square * @param y the y-coordinate of the center of the square * @param r radius is half the length of any side of the square * @throws IllegalArgumentException if r is negative */ public static void square(double x, double y, double r) { if (r < 0) throw new IllegalArgumentException("square side length must be nonnegative"); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*r); double hs = factorY(2*r); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs)); draw(); } /** * Draw a filled square of side length 2r, centered on (x, y). * @param x the x-coordinate of the center of the square * @param y the y-coordinate of the center of the square * @param r radius is half the length of any side of the square * @throws IllegalArgumentException if r is negative */ public static void filledSquare(double x, double y, double r) { if (r < 0) throw new IllegalArgumentException("square side length must be nonnegative"); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*r); double hs = factorY(2*r); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs)); draw(); } /** * Draw a rectangle of given half width and half height, centered on (x, y). * @param x the x-coordinate of the center of the rectangle * @param y the y-coordinate of the center of the rectangle * @param halfWidth is half the width of the rectangle * @param halfHeight is half the height of the rectangle * @throws IllegalArgumentException if halfWidth or halfHeight is negative */ public static void rectangle(double x, double y, double halfWidth, double halfHeight) { if (halfWidth < 0) throw new IllegalArgumentException("half width must be nonnegative"); if (halfHeight < 0) throw new IllegalArgumentException("half height must be nonnegative"); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*halfWidth); double hs = factorY(2*halfHeight); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.draw(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs)); draw(); } /** * Draw a filled rectangle of given half width and half height, centered on (x, y). * @param x the x-coordinate of the center of the rectangle * @param y the y-coordinate of the center of the rectangle * @param halfWidth is half the width of the rectangle * @param halfHeight is half the height of the rectangle * @throws IllegalArgumentException if halfWidth or halfHeight is negative */ public static void filledRectangle(double x, double y, double halfWidth, double halfHeight) { if (halfWidth < 0) throw new IllegalArgumentException("half width must be nonnegative"); if (halfHeight < 0) throw new IllegalArgumentException("half height must be nonnegative"); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(2*halfWidth); double hs = factorY(2*halfHeight); if (ws <= 1 && hs <= 1) pixel(x, y); else offscreen.fill(new Rectangle2D.Double(xs - ws/2, ys - hs/2, ws, hs)); draw(); } /** * Draw a polygon with the given (x[i], y[i]) coordinates. * @param x an array of all the x-coordindates of the polygon * @param y an array of all the y-coordindates of the polygon */ public static void polygon(double[] x, double[] y) { int N = x.length; GeneralPath path = new GeneralPath(); path.moveTo((float) scaleX(x[0]), (float) scaleY(y[0])); for (int i = 0; i < N; i++) path.lineTo((float) scaleX(x[i]), (float) scaleY(y[i])); path.closePath(); offscreen.draw(path); draw(); } /** * Draw a filled polygon with the given (x[i], y[i]) coordinates. * @param x an array of all the x-coordindates of the polygon * @param y an array of all the y-coordindates of the polygon */ public static void filledPolygon(double[] x, double[] y) { int N = x.length; GeneralPath path = new GeneralPath(); path.moveTo((float) scaleX(x[0]), (float) scaleY(y[0])); for (int i = 0; i < N; i++) path.lineTo((float) scaleX(x[i]), (float) scaleY(y[i])); path.closePath(); offscreen.fill(path); draw(); } /************************************************************************* * Drawing images. *************************************************************************/ // get an image from the given filename private static Image getImage(String filename) { // to read from file ImageIcon icon = new ImageIcon(filename); // try to read from URL if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) { try { URL url = new URL(filename); icon = new ImageIcon(url); } catch (Exception e) { /* not a url */ } } // in case file is inside a .jar if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) { URL url = StdDraw.class.getResource(filename); if (url == null) throw new IllegalArgumentException("image " + filename + " not found"); icon = new ImageIcon(url); } return icon.getImage(); } /** * Draw picture (gif, jpg, or png) centered on (x, y). * @param x the center x-coordinate of the image * @param y the center y-coordinate of the image * @param s the name of the image/picture, e.g., "ball.gif" * @throws IllegalArgumentException if the image is corrupt */ public static void picture(double x, double y, String s) { Image image = getImage(s); double xs = scaleX(x); double ys = scaleY(y); int ws = image.getWidth(null); int hs = image.getHeight(null); if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + s + " is corrupt"); offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int) Math.round(ys - hs/2.0), null); draw(); } /** * Draw picture (gif, jpg, or png) centered on (x, y), * rotated given number of degrees * @param x the center x-coordinate of the image * @param y the center y-coordinate of the image * @param s the name of the image/picture, e.g., "ball.gif" * @param degrees is the number of degrees to rotate counterclockwise * @throws IllegalArgumentException if the image is corrupt */ public static void picture(double x, double y, String s, double degrees) { Image image = getImage(s); double xs = scaleX(x); double ys = scaleY(y); int ws = image.getWidth(null); int hs = image.getHeight(null); if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + s + " is corrupt"); offscreen.rotate(Math.toRadians(-degrees), xs, ys); offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int) Math.round(ys - hs/2.0), null); offscreen.rotate(Math.toRadians(+degrees), xs, ys); draw(); } /** * Draw picture (gif, jpg, or png) centered on (x, y), rescaled to w-by-h. * @param x the center x coordinate of the image * @param y the center y coordinate of the image * @param s the name of the image/picture, e.g., "ball.gif" * @param w the width of the image * @param h the height of the image * @throws IllegalArgumentException if the width height are negative * @throws IllegalArgumentException if the image is corrupt */ public static void picture(double x, double y, String s, double w, double h) { Image image = getImage(s); double xs = scaleX(x); double ys = scaleY(y); if (w < 0) throw new IllegalArgumentException("width is negative: " + w); if (h < 0) throw new IllegalArgumentException("height is negative: " + h); double ws = factorX(w); double hs = factorY(h); if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + s + " is corrupt"); if (ws <= 1 && hs <= 1) pixel(x, y); else { offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int) Math.round(ys - hs/2.0), (int) Math.round(ws), (int) Math.round(hs), null); } draw(); } /** * Draw picture (gif, jpg, or png) centered on (x, y), rotated * given number of degrees, rescaled to w-by-h. * @param x the center x-coordinate of the image * @param y the center y-coordinate of the image * @param s the name of the image/picture, e.g., "ball.gif" * @param w the width of the image * @param h the height of the image * @param degrees is the number of degrees to rotate counterclockwise * @throws IllegalArgumentException if the image is corrupt */ public static void picture(double x, double y, String s, double w, double h, double degrees) { Image image = getImage(s); double xs = scaleX(x); double ys = scaleY(y); double ws = factorX(w); double hs = factorY(h); if (ws < 0 || hs < 0) throw new IllegalArgumentException("image " + s + " is corrupt"); if (ws <= 1 && hs <= 1) pixel(x, y); offscreen.rotate(Math.toRadians(-degrees), xs, ys); offscreen.drawImage(image, (int) Math.round(xs - ws/2.0), (int) Math.round(ys - hs/2.0), (int) Math.round(ws), (int) Math.round(hs), null); offscreen.rotate(Math.toRadians(+degrees), xs, ys); draw(); } /************************************************************************* * Drawing text. *************************************************************************/ /** * Write the given text string in the current font, centered on (x, y). * @param x the center x-coordinate of the text * @param y the center y-coordinate of the text * @param s the text */ public static void text(double x, double y, String s) { offscreen.setFont(font); FontMetrics metrics = offscreen.getFontMetrics(); double xs = scaleX(x); double ys = scaleY(y); int ws = metrics.stringWidth(s); int hs = metrics.getDescent(); offscreen.drawString(s, (float) (xs - ws/2.0), (float) (ys + hs)); draw(); } /** * Write the given text string in the current font, centered on (x, y) and * rotated by the specified number of degrees * @param x the center x-coordinate of the text * @param y the center y-coordinate of the text * @param s the text * @param degrees is the number of degrees to rotate counterclockwise */ public static void text(double x, double y, String s, double degrees) { double xs = scaleX(x); double ys = scaleY(y); offscreen.rotate(Math.toRadians(-degrees), xs, ys); text(x, y, s); offscreen.rotate(Math.toRadians(+degrees), xs, ys); } /** * Write the given text string in the current font, left-aligned at (x, y). * @param x the x-coordinate of the text * @param y the y-coordinate of the text * @param s the text */ public static void textLeft(double x, double y, String s) { offscreen.setFont(font); FontMetrics metrics = offscreen.getFontMetrics(); double xs = scaleX(x); double ys = scaleY(y); int hs = metrics.getDescent(); offscreen.drawString(s, (float) (xs), (float) (ys + hs)); draw(); } /** * Write the given text string in the current font, right-aligned at (x, y). * @param x the x-coordinate of the text * @param y the y-coordinate of the text * @param s the text */ public static void textRight(double x, double y, String s) { offscreen.setFont(font); FontMetrics metrics = offscreen.getFontMetrics(); double xs = scaleX(x); double ys = scaleY(y); int ws = metrics.stringWidth(s); int hs = metrics.getDescent(); offscreen.drawString(s, (float) (xs - ws), (float) (ys + hs)); draw(); } /** * Display on screen, pause for t milliseconds, and turn on * <em>animation mode</em>: subsequent calls to * drawing methods such as <tt>line()</tt>, <tt>circle()</tt>, and <tt>square()</tt> * will not be displayed on screen until the next call to <tt>show()</tt>. * This is useful for producing animations (clear the screen, draw a bunch of shapes, * display on screen for a fixed amount of time, and repeat). It also speeds up * drawing a huge number of shapes (call <tt>show(0)</tt> to defer drawing * on screen, draw the shapes, and call <tt>show(0)</tt> to display them all * on screen at once). * @param t number of milliseconds */ public static void show(int t) { defer = false; draw(); try { Thread.sleep(t); } catch (InterruptedException e) { System.out.println("Error sleeping"); } defer = true; } /** * Display on-screen and turn off animation mode: * subsequent calls to * drawing methods such as <tt>line()</tt>, <tt>circle()</tt>, and <tt>square()</tt> * will be displayed on screen when called. This is the default. */ public static void show() { defer = false; draw(); } // draw onscreen if defer is false private static void draw() { if (defer) return; onscreen.drawImage(offscreenImage, 0, 0, null); frame.repaint(); } /************************************************************************* * Save drawing to a file. *************************************************************************/ /** * Save onscreen image to file - suffix must be png, jpg, or gif. * @param filename the name of the file with one of the required suffixes */ public static void save(String filename) { File file = new File(filename); String suffix = filename.substring(filename.lastIndexOf('.') + 1); // png files if (suffix.toLowerCase().equals("png")) { try { ImageIO.write(onscreenImage, suffix, file); } catch (IOException e) { e.printStackTrace(); } } // need to change from ARGB to RGB for jpeg // reference: http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727 else if (suffix.toLowerCase().equals("jpg")) { WritableRaster raster = onscreenImage.getRaster(); WritableRaster newRaster; newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2}); DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel(); DirectColorModel newCM = new DirectColorModel(cm.getPixelSize(), cm.getRedMask(), cm.getGreenMask(), cm.getBlueMask()); BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null); try { ImageIO.write(rgbBuffer, suffix, file); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Invalid image file type: " + suffix); } } /** * This method cannot be called directly. */ public void actionPerformed(ActionEvent e) { FileDialog chooser = new FileDialog(StdDraw.frame, "Use a .png or .jpg extension", FileDialog.SAVE); chooser.setVisible(true); String filename = chooser.getFile(); if (filename != null) { StdDraw.save(chooser.getDirectory() + File.separator + chooser.getFile()); } } /************************************************************************* * Mouse interactions. *************************************************************************/ /** * Is the mouse being pressed? * @return true or false */ public static boolean mousePressed() { synchronized (mouseLock) { return mousePressed; } } /** * What is the x-coordinate of the mouse? * @return the value of the x-coordinate of the mouse */ public static double mouseX() { synchronized (mouseLock) { return mouseX; } } /** * What is the y-coordinate of the mouse? * @return the value of the y-coordinate of the mouse */ public static double mouseY() { synchronized (mouseLock) { return mouseY; } } /** * This method cannot be called directly. */ public void mouseClicked(MouseEvent e) { } /** * This method cannot be called directly. */ public void mouseEntered(MouseEvent e) { } /** * This method cannot be called directly. */ public void mouseExited(MouseEvent e) { } /** * This method cannot be called directly. */ public void mousePressed(MouseEvent e) { synchronized (mouseLock) { mouseX = StdDraw.userX(e.getX()); mouseY = StdDraw.userY(e.getY()); mousePressed = true; } } /** * This method cannot be called directly. */ public void mouseReleased(MouseEvent e) { synchronized (mouseLock) { mousePressed = false; } } /** * This method cannot be called directly. */ public void mouseDragged(MouseEvent e) { synchronized (mouseLock) { mouseX = StdDraw.userX(e.getX()); mouseY = StdDraw.userY(e.getY()); } } /** * This method cannot be called directly. */ public void mouseMoved(MouseEvent e) { synchronized (mouseLock) { mouseX = StdDraw.userX(e.getX()); mouseY = StdDraw.userY(e.getY()); } } /************************************************************************* * Keyboard interactions. *************************************************************************/ /** * Has the user typed a key? * @return true if the user has typed a key, false otherwise */ public static boolean hasNextKeyTyped() { synchronized (keyLock) { return !keysTyped.isEmpty(); } } /** * What is the next key that was typed by the user? This method returns * a Unicode character corresponding to the key typed (such as 'a' or 'A'). * It cannot identify action keys (such as F1 * and arrow keys) or modifier keys (such as control). * @return the next Unicode key typed */ public static char nextKeyTyped() { synchronized (keyLock) { return keysTyped.removeLast(); } } /** * Is the keycode currently being pressed? This method takes as an argument * the keycode (corresponding to a physical key). It can handle action keys * (such as F1 and arrow keys) and modifier keys (such as shift and control). * See <a href = "http://download.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html">KeyEvent.java</a> * for a description of key codes. * @return true if keycode is currently being pressed, false otherwise */ public static boolean isKeyPressed(int keycode) { synchronized (keyLock) { return keysDown.contains(keycode); } } /** * This method cannot be called directly. */ public void keyTyped(KeyEvent e) { synchronized (keyLock) { keysTyped.addFirst(e.getKeyChar()); } } /** * This method cannot be called directly. */ public void keyPressed(KeyEvent e) { synchronized (keyLock) { keysDown.add(e.getKeyCode()); } } /** * This method cannot be called directly. */ public void keyReleased(KeyEvent e) { synchronized (keyLock) { keysDown.remove(e.getKeyCode()); } } /** * Test client. */ public static void main(String[] args) { StdDraw.square(.2, .8, .1); StdDraw.filledSquare(.8, .8, .2); StdDraw.circle(.8, .2, .2); StdDraw.setPenColor(StdDraw.BOOK_RED); StdDraw.setPenRadius(.02); StdDraw.arc(.8, .2, .1, 200, 45); // draw a blue diamond StdDraw.setPenRadius(); StdDraw.setPenColor(StdDraw.BOOK_BLUE); double[] x = { .1, .2, .3, .2 }; double[] y = { .2, .3, .2, .1 }; StdDraw.filledPolygon(x, y); // text StdDraw.setPenColor(StdDraw.BLACK); StdDraw.text(0.2, 0.5, "black text"); StdDraw.setPenColor(StdDraw.WHITE); StdDraw.text(0.8, 0.8, "white text"); } }
apache-2.0
helicalinsight/helicalinsight
core/src/main/java/com/helicalinsight/resourcesecurity/jaxb/Efw.java
5340
/** * Copyright (C) 2013-2019 Helical IT Solutions (http://www.helicalinsight.com) - All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helicalinsight.resourcesecurity.jaxb; import com.helicalinsight.resourcesecurity.IResource; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * Created by author on 29-05-2015. * * @author Rajasekhar */ @Component @Scope("prototype") @XmlRootElement(name = "efw") @XmlAccessorType(XmlAccessType.FIELD) public class Efw implements IResource { @XmlElement private String title; @XmlElement private String author; @XmlElement private String description; @XmlElement private String icon; @XmlElement private String template; @XmlElement private String visible; @XmlElement private String style; @XmlElement private Security security; @XmlElement private Security.Share share; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getTemplate() { return template; } public void setTemplate(String template) { this.template = template; } public String getVisible() { return visible; } public void setVisible(String visible) { this.visible = visible; } public String getStyle() { return style; } public void setStyle(String style) { this.style = style; } public Security getSecurity() { return security; } public void setSecurity(Security security) { this.security = security; } public Security.Share getShare() { return share; } public void setShare(Security.Share share) { this.share = share; } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; Efw efw = (Efw) other; if (title != null ? !title.equals(efw.title) : efw.title != null) return false; if (author != null ? !author.equals(efw.author) : efw.author != null) return false; if (description != null ? !description.equals(efw.description) : efw.description != null) return false; if (icon != null ? !icon.equals(efw.icon) : efw.icon != null) return false; if (template != null ? !template.equals(efw.template) : efw.template != null) return false; if (visible != null ? !visible.equals(efw.visible) : efw.visible != null) return false; if (style != null ? !style.equals(efw.style) : efw.style != null) return false; if (security != null ? !security.equals(efw.security) : efw.security != null) return false; return !(share != null ? !share.equals(efw.share) : efw.share != null); } @Override public int hashCode() { int result = title != null ? title.hashCode() : 0; result = 31 * result + (author != null ? author.hashCode() : 0); result = 31 * result + (description != null ? description.hashCode() : 0); result = 31 * result + (icon != null ? icon.hashCode() : 0); result = 31 * result + (template != null ? template.hashCode() : 0); result = 31 * result + (visible != null ? visible.hashCode() : 0); result = 31 * result + (style != null ? style.hashCode() : 0); result = 31 * result + (security != null ? security.hashCode() : 0); result = 31 * result + (share != null ? share.hashCode() : 0); return result; } @Override public String toString() { return "Efw{" + "title='" + title + '\'' + ", author='" + author + '\'' + ", description='" + description + '\'' + ", icon='" + icon + '\'' + ", template='" + template + '\'' + ", visible='" + visible + '\'' + ", style='" + style + '\'' + ", security=" + security + ", share=" + share + '}'; } }
apache-2.0
sonalgoyal/hiho
src/test/java/co/nubetech/hiho/merge/TestMergeValueReducer.java
6357
/** * Copyright 2011 Nube Technologies * * 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 co.nubetech.hiho.merge; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.IOException; import java.util.ArrayList; import org.apache.hadoop.io.BytesWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Counter; import org.apache.hadoop.mapreduce.Counters; import org.apache.hadoop.mapreduce.Reducer; import org.junit.Test; import co.nubetech.hiho.dedup.HihoTuple; public class TestMergeValueReducer { @Test public void testReducerValidValues() throws IOException, InterruptedException { Text key = new Text("key123"); HihoTuple hihoTuple = new HihoTuple(); hihoTuple.setKey(key); HihoValue hihoValue1 = new HihoValue(); HihoValue hihoValue2 = new HihoValue(); Text value1 = new Text("value1"); Text value2 = new Text("value2"); hihoValue1.setVal(value1); hihoValue2.setVal(value2); hihoValue1.setIsOld(true); hihoValue2.setIsOld(false); ArrayList<HihoValue> values = new ArrayList<HihoValue>(); values.add(hihoValue1); values.add(hihoValue2); Reducer.Context context = mock(Reducer.Context.class); Counters counters = new Counters(); Counter counter = counters.findCounter(MergeRecordCounter.OUTPUT); when(context.getCounter(MergeRecordCounter.OUTPUT)).thenReturn(counter); MergeValueReducer mergeReducer = new MergeValueReducer(); mergeReducer.reduce(hihoTuple, values, context); verify(context).write(value2, key); assertEquals(1, context.getCounter(MergeRecordCounter.OUTPUT) .getValue()); } @Test public void testReducerNullValues() throws IOException, InterruptedException { Text key = new Text("key123"); HihoTuple hihoTuple = new HihoTuple(); hihoTuple.setKey(key); ArrayList<HihoValue> values = new ArrayList<HihoValue>(); Reducer.Context context = mock(Reducer.Context.class); Counters counters = new Counters(); Counter counter = counters.findCounter(MergeRecordCounter.OUTPUT); when(context.getCounter(MergeRecordCounter.OUTPUT)).thenReturn(counter); MergeValueReducer mergeReducer = new MergeValueReducer(); mergeReducer.reduce(hihoTuple, values, context); verify(context).write(null, key); assertEquals(1, context.getCounter(MergeRecordCounter.OUTPUT) .getValue()); } @Test public void testReducerForLongWritableKey() throws IOException, InterruptedException { LongWritable key = new LongWritable(Long.parseLong("123")); HihoTuple hihoTuple = new HihoTuple(); hihoTuple.setKey(key); HihoValue hihoValue1 = new HihoValue(); HihoValue hihoValue2 = new HihoValue(); Text value1 = new Text("value1"); Text value2 = new Text("value2"); hihoValue1.setVal(value1); hihoValue2.setVal(value2); hihoValue1.setIsOld(true); hihoValue2.setIsOld(false); ArrayList<HihoValue> values = new ArrayList<HihoValue>(); values.add(hihoValue1); values.add(hihoValue2); Reducer.Context context = mock(Reducer.Context.class); Counters counters = new Counters(); Counter counter = counters.findCounter(MergeRecordCounter.OUTPUT); when(context.getCounter(MergeRecordCounter.OUTPUT)).thenReturn(counter); MergeValueReducer mergeReducer = new MergeValueReducer(); mergeReducer.reduce(hihoTuple, values, context); verify(context).write(value2, key); assertEquals(1, context.getCounter(MergeRecordCounter.OUTPUT) .getValue()); } @Test public void testReducerForBytesWritableKeyAndValue() throws IOException, InterruptedException { BytesWritable key = new BytesWritable("abc123".getBytes()); HihoTuple hihoTuple = new HihoTuple(); hihoTuple.setKey(key); HihoValue hihoValue1 = new HihoValue(); HihoValue hihoValue2 = new HihoValue(); BytesWritable value1 = new BytesWritable("value1".getBytes()); BytesWritable value2 = new BytesWritable("value2".getBytes()); hihoValue1.setVal(value1); hihoValue2.setVal(value2); hihoValue1.setIsOld(true); hihoValue2.setIsOld(false); ArrayList<HihoValue> values = new ArrayList<HihoValue>(); values.add(hihoValue1); values.add(hihoValue2); Reducer.Context context = mock(Reducer.Context.class); Counters counters = new Counters(); Counter counter = counters.findCounter(MergeRecordCounter.OUTPUT); when(context.getCounter(MergeRecordCounter.OUTPUT)).thenReturn(counter); MergeValueReducer mergeReducer = new MergeValueReducer(); mergeReducer.reduce(hihoTuple, values, context); verify(context).write(value2, key); assertEquals(1, context.getCounter(MergeRecordCounter.OUTPUT) .getValue()); } @Test public void testReducerForIntWritableKeyAndValue() throws IOException, InterruptedException { IntWritable key = new IntWritable(123); HihoTuple hihoTuple = new HihoTuple(); hihoTuple.setKey(key); HihoValue hihoValue1 = new HihoValue(); HihoValue hihoValue2 = new HihoValue(); IntWritable value1 = new IntWritable(456); IntWritable value2 = new IntWritable(789); hihoValue1.setVal(value1); hihoValue2.setVal(value2); hihoValue1.setIsOld(true); hihoValue2.setIsOld(false); ArrayList<HihoValue> values = new ArrayList<HihoValue>(); values.add(hihoValue1); values.add(hihoValue2); Reducer.Context context = mock(Reducer.Context.class); Counters counters = new Counters(); Counter counter = counters.findCounter(MergeRecordCounter.OUTPUT); when(context.getCounter(MergeRecordCounter.OUTPUT)).thenReturn(counter); MergeValueReducer mergeReducer = new MergeValueReducer(); mergeReducer.reduce(hihoTuple, values, context); verify(context).write(value2, key); assertEquals(1, context.getCounter(MergeRecordCounter.OUTPUT) .getValue()); } }
apache-2.0
softelnet/sponge
sponge-core/src/main/java/org/openksavi/sponge/core/rule/ReflectionEventCondition.java
2804
/* * Copyright 2016-2017 The Sponge authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openksavi.sponge.core.rule; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.commons.lang3.reflect.MethodUtils; import org.openksavi.sponge.SpongeException; import org.openksavi.sponge.event.Event; import org.openksavi.sponge.rule.Rule; /** * Reflection rule event condition. */ public class ReflectionEventCondition extends MethodNameEventCondition { /** Method reference. */ private Method method; /** * Creates a new reflection rule event condition. * * @param method Java-based rule class method. */ protected ReflectionEventCondition(Method method) { super(method.getName()); this.method = method; } /** * Checks rule event condition by invoking the defined Java rule class method. * * @param rule rule. * @param event event. * @return {@code true} if this condition is met. */ @Override public synchronized boolean condition(Rule rule, Event event) { try { Object result = method.invoke(rule, new Object[] { event }); if (!(result instanceof Boolean)) { throw new IllegalArgumentException("Condition method must return a boolean value"); } return (Boolean) result; } catch (InvocationTargetException e) { if (e.getCause() != null) { throw new SpongeException(e.getCause()); } else { throw new SpongeException(e); } } catch (IllegalAccessException e) { throw new SpongeException(e); } } public static ReflectionEventCondition create(Rule rule, String methodName) { return new ReflectionEventCondition(resolveMethod(rule, methodName)); } public static Method resolveMethod(Rule rule, String methodName) { Method method = MethodUtils.getMatchingMethod(rule.getClass(), methodName, Event.class); if (method == null) { throw new IllegalArgumentException("Event condition method " + methodName + " not found in rule " + rule.getMeta().getName()); } return method; } }
apache-2.0
Oliver-Loeffler/NIOHttp
src/test/java/net/raumzeitfalle/niohttp/header/ConnectionTest.java
597
package net.raumzeitfalle.niohttp.header; import static org.junit.Assert.*; import org.junit.Test; import net.raumzeitfalle.niohttp.Constants; import net.raumzeitfalle.niohttp.header.Connection; public class ConnectionTest { private Connection classUnderTest; @Test public void close() { classUnderTest = Connection.close(); assertEquals("Connection: close" + Constants.CRLF, classUnderTest.get()); } @Test public void keepAlive() { classUnderTest = Connection.keepAlive(); assertEquals("Connection: keep-alive" + Constants.CRLF, classUnderTest.get()); } }
apache-2.0
frincon/openeos
modules/org.openeos.utils/src/main/java/org/openeos/utils/BundleFilter.java
772
/** * Copyright 2014 Fernando Rincon Martin <frm.rincon@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.openeos.utils; import org.osgi.framework.Bundle; public interface BundleFilter<T> { public T filterBundle(Bundle bundle); }
apache-2.0