repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
box/box-java-sdk | src/test/java/com/box/sdk/BoxAPIResponseExceptionTest.java | 11941 | package com.box.sdk;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static java.lang.String.format;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonObject;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.TreeMap;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
/**
* BoxAPIConnection unit tests
*/
public class BoxAPIResponseExceptionTest {
@Rule
public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().dynamicPort());
private final BoxAPIConnection api = TestConfig.getAPIConnection();
@Before
public void setUpBaseUrl() {
api.setMaxRetryAttempts(1);
api.setBaseURL(baseUrl());
}
@Test
public void testAPIResponseExceptionReturnsCorrectErrorMessage() throws MalformedURLException {
BoxAPIConnection api = new BoxAPIConnection("");
final JsonObject fakeJSONResponse = Json.parse("{\n"
+ " \"type\": \"error\",\n"
+ " \"status\": \"409\",\n"
+ " \"code\": \"item_name_in_use\",\n"
+ " \"context_info\": {\n"
+ " \"conflicts\": [\n"
+ " {\n"
+ " \"type\": \"folder\",\n"
+ " \"id\": \"12345\",\n"
+ " \"sequence_id\": \"1\",\n"
+ " \"etag\": \"1\",\n"
+ " \"name\": \"Helpful things\"\n"
+ " }\n"
+ " ]\n"
+ " },\n"
+ " \"help_url\": \"http://developers.box.com/docs/#errors\",\n"
+ " \"message\": \"Item with the same name already exists\",\n"
+ " \"request_id\": \"5678\"\n"
+ " }").asObject();
stubFor(post(urlEqualTo("/folders"))
.willReturn(aResponse()
.withStatus(409)
.withHeader("Content-Type", "application/json")
.withBody(fakeJSONResponse.toString())));
BoxAPIRequest request = new BoxAPIRequest(api, foldersUrl(), "POST");
try {
request.send();
} catch (BoxAPIResponseException e) {
assertEquals(409, e.getResponseCode());
assertEquals("The API returned an error code [409 | 5678] item_name_in_use - "
+ "Item with the same name already exists", e.getMessage());
return;
}
fail("Never threw a BoxAPIResponseException");
}
@Test
public void testAPIResponseExceptionMissingFieldsReturnsCorrectErrorMessage() throws MalformedURLException {
BoxAPIConnection api = new BoxAPIConnection("");
final JsonObject fakeJSONResponse = Json.parse("{\n"
+ " \"type\": \"error\",\n"
+ " \"status\": \"409\",\n"
+ " \"context_info\": {\n"
+ " \"conflicts\": [\n"
+ " {\n"
+ " \"type\": \"folder\",\n"
+ " \"id\": \"12345\",\n"
+ " \"sequence_id\": \"1\",\n"
+ " \"etag\": \"1\",\n"
+ " \"name\": \"Helpful things\"\n"
+ " }\n"
+ " ]\n"
+ " },\n"
+ " \"help_url\": \"http://developers.box.com/docs/#errors\"\n"
+ " }").asObject();
stubFor(post(urlEqualTo("/folders"))
.willReturn(aResponse()
.withStatus(409)
.withHeader("Content-Type", "application/json")
.withBody(fakeJSONResponse.toString())));
BoxAPIRequest request = new BoxAPIRequest(api, foldersUrl(), "POST");
try {
request.send();
} catch (BoxAPIResponseException e) {
assertEquals(409, e.getResponseCode());
assertEquals("The API returned an error code [409]", e.getMessage());
return;
}
fail("Never threw a BoxAPIResponseException");
}
@Test
public void testAPIResponseExceptionMissingBodyReturnsCorrectErrorMessage() throws MalformedURLException {
BoxAPIConnection api = new BoxAPIConnection("");
stubFor(post(urlEqualTo("/folders"))
.willReturn(aResponse()
.withStatus(403)));
BoxAPIRequest request = new BoxAPIRequest(api, foldersUrl(), "POST");
try {
request.send();
} catch (BoxAPIResponseException e) {
assertEquals(403, e.getResponseCode());
assertEquals("", e.getResponse());
assertEquals("The API returned an error code [403]", e.getMessage());
return;
}
fail("Never threw a BoxAPIResponseException");
}
@Test
public void testAPIResponseExceptionWithHTMLBodyReturnsCorrectErrorMessage() throws MalformedURLException {
String body = "<html><body><h1>500 Server Error</h1></body></html>";
BoxAPIConnection api = new BoxAPIConnection("");
api.setMaxRetryAttempts(1);
stubFor(post(urlEqualTo("/folders"))
.willReturn(aResponse()
.withBody(body)
.withStatus(500)));
BoxAPIRequest request = new BoxAPIRequest(api, foldersUrl(), "POST");
try {
request.send();
} catch (BoxAPIResponseException e) {
assertEquals(500, e.getResponseCode());
assertEquals(body, e.getResponse());
assertEquals("The API returned an error code [500]", e.getMessage());
return;
}
fail("Never threw a BoxAPIResponseException");
}
@Test
public void testResponseExceptionHeadersIsCaseInsensitive() {
Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
headers.put("FOO", "bAr");
BoxAPIResponse responseObject = new BoxAPIResponse(202, headers);
BoxAPIResponseException responseException = new BoxAPIResponseException("Test Message", responseObject);
Assert.assertTrue(responseException.getHeaders().containsKey("foo"));
Assert.assertTrue(responseException.getHeaders().containsKey("fOo"));
Assert.assertTrue(responseException.getHeaders().containsKey("FOO"));
assertEquals("bAr", responseException.getHeaders().get("foo").get(0));
}
@Test
public void testGetResponseHeadersWithNoRequestID() throws IOException {
final String userURL = "/users/12345";
String result = TestConfig.getFixture("BoxException/BoxResponseException403");
wireMockRule.stubFor(WireMock.get(WireMock.urlPathEqualTo(userURL))
.willReturn(WireMock.aResponse()
.withHeader("BOX-REQUEST-ID", "11111")
.withStatus(403)
.withBody(result)));
try {
BoxUser user = new BoxUser(this.api, "12345");
assertNotNull(user.getInfo());
} catch (Exception e) {
assertEquals("The API returned an error code [403 | .11111] Forbidden", e.getMessage());
}
}
@Test
public void testGetResponseExceptionCorrectlyWithAllID() throws IOException {
final String userURL = "/users/12345";
String result = TestConfig.getFixture("BoxException/BoxResponseException403WithRequestID");
wireMockRule.stubFor(WireMock.get(WireMock.urlPathEqualTo(userURL))
.willReturn(WireMock.aResponse()
.withHeader("BOX-REQUEST-ID", "11111")
.withStatus(403)
.withBody(result)));
try {
BoxUser user = new BoxUser(this.api, "12345");
assertNotNull(user.getInfo());
} catch (Exception e) {
assertEquals("The API returned an error code [403 | 22222.11111] Forbidden", e.getMessage());
}
}
@Test
public void testGetResponseExceptionErrorAndErrorDescription() throws IOException {
final String userURL = "/users/12345";
String result = TestConfig.getFixture("BoxException/BoxResponseException400WithErrorAndErrorDescription");
wireMockRule.stubFor(WireMock.get(WireMock.urlPathEqualTo(userURL))
.willReturn(WireMock.aResponse()
.withHeader("BOX-REQUEST-ID", "11111")
.withStatus(403)
.withBody(result)));
try {
new BoxUser(this.api, "12345");
} catch (Exception e) {
assertEquals(
"The API returned an error code [403 | 22222.11111] Forbidden - Unauthorized Access",
e.getMessage()
);
}
}
@Test
public void testGetResponseHeadersCorrectlyWithEmptyBody() {
final String userURL = "/users/12345";
wireMockRule.stubFor(WireMock.get(WireMock.urlPathEqualTo(userURL))
.willReturn(WireMock.aResponse()
.withHeader("BOX-REQUEST-ID", "11111")
.withStatus(403)));
try {
BoxUser user = new BoxUser(this.api, "12345");
assertNotNull(user.getInfo());
} catch (Exception e) {
assertEquals("The API returned an error code [403 | .11111]", e.getMessage());
}
}
@Test
public void testGeneratingWhenContextInfoPresentWithOneError() {
// given
String errorJsonString = "{\n"
+ " \"type\": \"error\",\n"
+ " \"status\": 400,\n"
+ " \"code\": \"bad_request\",\n"
+ " \"context_info\": {\n"
+ " \"errors\": [\n"
+ " {\n"
+ " \"reason\": \"invalid_parameter\",\n"
+ " \"name\": \"stream_type\",\n"
+ " \"message\": \"Invalid value 'admin_logs_streaming'.\"\n"
+ " }\n"
+ " ]\n"
+ " },\n"
+ " \"help_url\": \"http:\\/\\/developers.box.com\\/docs\\/#errors\",\n"
+ " \"message\": \"Bad Request\",\n"
+ " \"request_id\": \"feo3k0gwg4ji04zl\"\n"
+ "}";
BoxAPIResponse response = mock(BoxAPIResponse.class);
when(response.bodyToString()).thenReturn(errorJsonString);
when(response.getResponseCode()).thenReturn(400);
//when
BoxAPIResponseException exception = new BoxAPIResponseException("Bad Request", response);
assertThat(exception.getMessage(), is("Bad Request [400 | feo3k0gwg4ji04zl] bad_request - Bad Request"));
assertThat(exception.getResponseCode(), is(400));
assertThat(exception.getResponse(), is(errorJsonString)
);
}
private URL foldersUrl() throws MalformedURLException {
return new URL(baseUrl() + "/folders");
}
private String baseUrl() {
return format("http://localhost:%d", wireMockRule.port());
}
}
| apache-2.0 |
mhurne/aws-sdk-java | aws-java-sdk-directory/src/main/java/com/amazonaws/services/directory/model/transform/DeleteTrustRequestMarshaller.java | 3295 | /*
* Copyright 2010-2016 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.directory.model.transform;
import java.io.ByteArrayInputStream;
import java.util.Collections;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;
import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.directory.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;
/**
* DeleteTrustRequest Marshaller
*/
public class DeleteTrustRequestMarshaller implements
Marshaller<Request<DeleteTrustRequest>, DeleteTrustRequest> {
public Request<DeleteTrustRequest> marshall(
DeleteTrustRequest deleteTrustRequest) {
if (deleteTrustRequest == null) {
throw new AmazonClientException(
"Invalid argument passed to marshall(...)");
}
Request<DeleteTrustRequest> request = new DefaultRequest<DeleteTrustRequest>(
deleteTrustRequest, "AWSDirectoryService");
request.addHeader("X-Amz-Target",
"DirectoryService_20150416.DeleteTrust");
request.setHttpMethod(HttpMethodName.POST);
request.setResourcePath("");
try {
final StructuredJsonGenerator jsonGenerator = SdkJsonProtocolFactory
.createWriter(false, "1.1");
jsonGenerator.writeStartObject();
if (deleteTrustRequest.getTrustId() != null) {
jsonGenerator.writeFieldName("TrustId").writeValue(
deleteTrustRequest.getTrustId());
}
if (deleteTrustRequest.getDeleteAssociatedConditionalForwarder() != null) {
jsonGenerator.writeFieldName(
"DeleteAssociatedConditionalForwarder").writeValue(
deleteTrustRequest
.getDeleteAssociatedConditionalForwarder());
}
jsonGenerator.writeEndObject();
byte[] content = jsonGenerator.getBytes();
request.setContent(new ByteArrayInputStream(content));
request.addHeader("Content-Length",
Integer.toString(content.length));
request.addHeader("Content-Type", jsonGenerator.getContentType());
} catch (Throwable t) {
throw new AmazonClientException(
"Unable to marshall request to JSON: " + t.getMessage(), t);
}
return request;
}
}
| apache-2.0 |
googleapis/java-aiplatform | proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/UpdateFeaturestoreRequest.java | 41299 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1beta1/featurestore_service.proto
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* Request message for [FeaturestoreService.UpdateFeaturestore][google.cloud.aiplatform.v1beta1.FeaturestoreService.UpdateFeaturestore].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest}
*/
public final class UpdateFeaturestoreRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest)
UpdateFeaturestoreRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateFeaturestoreRequest.newBuilder() to construct.
private UpdateFeaturestoreRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateFeaturestoreRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateFeaturestoreRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private UpdateFeaturestoreRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.aiplatform.v1beta1.Featurestore.Builder subBuilder = null;
if (featurestore_ != null) {
subBuilder = featurestore_.toBuilder();
}
featurestore_ =
input.readMessage(
com.google.cloud.aiplatform.v1beta1.Featurestore.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(featurestore_);
featurestore_ = subBuilder.buildPartial();
}
break;
}
case 18:
{
com.google.protobuf.FieldMask.Builder subBuilder = null;
if (updateMask_ != null) {
subBuilder = updateMask_.toBuilder();
}
updateMask_ =
input.readMessage(com.google.protobuf.FieldMask.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(updateMask_);
updateMask_ = subBuilder.buildPartial();
}
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.FeaturestoreServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_UpdateFeaturestoreRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.FeaturestoreServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_UpdateFeaturestoreRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest.class,
com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest.Builder.class);
}
public static final int FEATURESTORE_FIELD_NUMBER = 1;
private com.google.cloud.aiplatform.v1beta1.Featurestore featurestore_;
/**
*
*
* <pre>
* Required. The Featurestore's `name` field is used to identify the Featurestore to be
* updated.
* Format:
* `projects/{project}/locations/{location}/featurestores/{featurestore}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.Featurestore featurestore = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the featurestore field is set.
*/
@java.lang.Override
public boolean hasFeaturestore() {
return featurestore_ != null;
}
/**
*
*
* <pre>
* Required. The Featurestore's `name` field is used to identify the Featurestore to be
* updated.
* Format:
* `projects/{project}/locations/{location}/featurestores/{featurestore}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.Featurestore featurestore = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The featurestore.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.Featurestore getFeaturestore() {
return featurestore_ == null
? com.google.cloud.aiplatform.v1beta1.Featurestore.getDefaultInstance()
: featurestore_;
}
/**
*
*
* <pre>
* Required. The Featurestore's `name` field is used to identify the Featurestore to be
* updated.
* Format:
* `projects/{project}/locations/{location}/featurestores/{featurestore}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.Featurestore featurestore = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.FeaturestoreOrBuilder getFeaturestoreOrBuilder() {
return getFeaturestore();
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* Featurestore resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then only the non-empty fields present in the
* request will be overwritten. Set the update_mask to `*` to override all
* fields.
* Updatable fields:
* * `labels`
* * `online_serving_config.fixed_node_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return updateMask_ != null;
}
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* Featurestore resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then only the non-empty fields present in the
* request will be overwritten. Set the update_mask to `*` to override all
* fields.
* Updatable fields:
* * `labels`
* * `online_serving_config.fixed_node_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* Featurestore resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then only the non-empty fields present in the
* request will be overwritten. Set the update_mask to `*` to override all
* fields.
* Updatable fields:
* * `labels`
* * `online_serving_config.fixed_node_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return getUpdateMask();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (featurestore_ != null) {
output.writeMessage(1, getFeaturestore());
}
if (updateMask_ != null) {
output.writeMessage(2, getUpdateMask());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (featurestore_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getFeaturestore());
}
if (updateMask_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest other =
(com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest) obj;
if (hasFeaturestore() != other.hasFeaturestore()) return false;
if (hasFeaturestore()) {
if (!getFeaturestore().equals(other.getFeaturestore())) return false;
}
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask().equals(other.getUpdateMask())) return false;
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasFeaturestore()) {
hash = (37 * hash) + FEATURESTORE_FIELD_NUMBER;
hash = (53 * hash) + getFeaturestore().hashCode();
}
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request message for [FeaturestoreService.UpdateFeaturestore][google.cloud.aiplatform.v1beta1.FeaturestoreService.UpdateFeaturestore].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest)
com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.FeaturestoreServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_UpdateFeaturestoreRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.FeaturestoreServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_UpdateFeaturestoreRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest.class,
com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (featurestoreBuilder_ == null) {
featurestore_ = null;
} else {
featurestore_ = null;
featurestoreBuilder_ = null;
}
if (updateMaskBuilder_ == null) {
updateMask_ = null;
} else {
updateMask_ = null;
updateMaskBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1beta1.FeaturestoreServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_UpdateFeaturestoreRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest build() {
com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest buildPartial() {
com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest result =
new com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest(this);
if (featurestoreBuilder_ == null) {
result.featurestore_ = featurestore_;
} else {
result.featurestore_ = featurestoreBuilder_.build();
}
if (updateMaskBuilder_ == null) {
result.updateMask_ = updateMask_;
} else {
result.updateMask_ = updateMaskBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest other) {
if (other
== com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest.getDefaultInstance())
return this;
if (other.hasFeaturestore()) {
mergeFeaturestore(other.getFeaturestore());
}
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest)
e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private com.google.cloud.aiplatform.v1beta1.Featurestore featurestore_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Featurestore,
com.google.cloud.aiplatform.v1beta1.Featurestore.Builder,
com.google.cloud.aiplatform.v1beta1.FeaturestoreOrBuilder>
featurestoreBuilder_;
/**
*
*
* <pre>
* Required. The Featurestore's `name` field is used to identify the Featurestore to be
* updated.
* Format:
* `projects/{project}/locations/{location}/featurestores/{featurestore}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.Featurestore featurestore = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the featurestore field is set.
*/
public boolean hasFeaturestore() {
return featurestoreBuilder_ != null || featurestore_ != null;
}
/**
*
*
* <pre>
* Required. The Featurestore's `name` field is used to identify the Featurestore to be
* updated.
* Format:
* `projects/{project}/locations/{location}/featurestores/{featurestore}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.Featurestore featurestore = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The featurestore.
*/
public com.google.cloud.aiplatform.v1beta1.Featurestore getFeaturestore() {
if (featurestoreBuilder_ == null) {
return featurestore_ == null
? com.google.cloud.aiplatform.v1beta1.Featurestore.getDefaultInstance()
: featurestore_;
} else {
return featurestoreBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The Featurestore's `name` field is used to identify the Featurestore to be
* updated.
* Format:
* `projects/{project}/locations/{location}/featurestores/{featurestore}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.Featurestore featurestore = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setFeaturestore(com.google.cloud.aiplatform.v1beta1.Featurestore value) {
if (featurestoreBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
featurestore_ = value;
onChanged();
} else {
featurestoreBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Required. The Featurestore's `name` field is used to identify the Featurestore to be
* updated.
* Format:
* `projects/{project}/locations/{location}/featurestores/{featurestore}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.Featurestore featurestore = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setFeaturestore(
com.google.cloud.aiplatform.v1beta1.Featurestore.Builder builderForValue) {
if (featurestoreBuilder_ == null) {
featurestore_ = builderForValue.build();
onChanged();
} else {
featurestoreBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Required. The Featurestore's `name` field is used to identify the Featurestore to be
* updated.
* Format:
* `projects/{project}/locations/{location}/featurestores/{featurestore}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.Featurestore featurestore = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeFeaturestore(com.google.cloud.aiplatform.v1beta1.Featurestore value) {
if (featurestoreBuilder_ == null) {
if (featurestore_ != null) {
featurestore_ =
com.google.cloud.aiplatform.v1beta1.Featurestore.newBuilder(featurestore_)
.mergeFrom(value)
.buildPartial();
} else {
featurestore_ = value;
}
onChanged();
} else {
featurestoreBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Required. The Featurestore's `name` field is used to identify the Featurestore to be
* updated.
* Format:
* `projects/{project}/locations/{location}/featurestores/{featurestore}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.Featurestore featurestore = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearFeaturestore() {
if (featurestoreBuilder_ == null) {
featurestore_ = null;
onChanged();
} else {
featurestore_ = null;
featurestoreBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Required. The Featurestore's `name` field is used to identify the Featurestore to be
* updated.
* Format:
* `projects/{project}/locations/{location}/featurestores/{featurestore}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.Featurestore featurestore = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.Featurestore.Builder getFeaturestoreBuilder() {
onChanged();
return getFeaturestoreFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The Featurestore's `name` field is used to identify the Featurestore to be
* updated.
* Format:
* `projects/{project}/locations/{location}/featurestores/{featurestore}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.Featurestore featurestore = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.FeaturestoreOrBuilder getFeaturestoreOrBuilder() {
if (featurestoreBuilder_ != null) {
return featurestoreBuilder_.getMessageOrBuilder();
} else {
return featurestore_ == null
? com.google.cloud.aiplatform.v1beta1.Featurestore.getDefaultInstance()
: featurestore_;
}
}
/**
*
*
* <pre>
* Required. The Featurestore's `name` field is used to identify the Featurestore to be
* updated.
* Format:
* `projects/{project}/locations/{location}/featurestores/{featurestore}`
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.Featurestore featurestore = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Featurestore,
com.google.cloud.aiplatform.v1beta1.Featurestore.Builder,
com.google.cloud.aiplatform.v1beta1.FeaturestoreOrBuilder>
getFeaturestoreFieldBuilder() {
if (featurestoreBuilder_ == null) {
featurestoreBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Featurestore,
com.google.cloud.aiplatform.v1beta1.Featurestore.Builder,
com.google.cloud.aiplatform.v1beta1.FeaturestoreOrBuilder>(
getFeaturestore(), getParentForChildren(), isClean());
featurestore_ = null;
}
return featurestoreBuilder_;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* Featurestore resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then only the non-empty fields present in the
* request will be overwritten. Set the update_mask to `*` to override all
* fields.
* Updatable fields:
* * `labels`
* * `online_serving_config.fixed_node_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return updateMaskBuilder_ != null || updateMask_ != null;
}
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* Featurestore resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then only the non-empty fields present in the
* request will be overwritten. Set the update_mask to `*` to override all
* fields.
* Updatable fields:
* * `labels`
* * `online_serving_config.fixed_node_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* Featurestore resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then only the non-empty fields present in the
* request will be overwritten. Set the update_mask to `*` to override all
* fields.
* Updatable fields:
* * `labels`
* * `online_serving_config.fixed_node_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
onChanged();
} else {
updateMaskBuilder_.setMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* Featurestore resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then only the non-empty fields present in the
* request will be overwritten. Set the update_mask to `*` to override all
* fields.
* Updatable fields:
* * `labels`
* * `online_serving_config.fixed_node_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
onChanged();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* Featurestore resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then only the non-empty fields present in the
* request will be overwritten. Set the update_mask to `*` to override all
* fields.
* Updatable fields:
* * `labels`
* * `online_serving_config.fixed_node_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (updateMask_ != null) {
updateMask_ =
com.google.protobuf.FieldMask.newBuilder(updateMask_).mergeFrom(value).buildPartial();
} else {
updateMask_ = value;
}
onChanged();
} else {
updateMaskBuilder_.mergeFrom(value);
}
return this;
}
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* Featurestore resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then only the non-empty fields present in the
* request will be overwritten. Set the update_mask to `*` to override all
* fields.
* Updatable fields:
* * `labels`
* * `online_serving_config.fixed_node_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder clearUpdateMask() {
if (updateMaskBuilder_ == null) {
updateMask_ = null;
onChanged();
} else {
updateMask_ = null;
updateMaskBuilder_ = null;
}
return this;
}
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* Featurestore resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then only the non-empty fields present in the
* request will be overwritten. Set the update_mask to `*` to override all
* fields.
* Updatable fields:
* * `labels`
* * `online_serving_config.fixed_node_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* Featurestore resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then only the non-empty fields present in the
* request will be overwritten. Set the update_mask to `*` to override all
* fields.
* Updatable fields:
* * `labels`
* * `online_serving_config.fixed_node_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Field mask is used to specify the fields to be overwritten in the
* Featurestore resource by the update.
* The fields specified in the update_mask are relative to the resource, not
* the full request. A field will be overwritten if it is in the mask. If the
* user does not provide a mask then only the non-empty fields present in the
* request will be overwritten. Set the update_mask to `*` to override all
* fields.
* Updatable fields:
* * `labels`
* * `online_serving_config.fixed_node_count`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest)
private static final com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest();
}
public static com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateFeaturestoreRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateFeaturestoreRequest>() {
@java.lang.Override
public UpdateFeaturestoreRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new UpdateFeaturestoreRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<UpdateFeaturestoreRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateFeaturestoreRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.UpdateFeaturestoreRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| apache-2.0 |
MSG134/IVCT_Framework | Command/src/main/java/nato/ivct/commander/TcLoggerData.java | 2874 | /* Copyright 2020, Reinhard Herzog, Johannes Mulder (Fraunhofer IOSB)
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 nato.ivct.commander;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import ch.qos.logback.classic.Level;
public class TcLoggerData {
private static Map<String, LoggerData> loggerDataMap = new HashMap<>();
private static String levelStr = "INFO";
public static LoggerData getLoggerData(final String loggerName) {
LoggerData loggerData = loggerDataMap.get(loggerName);
return loggerData;
}
public static void addLoggerData(final Logger logger, final String loggerName, final String sutName, final String badgeName, final String tcName) {
ch.qos.logback.classic.Logger lo = (ch.qos.logback.classic.Logger) logger;
setLogLevel(lo, levelStr);
LoggerData loggerData = new LoggerData(logger, sutName, badgeName, tcName);
loggerDataMap.put(loggerName, loggerData);
}
public static Level getLogLevel() {
Level level = null;
switch (levelStr) {
case "ERROR":
level = Level.ERROR;
break;
case "WARNING":
level = Level.WARN;
break;
case "INFO":
level = Level.INFO;
break;
case "DEBUG":
level = Level.DEBUG;
break;
case "TRACE":
level = Level.TRACE;
break;
}
return level;
}
public static Set<Logger> getLoggers() {
Set<Logger> loggers = new HashSet<>();
for (Map.Entry<String, LoggerData> entry : loggerDataMap.entrySet()) {
loggers.add(entry.getValue().logger);
}
return loggers;
}
public static void removeLogger(final String loggerName) {
loggerDataMap.remove(loggerName);
}
public static void setLogLevel(final String level) {
levelStr = level;
for (Map.Entry<String, LoggerData> entry : loggerDataMap.entrySet()) {
ch.qos.logback.classic.Logger lo = (ch.qos.logback.classic.Logger) entry.getValue().logger;
setLogLevel(lo, level);
entry.getValue().logger.warn("setLogLevel {}", level);
}
}
public static void setLogLevel(final ch.qos.logback.classic.Logger lo, final String level) {
switch (level) {
case "ERROR":
lo.setLevel(Level.ERROR);
break;
case "WARNING":
lo.setLevel(Level.WARN);
break;
case "INFO":
lo.setLevel(Level.INFO);
break;
case "DEBUG":
lo.setLevel(Level.DEBUG);
break;
case "TRACE":
lo.setLevel(Level.TRACE);
break;
}
}
}
| apache-2.0 |
ctripcorp/x-pipe | core/src/main/java/com/ctrip/xpipe/config/CompositeConfig.java | 661 | package com.ctrip.xpipe.config;
import com.ctrip.xpipe.api.config.Config;
import java.util.LinkedList;
import java.util.List;
/**
* @author wenchao.meng
*
* Aug 9, 2016
*/
public class CompositeConfig extends AbstractConfig{
private List<Config> configs = new LinkedList<>();
public CompositeConfig(Config ... configsArgu) {
for(Config config : configsArgu){
configs.add(config);
}
}
public void addConfig(Config config){
configs.add(config);
}
@Override
public String get(String key) {
for(Config config : configs){
String value = config.get(key);
if( value != null){
return value;
}
}
return null;
}
}
| apache-2.0 |
OpenWiseSolutions/openhub-ri | openhub-ext/src/main/java/org/openhubframework/openhub/ri/ServiceEnum.java | 1084 | /*
* Copyright 2002-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 org.openhubframework.openhub.ri;
import org.openhubframework.openhub.api.entity.ServiceExtEnum;
/**
* Enumeration of possible services (aka modules).
*
* @author Petr Juza
* @since 1.0.0
*/
public enum ServiceEnum implements ServiceExtEnum {
/**
* Translates input text.
*/
TRANSLATE,
/**
* Gets exchange rates.
*/
EXCHANGE_RATE;
@Override
public String getServiceName() {
return name();
}
}
| apache-2.0 |
bsensale/qp-iif-utility | src/test/java/net/sensale/qp/quickbooks/TransactionCreateSplitLineTest.java | 6371 | /**
* Copyright 2014 Brian Sensale
*
* 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.sensale.qp.quickbooks;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class TransactionCreateSplitLineTest {
Transaction t;
private String mMemoValue = "This is an awesome memo";
private String mShowName = "\"Awesome Show\"";
@Before
public void setUp() {
t = new Transaction();
t.mAccount = Account.DOOR_SALES;
t.mClass = QBClass.SHOW;
t.mName = mShowName;
TransactionLine tl = new TransactionLine(
new Date("1/1/2002"),
Account.DOOR_SALES,
new Name("name"),
QBClass.SHOW,
new Amount(233.00),
new Memo(mMemoValue));
t.mTransLine = tl;
}
String incomeLine = "SPL\t\"9/4/2009\"\t\"Other Income\" \t\"Person\"\t-20.00";
@Test
public void testShowIncome() {
SplitLine line = t.createSplitLine(incomeLine);
assertEquals("Wrong Date", "\"9/4/2009\"", line.mDate.toString());
assertEquals("Wrong Account", Account.DOOR_SALES, line.mAccount);
assertEquals("Wrong Name", mShowName, line.mName.toString());
assertEquals("Wrong class", QBClass.SHOW, line.mClass);
assertEquals("Wrong amount", "-20.00", line.mAmount.toString());
assertEquals("Wrong memo", "\"" + mMemoValue + "\"", line.mMemo.toString());
}
@Test
public void testSeasubIncome() {
t.mAccount = Account.SEA_SUB;
t.mClass = QBClass.HOUSE;
t.mName = "Person";
SplitLine line = t.createSplitLine(incomeLine);
assertEquals("Wrong Date", "\"9/4/2009\"", line.mDate.toString());
assertEquals("Wrong Account", Account.SEA_SUB, line.mAccount);
assertEquals("Wrong Name", "\"Person\"", line.mName.toString());
assertEquals("Wrong class", QBClass.HOUSE, line.mClass);
assertEquals("Wrong amount", "-20.00", line.mAmount.toString());
assertEquals("Wrong memo", "\"" + mMemoValue + "\"", line.mMemo.toString());
}
@Test
public void testFundraiserIncome() {
t.mAccount = Account.DOOR_SALES;
t.mClass = QBClass.HOUSE;
t.mName = "Fundraiser";
SplitLine line = t.createSplitLine(incomeLine);
assertEquals("Wrong Date", "\"9/4/2009\"", line.mDate.toString());
assertEquals("Wrong Account", Account.DOOR_SALES, line.mAccount);
assertEquals("Wrong Name", "\"Fundraiser\"", line.mName.toString());
assertEquals("Wrong class", QBClass.HOUSE, line.mClass);
assertEquals("Wrong amount", "-20.00", line.mAmount.toString());
assertEquals("Wrong memo", "\"" + mMemoValue + "\"", line.mMemo.toString());
}
String expenseLine = "SPL\t\"9/4/2009\"\t\"Other Expenses\"\tFee\t2.04";
@Test
public void testShowExpense() {
SplitLine line = t.createSplitLine(expenseLine);
assertEquals("Wrong Date", "\"9/4/2009\"", line.mDate.toString());
assertEquals("Wrong Account", Account.PAYPAL_EXPENSE, line.mAccount);
assertEquals("Wrong Name", mShowName, line.mName.toString());
assertEquals("Wrong class", QBClass.SHOW, line.mClass);
assertEquals("Wrong amount", "2.04", line.mAmount.toString());
assertEquals("Wrong memo", "\"" + mMemoValue + "\"", line.mMemo.toString());
}
@Test
public void testSeasubExpense() {
t.mAccount = Account.SEA_SUB;
t.mClass = QBClass.HOUSE;
t.mName = "Person";
SplitLine line = t.createSplitLine(expenseLine);
assertEquals("Wrong Date", "\"9/4/2009\"", line.mDate.toString());
assertEquals("Wrong Account", Account.PAYPAL_EXPENSE, line.mAccount);
assertEquals("Wrong Name", "\"Person\"", line.mName.toString());
assertEquals("Wrong class", QBClass.HOUSE, line.mClass);
assertEquals("Wrong amount", "2.04", line.mAmount.toString());
assertEquals("Wrong memo", "\"" + mMemoValue + "\"", line.mMemo.toString());
}
@Test
public void testFundraiserExpense() {
t.mAccount = Account.DOOR_SALES;
t.mClass = QBClass.HOUSE;
t.mName = "Fundraiser";
SplitLine line = t.createSplitLine(expenseLine);
assertEquals("Wrong Date", "\"9/4/2009\"", line.mDate.toString());
assertEquals("Wrong Account", Account.PAYPAL_EXPENSE, line.mAccount);
assertEquals("Wrong Name", "\"Fundraiser\"", line.mName.toString());
assertEquals("Wrong class", QBClass.HOUSE, line.mClass);
assertEquals("Wrong amount", "2.04", line.mAmount.toString());
assertEquals("Wrong memo", "\"" + mMemoValue + "\"", line.mMemo.toString());
}
@Test
public void testBadNumberArgs() {
String tooMany = "SPL\t1/1/2009\tOther Income\tFoobar\t2\tThis memosucks";
SplitLine line = t.createSplitLine(tooMany);
assertEquals("Wrong Date", "\"1/1/2009\"", line.mDate.toString());
assertEquals("Wrong Account", Account.DOOR_SALES, line.mAccount);
assertEquals("Wrong Name", mShowName, line.mName.toString());
assertEquals("Wrong class", QBClass.SHOW, line.mClass);
assertEquals("Wrong amount", "2.00", line.mAmount.toString());
assertEquals("Wrong memo", "\"" + mMemoValue + "\"", line.mMemo.toString());
}
@Test(expected=IllegalArgumentException.class)
public void testTooMany() {
t.createSplitLine("SPL\foo");
}
@Test(expected=IllegalArgumentException.class)
public void testBadStart() {
t.createSplitLine("SP L\t1\t2\t3\t4\t5");
}
}
| apache-2.0 |
ZhangQinglian/clippings_ui | src/main/java/com/zql/android/clippings/bridge/mvpc/IContract.java | 919 | /*******************************************************************************
* Copyright 2017-present, Clippings Contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.zql.android.clippings.bridge.mvpc;
/**
* Base interface od Contract
*/
public interface IContract {
}
| apache-2.0 |
math4youbyusgroupillinois/apigee-android-sdk | source/src/main/java/com/apigee/sdk/apm/android/AbstractURLWrapper.java | 1842 | package com.apigee.sdk.apm.android;
import java.net.Proxy;
import java.net.URLConnection;
public abstract class AbstractURLWrapper implements URLWrapper {
private java.net.URL realURL;
public AbstractURLWrapper(java.net.URL theRealURL)
{
realURL = theRealURL;
}
public boolean equals(Object o)
{
return realURL.equals(o);
}
public java.net.URL getRealURL()
{
return realURL;
}
public String getAuthority()
{
return realURL.getAuthority();
}
public abstract Object getContent(Class[] types) throws java.io.IOException;
public abstract Object getContent() throws java.io.IOException;
public int getDefaultPort()
{
return realURL.getDefaultPort();
}
public String getFile()
{
return realURL.getFile();
}
public String getHost()
{
return realURL.getHost();
}
public String getPath()
{
return realURL.getPath();
}
public int getPort()
{
return realURL.getPort();
}
public String getProtocol()
{
return realURL.getProtocol();
}
public String getQuery()
{
return realURL.getQuery();
}
public String getRef()
{
return realURL.getRef();
}
public String getUserInfo()
{
return realURL.getUserInfo();
}
public int hashCode()
{
return realURL.hashCode();
}
public abstract URLConnection openConnection(Proxy proxy) throws java.io.IOException;
public abstract URLConnection openConnection() throws java.io.IOException;
public boolean sameFile(java.net.URL otherURL)
{
return realURL.sameFile(otherURL);
}
public String toExternalForm()
{
return realURL.toExternalForm();
}
public String toString()
{
return realURL.toString();
}
public java.net.URI toURI() throws java.net.URISyntaxException
{
return realURL.toURI();
}
protected String urlAsString() {
return realURL.toString();
}
}
| apache-2.0 |
grzesuav/gjpf-core | main/src/main/java/gov/nasa/jpf/util/event/Event.java | 13971 | /*
* Copyright (C) 2014, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The Java Pathfinder core (jpf-core) platform is 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 gov.nasa.jpf.util.event;
import gov.nasa.jpf.util.Misc;
import gov.nasa.jpf.util.OATHash;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
/**
* class that represents an external stimulus to the SUT, which is produced by EventTree instances
* (our environment models)
* <p>
* Note that albeit concrete EventTree can provide their own, specialized Event types, this class
* is generic enough that we don't declare it as abstract
*/
public class Event implements Cloneable {
static final Object[] NO_ARGUMENTS = new Object[0];
//--- linkage
protected Event next;
protected Event prev;
protected Event alt;
//--- payload
protected String name;
protected Object[] arguments;
protected Object source; // optional, set on demand to keep track of where an event came from
public Event(String name) {
this(name, NO_ARGUMENTS, null);
}
public Event(String name, Object source) {
this(name, NO_ARGUMENTS, source);
}
public Event(String name, Object[] arguments) {
this(name, arguments, null);
}
public Event(String name, Object[] arguments, Object source) {
this.name = name;
this.arguments = arguments != null ? arguments : NO_ARGUMENTS;
this.source = source;
}
@Override
public boolean equals(Object o) {
if (o instanceof Event) {
Event other = (Event) o;
if (name.equals(other.name)) {
return Misc.equals(arguments, other.arguments);
}
}
return false;
}
@Override
public int hashCode() {
int h = name.hashCode();
for (int i = 0; i < arguments.length; i++) {
h = OATHash.hashMixin(h, arguments[i].hashCode());
}
return OATHash.hashFinalize(h);
}
protected void setNext(Event e) {
next = e;
e.prev = this;
}
protected void setPrev(Event e) {
prev = e;
if (alt != null) {
alt.setPrev(e);
}
}
protected void setAlt(Event e) {
alt = e;
if (prev != null) {
e.setPrev(prev);
}
}
public void setLinksFrom(Event other) {
prev = other.prev;
next = other.next;
alt = other.alt;
}
public Event replaceWithSequenceFrom(List<Event> list) {
Event eLast = null;
for (Event e : list) {
if (eLast == null) {
e.prev = prev;
e.alt = alt;
} else {
e.prev = eLast;
eLast.next = e;
}
eLast = e;
}
if (eLast != null) {
eLast.next = next;
return list.get(0);
} else {
return null;
}
}
public Event replaceWithAlternativesFrom(List<Event> list) {
Event eLast = null;
for (Event e : list) {
e.prev = prev;
e.next = next;
if (eLast != null) {
eLast.alt = e;
}
eLast = e;
}
if (eLast != null) {
eLast.alt = alt;
return list.get(0);
} else {
return null;
}
}
public Event replaceWith(Event e) {
e.prev = prev;
e.next = next;
e.alt = alt;
return e;
}
protected void setSource(Object source) {
this.source = source;
}
public int getNumberOfAlternatives() {
int n = 0;
for (Event e = alt; e != null; e = e.alt) {
n++;
}
return n;
}
public boolean hasAlternatives() {
return (alt != null);
}
public List<Event> getAlternatives() {
List<Event> list = new ArrayList<Event>();
list.add(this);
for (Event e = alt; e != null; e = e.alt) {
list.add(e);
}
return list;
}
public Event unlinkedClone() {
try {
Event e = (Event) super.clone();
e.next = e.prev = e.alt = null;
return e;
} catch (CloneNotSupportedException x) {
throw new RuntimeException("event clone failed", x);
}
}
public Event clone() {
try {
return (Event) super.clone();
} catch (CloneNotSupportedException cnsx) {
throw new RuntimeException("Event clone failed");
}
}
public Event deepClone() {
try {
Event e = (Event) super.clone();
if (next != null) {
e.next = next.deepClone();
e.next.prev = e;
if (next.alt != null) {
e.next.alt.prev = e;
}
}
if (alt != null) {
e.alt = alt.deepClone();
}
return e;
} catch (CloneNotSupportedException x) {
throw new RuntimeException("event clone failed", x);
}
}
public String getName() {
return name;
}
public Object[] getArguments() {
return arguments;
}
public Object getArgument(int idx) {
if (idx < arguments.length) {
return arguments[idx];
}
return null;
}
public Event getNext() {
return next;
}
public Event getAlt() {
return alt;
}
public Event getPrev() {
return prev;
}
public Object getSource() {
return source;
}
public Event addNext(Event e) {
boolean first = true;
for (Event ee : endEvents()) { // this includes alternatives
if (!first) {
e = e.deepClone();
} else {
first = false; // first one doesn't need a clone
}
ee.setNext(e);
e.setPrev(ee);
}
return this;
}
public Event addAlternative(Event e) {
Event ea;
for (ea = this; ea.alt != null; ea = ea.alt) ;
ea.setAlt(e);
if (next != null) {
e.setNext(next.deepClone());
}
return this;
}
protected static Event createClonedSequence(int firstIdx, int len, Event[] events) {
Event base = events[firstIdx].unlinkedClone();
Event e = base;
for (int i = firstIdx + 1; i < len; i++) {
Event ne = events[i].unlinkedClone();
e.setNext(ne);
e = ne;
}
return base;
}
/**
* extend this tree with a new path
*/
public void addPath(int pathLength, Event... path) {
Event t = this;
Event pe;
outer:
for (int i = 0; i < pathLength; i++) {
pe = path[i];
for (Event te = t; te != null; te = te.alt) {
if (pe.equals(te)) { // prefix is in tree
if (te.next == null) { // reached tree leaf
if (++i < pathLength) { // but the path still has events
Event tail = createClonedSequence(i, pathLength, path);
te.setNext(tail);
tail.setAlt(new NoEvent()); // preserve the tree path
}
return;
} else { // there is a next in the tree
t = te.next;
if (i == pathLength - 1) { // but the path is done, add a NoEvent as a next alternative to mark the end
Event e = t.getLastAlt();
e.setAlt(new NoEvent());
return;
} else {
continue outer;
}
}
}
}
//--- path prefix was not in tree, append as (last) alternative
Event tail = createClonedSequence(i, pathLength, path);
Event e = t.getLastAlt();
e.setAlt(tail);
return;
}
}
public Event getLastAlt() {
Event e;
for (e = this; e.alt != null; e = e.alt) ;
return e;
}
protected void collectEndEvents(List<Event> list, boolean includeNoEvents) {
if (next != null) {
next.collectEndEvents(list, includeNoEvents);
} else { // base case: no next
// strip trailing NoEvents
if (prev == null) {
list.add(this); // root NoEvents have to stay
} else { // else we skip trailing NoEvents up to root
Event ee = this;
if (!includeNoEvents) {
for (Event e = this; e.prev != null && (e instanceof NoEvent); e = e.prev) {
ee = e.prev;
}
}
list.add(ee);
}
}
if (alt != null) {
alt.collectEndEvents(list, includeNoEvents);
}
}
public Event endEvent() {
if (next != null) {
return next.endEvent();
} else {
return this;
}
}
public List<Event> visibleEndEvents() {
List<Event> list = new ArrayList<Event>();
collectEndEvents(list, false);
return list;
}
public List<Event> endEvents() {
List<Event> list = new ArrayList<Event>();
collectEndEvents(list, true);
return list;
}
private void interleave(Event a, Event b, Event[] path, int pathLength, int i, Event result) {
if (a == null && b == null) { // base case
result.addPath(pathLength, path);
} else {
if (a != null) {
path[i] = a;
interleave(a.prev, b, path, pathLength, i - 1, result);
}
if (b != null) {
path[i] = b;
interleave(a, b.prev, path, pathLength, i - 1, result);
}
}
}
/**
* this creates a new tree that contains all paths resulting from
* all interleavings of all paths of this tree with the specified other events
* <p>
* BEWARE: this is a combinatorial bomb that should only be used if we know all
* paths are short
*/
public Event interleave(Event... otherEvents) {
Event t = new NoEvent(); // we need a root for the new tree
Event[] pathBuffer = new Event[32];
int mergedTrees = 0;
for (Event o : otherEvents) {
List<Event> endEvents = (mergedTrees++ > 0) ? t.visibleEndEvents() : visibleEndEvents();
for (Event ee1 : endEvents) {
for (Event ee2 : o.visibleEndEvents()) {
int n = ee1.getPathLength() + ee2.getPathLength();
if (n > pathBuffer.length) {
pathBuffer = new Event[n];
}
interleave(ee1, ee2, pathBuffer, n, n - 1, t);
}
}
}
return t.alt;
}
private void removeSource(Object src, Event[] path, int i, Event result) {
if (alt != null) {
alt.removeSource(src, path, i, result);
}
if (source != src) {
path[i++] = this;
}
if (next != null) {
next.removeSource(src, path, i, result);
} else { // done, add path to result
result.addPath(i, path);
}
}
/**
* remove all events from this tree that are from the specified source
*/
public Event removeSource(Object src) {
Event base = new NoEvent(); // we need a root to add to
int maxDepth = getMaxDepth();
Event[] pathBuffer = new Event[maxDepth];
removeSource(src, pathBuffer, 0, base);
return base.alt;
}
private void printPath(PrintStream ps, boolean isLast) {
if (prev != null) {
prev.printPath(ps, false);
}
if (!isNoEvent()) {
ps.print(name);
if (!isLast) {
ps.print(',');
}
}
}
public void printPath(PrintStream ps) {
printPath(ps, true);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(name);
if (arguments != NO_ARGUMENTS) {
sb.append('(');
boolean first = true;
for (Object a : arguments) {
if (first) {
first = false;
} else {
sb.append(',');
}
sb.append(a.toString());
}
sb.append(')');
}
return sb.toString();
}
/**
* upwards path length
*/
public int getPathLength() {
int n = 0;
for (Event e = this; e != null; e = e.prev) {
n++;
}
return n;
}
private int getMaxDepth(int depth) {
int maxAlt = depth;
int maxNext = depth;
if (alt != null) {
maxAlt = alt.getMaxDepth(depth);
}
if (next != null) {
maxNext = next.getMaxDepth(depth + 1);
}
if (maxAlt > maxNext) {
return maxAlt;
} else {
return maxNext;
}
}
/**
* maximum downwards tree depth
*/
public int getMaxDepth() {
return getMaxDepth(1);
}
public Event[] getPath() {
int n = getPathLength();
Event[] trace = new Event[n];
for (Event e = this; e != null; e = e.prev) {
trace[--n] = e;
}
return trace;
}
public void printTree(PrintStream ps, int level) {
for (int i = 0; i < level; i++) {
ps.print(". ");
}
ps.print(this);
//ps.print(" [" + prev + ']');
ps.println();
if (next != null) {
next.printTree(ps, level + 1);
}
if (alt != null) {
alt.printTree(ps, level);
}
}
public boolean isEndOfTrace(String[] eventNames) {
int n = eventNames.length - 1;
for (Event e = this; e != null; e = e.prev) {
if (e.getName().equals(eventNames[n])) {
n--;
} else {
return false;
}
}
return (n == 0);
}
protected void collectTrace(StringBuilder sb, String separator, boolean isLast) {
if (prev != null) {
prev.collectTrace(sb, separator, false);
}
if (!isNoEvent()) {
sb.append(toString());
if (!isLast && separator != null) {
sb.append(separator);
}
}
}
public String getPathString(String separator) {
StringBuilder sb = new StringBuilder();
collectTrace(sb, separator, true);
return sb.toString();
}
public boolean isNoEvent() {
return false;
}
public boolean isSystemEvent() {
return false;
}
//--- generic processing interface
public void process(Object source) {
// can be overridden by subclass if instance has sufficient context info
}
public void setProcessed() {
// can be overridden by subclass, e.g. to maintain event caches
}
}
| apache-2.0 |
Skullabs/kikaha | kikaha-modules/kikaha-urouting/tests/kikaha/urouting/it/params/PathParametersIntegrationTest.java | 1668 | package kikaha.urouting.it.params;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import kikaha.core.test.KikahaServerRunner;
import kikaha.urouting.it.Http;
import kikaha.urouting.it.Http.EmptyText;
import okhttp3.*;
import okhttp3.Request.Builder;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author: miere.teixeira
*/
@RunWith( KikahaServerRunner.class )
public class PathParametersIntegrationTest {
final Request.Builder request = new Builder().url( "http://localhost:19999/it/parameters/path/12" );
@Test
public void ensureCanSendGet() throws IOException {
final Response response = Http.send( this.request.get() );
ensureHaveTheExpectedResponse( response );
}
@Test
public void ensureCanSendPost() throws IOException {
final Response response = Http.send( this.request.post( new EmptyText() ) );
ensureHaveTheExpectedResponse( response );
}
@Test
public void ensureCanSendPut() throws IOException {
final Response response = Http.send( this.request.put( new EmptyText() ) );
ensureHaveTheExpectedResponse( response );
}
@Test
public void ensureCanSendPatch() throws IOException {
final Response response = Http.send( this.request.patch( new EmptyText() ) );
ensureHaveTheExpectedResponse( response );
}
@Test
public void ensureCanSendDelete() throws IOException {
final Response response = Http.send( this.request.delete() );
ensureHaveTheExpectedResponse( response );
}
void ensureHaveTheExpectedResponse( final Response response ) throws IOException {
assertEquals( 200, response.code() );
assertEquals( 12, Integer.valueOf( response.body().string() ), 0 );
}
}
| apache-2.0 |
patrickvanamstel/SimplerInvoicing | si-sender/src/main/java/nl/kaninefatendreef/si/document/SIDocumentSenderException.java | 318 | package nl.kaninefatendreef.si.document;
import nl.kaninefatendreef.si.SIException;
@SuppressWarnings("serial")
public class SIDocumentSenderException extends SIException {
public SIDocumentSenderException(Throwable t) {
super(t);
}
public SIDocumentSenderException(String message) {
super(message);
}
}
| apache-2.0 |
eID-Testbeds/server | eidsrv-testbed-common/src/main/java/com/secunet/eidserver/testbed/common/helper/CryptoHelper.java | 13112 | package com.secunet.eidserver.testbed.common.helper;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import com.secunet.eidserver.testbed.common.ics.IcsXmlsecSignatureUri;
import com.secunet.eidserver.testbed.common.types.testcase.EService;
import com.secunet.testbedutils.cvc.cvcertificate.CVCertificate;
import com.secunet.testbedutils.cvc.cvcertificate.DataBuffer;
import com.secunet.testbedutils.cvc.cvcertificate.exception.CVBufferNotEmptyException;
import com.secunet.testbedutils.cvc.cvcertificate.exception.CVDecodeErrorException;
import com.secunet.testbedutils.cvc.cvcertificate.exception.CVInvalidDateException;
import com.secunet.testbedutils.cvc.cvcertificate.exception.CVInvalidECPointLengthException;
import com.secunet.testbedutils.cvc.cvcertificate.exception.CVInvalidOidException;
import com.secunet.testbedutils.cvc.cvcertificate.exception.CVTagNotFoundException;
/**
* Helper class
*/
public class CryptoHelper
{
static
{
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
}
public enum Protocol
{
SAML_PROT_ID("SAML"), SOAP_PROT_ID("SOAP");
private final String value;
private Protocol(String value)
{
this.value = value;
}
public String getProtocolName()
{
return value;
}
}
public enum Algorithm
{
RSA_ALG_ID("RSA"), ECDSA_ALG_ID("ECDSA"), DSA_ALG_ID("DSA"), HMAC_ALG_ID("HMAC");
private final String value;
private Algorithm(String value)
{
this.value = value;
}
public String getAlgorithmName()
{
return value;
}
/**
* Returns the enum value that represents the algorithm with the given name
*
* @param name
* Name
*/
public static Algorithm getFromEnumName(String name)
{
for (Algorithm x : Algorithm.values())
{
if (name != null && name.equals(x.toString()))
{
return x;
}
}
return null;
}
/**
* Returns the enum value that represents the algorithm with the given algorithm name
*
* @param name
* Name
*/
public static Algorithm getFromAlgorithmName(String name)
{
for (Algorithm x : Algorithm.values())
{
if (name != null && name.equals(x.getAlgorithmName()))
{
return x;
}
}
return null;
}
}
private static final Logger logger = LogManager.getLogger(CryptoHelper.class);
/*
* Determine algorithm from a given signature URL
*
* @param url Signature URL
*/
public static String getAlgorithmForSignatureUrl(String url)
{
String returnValue = null;
if (url == null)
return null;
if (url.contains("sha1"))
{
returnValue = "SHA1";
}
else if (url.endsWith("ripemd160"))
{
returnValue = "RIPEMD160";
}
// shaXXX
else
{
returnValue = url.substring(url.length() - "shaXXX".length(), url.length()).toUpperCase();
}
returnValue += "with";
if (url.contains("rsa"))
{
returnValue += "RSA";
}
else if (url.contains("ecdsa"))
{
returnValue += "ECDSA";
}
else if (url.contains("dsa"))
{
returnValue += "DSA";
}
else
{
returnValue += "HMAC";
}
return returnValue;
}
/**
* Determine algorithm from a given string
*
* @param toCheck
* String to check
*
* @param toUpperCase
* If true returned algorithm is in upper case, if false in lower case
*
* @return Algorithm identifier or null if nothing valid has been found
*/
public static String getAlgorithm(String toCheck, boolean toUpperCase)
{
String returnValue = null;
if (toCheck == null)
return null;
String lowerToCheck = toCheck.toLowerCase();
if (lowerToCheck.contains("rsa"))
{
returnValue = "rsa";
}
else if (lowerToCheck.contains("ecdsa"))
{
returnValue = "ecdsa";
}
else if (lowerToCheck.contains("dsa"))
{
returnValue = "dsa";
}
else if (lowerToCheck.contains("hmac"))
{
returnValue = "hmac";
}
if ((returnValue != null) && (toUpperCase))
{
returnValue = returnValue.toUpperCase();
}
return returnValue;
}
/**
* Get a list of all supported signature algorithms regarding a given crypto algorithm
*
* @param algorithm
* Algorithm
* @return Supported signature algorithms
*/
public static List<String> getSupportedSignatureAlgorithms(String algorithm)
{
List<String> listURI = new LinkedList<String>();
if (CryptoHelper.Algorithm.RSA_ALG_ID.getAlgorithmName().equals(algorithm))
{
// listURIRSA.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2001_04_XMLDSIG_MORE_RSA_MD_5.value()); // Not supported
listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2000_09_XMLDSIG_RSA_SHA_1.value());
// listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2001_04_XMLDSIG_MORE_RSA_SHA_224.value()); // Not supported
listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2001_04_XMLDSIG_MORE_RSA_SHA_256.value());
listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2001_04_XMLDSIG_MORE_RSA_SHA_384.value());
listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2001_04_XMLDSIG_MORE_RSA_SHA_512.value());
// listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2001_04_XMLDSIG_MORE_RSA_RIPEMD_160.value()); // Not supported
}
else if (CryptoHelper.Algorithm.DSA_ALG_ID.getAlgorithmName().equals(algorithm))
{
listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2000_09_XMLDSIG_DSA_SHA_1.value());
listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2009_XMLDSIG_11_DSA_SHA_256.value());
}
else if (CryptoHelper.Algorithm.DSA_ALG_ID.getAlgorithmName().equals(algorithm))
{
listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2001_04_XMLDSIG_MORE_ECDSA_SHA_1.value());
// listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2001_04_XMLDSIG_MORE_ECDSA_SHA_224.value());
listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2001_04_XMLDSIG_MORE_ECDSA_SHA_256.value());
listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2001_04_XMLDSIG_MORE_ECDSA_SHA_384.value());
listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2001_04_XMLDSIG_MORE_ECDSA_SHA_512.value());
}
else if (CryptoHelper.Algorithm.HMAC_ALG_ID.getAlgorithmName().equals(algorithm))
{
listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2000_09_XMLDSIG_HMAC_SHA_1.value());
// listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2001_04_XMLDSIG_MORE_HMAC_SHA_224.value());
listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2001_04_XMLDSIG_MORE_HMAC_SHA_256.value());
listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2001_04_XMLDSIG_MORE_HMAC_SHA_384.value());
listURI.add(IcsXmlsecSignatureUri.HTTP_WWW_W_3_ORG_2001_04_XMLDSIG_MORE_HMAC_SHA_512.value());
}
return listURI;
}
/**
* Load the certificate with the given name from the file system. For valid parameter values:
*
* @see com.secunet.eidserver.testbed.common.constants.GeneralConstants for valid parameter values
*
* @param protocol
* Protocol identifier
* @param alg
* Algorithm identifier
* @param eservice
* {@link EService} The eService for which the certificate is to be loaded.
* @return {@link X509Certificate}
*/
public static X509Certificate loadSignatureCertificate(Protocol protocol, Algorithm alg, EService eservice)
{
return loadCertificate(protocol, alg, eservice.toString());
}
/**
* Returns the algorithm ID that needs to be used for a given {@link EService}.
*
* @param service
* {@link EService}
* @return {@link CryptoHelper.Algorithm} The algorithm to be used
*/
public static Algorithm getAlgorithmFromService(EService service)
{
switch (service)
{
case EDSA:
return CryptoHelper.Algorithm.DSA_ALG_ID;
case EECDSA:
return CryptoHelper.Algorithm.ECDSA_ALG_ID;
default:
return CryptoHelper.Algorithm.RSA_ALG_ID;
}
}
/**
* Load the certificate with the given name from the file system. For valid parameter values:
*
* @see com.secunet.eidserver.testbed.common.constants.GeneralConstants for valid parameter values
*
* @param protocol
* Protocol identifier
* @param alg
* Algorithm identifier
* @param name
* {@link String} The name of the certificate to load.
* @return {@link X509Certificate}
*/
public static X509Certificate loadCertificate(Protocol protocol, Algorithm alg, String name)
{
CertificateFactory certFactory;
try (InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("certificates/" + alg.getAlgorithmName() + "/" + name + ".crt");)
{
if (input != null)
{
certFactory = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME);
X509Certificate cert = (X509Certificate) certFactory.generateCertificate(input);
return cert;
}
}
catch (CertificateException | NoSuchProviderException | IOException e)
{
StringWriter trace = new StringWriter();
e.printStackTrace(new PrintWriter(trace));
logger.error("Could not load " + protocol.getProtocolName() + " x509 certificate " + name + " due to: " + e.getMessage() + System.getProperty("line.separator") + trace.toString());
}
return null;
}
/**
* Load the key with the given name from the file system.
*
* @see com.secunet.eidserver.testbed.common.constants.GeneralConstants for valid parameter values
*
* @param protocol
* Protocol identifier
* @param alg
* Algorithm identifier
* @param eservice
* {@link EService} The eService for which the key is to be loaded.
* @return {@link PrivateKey}
*/
public static PrivateKey loadSignatureKey(Protocol protocol, Algorithm alg, EService eservice)
{
return loadKey(protocol, alg, eservice.toString());
}
/**
* Load the key with the given name from the file system.
*
* @see com.secunet.eidserver.testbed.common.constants.GeneralConstants for valid parameter values
*
* @param protocol
* Protocol identifier
* @param alg
* Algorithm identifier
* @param name
* {@link String} The name of the key to load.
* @return {@link PrivateKey}
*/
public static PrivateKey loadKey(Protocol protocol, Algorithm alg, String name)
{
try (InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("keys/" + alg.getAlgorithmName() + "/" + name + ".der");)
{
if (input != null)
{
KeyFactory factory = KeyFactory.getInstance(alg.getAlgorithmName());
byte[] keyBytes = IOUtils.toByteArray(input);
KeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
return factory.generatePrivate(spec);
}
}
catch (InvalidKeySpecException | NoSuchAlgorithmException | IOException e)
{
StringWriter trace = new StringWriter();
e.printStackTrace(new PrintWriter(trace));
logger.error("Could not load " + protocol.getProtocolName() + " key " + name + " due to: " + e.getMessage() + System.getProperty("line.separator") + trace.toString());
}
return null;
}
/**
* Loads a CV certificate from the file with the given relative path
*
* @param path
* @return {@link CVCertificate} if the certificate was successfully loaded, or <i>null</i> otherwise
*/
public static CVCertificate loadCvFromFile(String path)
{
try
{
File expectedDvFile = new File(Thread.currentThread().getContextClassLoader().getResource(path).getFile());
DataBuffer cvBuffer = new DataBuffer(IOUtils.toByteArray(new FileInputStream(expectedDvFile)));
return new CVCertificate(cvBuffer);
}
catch (CVTagNotFoundException | CVBufferNotEmptyException | CVInvalidOidException | CVDecodeErrorException | CVInvalidDateException | CVInvalidECPointLengthException | IOException e)
{
StringWriter trace = new StringWriter();
e.printStackTrace(new PrintWriter(trace));
logger.error("Could not load expected DV certificate: " + e.getMessage() + System.getProperty("line.separator") + trace.toString());
}
return null;
}
}
| apache-2.0 |
jexp/idea2 | platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/PsiAwareFileEditorManagerImpl.java | 5665 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.fileEditor.impl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.impl.text.TextEditorPsiDataProvider;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.problems.WolfTheProblemSolver;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
/**
* @author yole
*/
public class PsiAwareFileEditorManagerImpl extends FileEditorManagerImpl {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileEditor.impl.text.PsiAwareFileEditorManagerImpl");
private final PsiManager myPsiManager;
private final WolfTheProblemSolver myProblemSolver;
/**
* Updates icons for open files when project roots change
*/
private final MyPsiTreeChangeListener myPsiTreeChangeListener;
private final WolfTheProblemSolver.ProblemListener myProblemListener;
public PsiAwareFileEditorManagerImpl(final Project project, final PsiManager psiManager, final WolfTheProblemSolver problemSolver) {
super(project);
myPsiManager = psiManager;
myProblemSolver = problemSolver;
myPsiTreeChangeListener = new MyPsiTreeChangeListener();
myProblemListener = new MyProblemListener();
registerExtraEditorDataProvider(new TextEditorPsiDataProvider(), null);
}
@Override
public void projectOpened() {
super.projectOpened(); //To change body of overridden methods use File | Settings | File Templates.
myPsiManager.addPsiTreeChangeListener(myPsiTreeChangeListener);
myProblemSolver.addProblemListener(myProblemListener);
}
@Override
public Color getFileColor(@NotNull final VirtualFile file) {
Color color = super.getFileColor(file);
if (myProblemSolver.isProblemFile(file)) {
return new Color(color.getRed(), color.getGreen(), color.getBlue(), WaverGraphicsDecorator.WAVE_ALPHA_KEY);
}
return color;
}
public boolean isProblem(@NotNull final VirtualFile file) {
return myProblemSolver.isProblemFile(file);
}
public String getFileTooltipText(final VirtualFile file) {
final StringBuilder tooltipText = new StringBuilder();
final Module module = ModuleUtil.findModuleForFile(file, getProject());
if (module != null) {
tooltipText.append("[");
tooltipText.append(module.getName());
tooltipText.append("] ");
}
tooltipText.append(file.getPresentableUrl());
return tooltipText.toString();
}
@Override
protected Editor getOpenedEditor(final Editor editor, final boolean focusEditor) {
PsiDocumentManager documentManager = PsiDocumentManager.getInstance(getProject());
Document document = editor.getDocument();
PsiFile psiFile = documentManager.getPsiFile(document);
if (!focusEditor || documentManager.isUncommited(document)) {
return editor;
}
return InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(editor, psiFile);
}
/**
* Updates attribute of open files when roots change
*/
private final class MyPsiTreeChangeListener extends PsiTreeChangeAdapter {
public void propertyChanged(final PsiTreeChangeEvent e) {
if (PsiTreeChangeEvent.PROP_ROOTS.equals(e.getPropertyName())) {
ApplicationManager.getApplication().assertIsDispatchThread();
final VirtualFile[] openFiles = getOpenFiles();
for (int i = openFiles.length - 1; i >= 0; i--) {
final VirtualFile file = openFiles[i];
LOG.assertTrue(file != null);
updateFileIcon(file);
}
}
}
public void childAdded(PsiTreeChangeEvent event) {
doChange(event);
}
public void childRemoved(PsiTreeChangeEvent event) {
doChange(event);
}
public void childReplaced(PsiTreeChangeEvent event) {
doChange(event);
}
public void childMoved(PsiTreeChangeEvent event) {
doChange(event);
}
public void childrenChanged(PsiTreeChangeEvent event) {
doChange(event);
}
private void doChange(final PsiTreeChangeEvent event) {
final PsiFile psiFile = event.getFile();
final VirtualFile currentFile = getCurrentFile();
if (currentFile != null && psiFile != null && psiFile.getVirtualFile() == currentFile) {
updateFileIcon(currentFile);
}
}
}
private class MyProblemListener extends WolfTheProblemSolver.ProblemListener {
public void problemsAppeared(final VirtualFile file) {
updateFile(file);
}
public void problemsDisappeared(VirtualFile file) {
updateFile(file);
}
public void problemsChanged(VirtualFile file) {
updateFile(file);
}
private void updateFile(final VirtualFile file) {
queueUpdateFile(file);
}
}
}
| apache-2.0 |
chinglimchan/Demo2016 | MultiThreadDemo/app/src/main/java/com/chenql/multithreaddemo/Constants.java | 559 | package com.chenql.multithreaddemo;
/**
* Constants
* Created by chinglimchan on 7/10/2016.
*/
public class Constants {
/**
* target installed
*/
public static final int STATUS_INSTALLED = 0X0001;
/**
* target downloaded but not installed
*/
public static final int STATUS_DOWNLOADED = 0X0002;
/**
* target is downloading
*/
public static final int STATUS_DOWNLOADING = 0X0003;
/**
* target is neither downloaded nor installed
*/
public static final int STATUS_NULL = 0X0004;
}
| apache-2.0 |
Legioth/vaadin | uitest/src/main/java/com/vaadin/v7/tests/components/grid/GridExtensionCommunication.java | 2604 | /*
* Copyright 2000-2016 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.v7.tests.components.grid;
import com.vaadin.annotations.Widgetset;
import com.vaadin.server.VaadinRequest;
import com.vaadin.shared.MouseEventDetails;
import com.vaadin.tests.components.AbstractTestUIWithLog;
import com.vaadin.tests.widgetset.TestingWidgetSet;
import com.vaadin.tests.widgetset.client.v7.grid.GridClickExtensionConnector.GridClickServerRpc;
import com.vaadin.v7.data.Item;
import com.vaadin.v7.ui.Grid;
import com.vaadin.v7.ui.Grid.AbstractGridExtension;
import com.vaadin.v7.ui.Grid.Column;
import com.vaadin.v7.ui.Grid.SelectionMode;
@Widgetset(TestingWidgetSet.NAME)
public class GridExtensionCommunication extends AbstractTestUIWithLog {
public class GridClickExtension extends AbstractGridExtension {
public GridClickExtension(Grid grid) {
super(grid);
registerRpc(new GridClickServerRpc() {
@Override
public void click(String row, String column,
MouseEventDetails click) {
Object itemId = getItemId(row);
Column col = getColumn(column);
Item person = getParentGrid().getContainerDataSource()
.getItem(itemId);
log("Click on Person "
+ person.getItemProperty("firstName").getValue()
+ " "
+ person.getItemProperty("lastName").getValue()
+ " on column " + col.toString());
log("MouseEventDetails: " + click.getButtonName() + " ("
+ click.getClientX() + ", " + click.getClientY()
+ ")");
}
});
}
}
@Override
protected void setup(VaadinRequest request) {
Grid grid = new PersonTestGrid(50);
grid.setSelectionMode(SelectionMode.NONE);
new GridClickExtension(grid);
addComponent(grid);
}
}
| apache-2.0 |
abimarank/carbon-apimgt | components/apimgt/org.wso2.carbon.apimgt.core/src/test/java/org/wso2/carbon/apimgt/core/dao/impl/PolicyDAOImplIT.java | 29095 |
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.core.dao.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.wso2.carbon.apimgt.core.SampleTestObjectCreator;
import org.wso2.carbon.apimgt.core.TestUtil;
import org.wso2.carbon.apimgt.core.api.APIMgtAdminService;
import org.wso2.carbon.apimgt.core.dao.PolicyDAO;
import org.wso2.carbon.apimgt.core.exception.APIMgtDAOException;
import org.wso2.carbon.apimgt.core.exception.APIMgtResourceNotFoundException;
import org.wso2.carbon.apimgt.core.exception.BlockConditionAlreadyExistsException;
import org.wso2.carbon.apimgt.core.models.BlockConditions;
import org.wso2.carbon.apimgt.core.models.PolicyValidationData;
import org.wso2.carbon.apimgt.core.models.policy.APIPolicy;
import org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy;
import org.wso2.carbon.apimgt.core.models.policy.CustomPolicy;
import org.wso2.carbon.apimgt.core.models.policy.Policy;
import org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy;
import org.wso2.carbon.apimgt.core.util.APIMgtConstants;
import org.wso2.carbon.apimgt.core.util.ETagUtils;
import java.util.List;
import java.util.Set;
import java.util.UUID;
public class PolicyDAOImplIT extends DAOIntegrationTestBase {
private static final Logger log = LoggerFactory.getLogger(PolicyDAOImplIT.class);
@Test
public void testFingerprintAfterUpdatingAPIPolicy() throws Exception {
APIPolicy policy = SampleTestObjectCreator.createDefaultAPIPolicy();
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
policyDAO.addApiPolicy(policy);
String fingerprintBeforeUpdatingPolicy = ETagUtils
.generateETag(policyDAO.getLastUpdatedTimeOfThrottlingPolicy(APIMgtAdminService.PolicyLevel.api,
policy.getPolicyName()));
Assert.assertNotNull(fingerprintBeforeUpdatingPolicy);
APIPolicy updatedAPIPolicy = SampleTestObjectCreator.updateAPIPolicy(policy);
Thread.sleep(100L);
policyDAO.updateApiPolicy(updatedAPIPolicy);
String fingerprintAfterUpdatingPolicy = ETagUtils
.generateETag(policyDAO.getLastUpdatedTimeOfThrottlingPolicy(APIMgtAdminService.PolicyLevel.api,
updatedAPIPolicy.getPolicyName()));
Assert.assertNotNull(fingerprintAfterUpdatingPolicy);
Assert.assertNotEquals(fingerprintBeforeUpdatingPolicy, fingerprintAfterUpdatingPolicy, "Policy "
+ "fingerprint expected to be different before and after updating for policy: "
+ policy.getPolicyName());
updatedAPIPolicy.setUuid(null);
//test for exception
try {
policyDAO.updateApiPolicy(updatedAPIPolicy);
} catch (APIMgtDAOException ex) {
Assert.assertEquals(ex.getMessage(),
"Policy uuid is not found, unable to update policy: " + updatedAPIPolicy.getPolicyName());
}
}
@Test
public void testFingerprintAfterUpdatingApplicationPolicy() throws Exception {
ApplicationPolicy policy = SampleTestObjectCreator.createDefaultApplicationPolicy();
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
policyDAO.addApplicationPolicy(policy);
String fingerprintBeforeUpdatingPolicy = ETagUtils
.generateETag(policyDAO.getLastUpdatedTimeOfThrottlingPolicy(APIMgtAdminService.PolicyLevel.application,
policy.getPolicyName()));
Assert.assertNotNull(fingerprintBeforeUpdatingPolicy);
ApplicationPolicy updatedPolicy = SampleTestObjectCreator.updateApplicationPolicy(policy);
Thread.sleep(100L);
policyDAO.updateApplicationPolicy(updatedPolicy);
String fingerprintAfterUpdatingPolicy = ETagUtils
.generateETag(policyDAO.getLastUpdatedTimeOfThrottlingPolicy(APIMgtAdminService.PolicyLevel.application,
updatedPolicy.getPolicyName()));
Assert.assertNotNull(fingerprintAfterUpdatingPolicy);
Assert.assertNotEquals(fingerprintBeforeUpdatingPolicy, fingerprintAfterUpdatingPolicy, "Policy "
+ "fingerprint expected to be different before and after updating for policy: "
+ policy.getPolicyName());
//Test for exception uuid null
updatedPolicy.setUuid(null);
try {
policyDAO.updateApplicationPolicy(updatedPolicy);
} catch (APIMgtDAOException ex) {
Assert.assertEquals(ex.getMessage(),
"Policy uuid is not found, unable to update policy: " + updatedPolicy.getPolicyName());
}
}
@Test
public void testFingerprintAfterUpdatingSubscriptionPolicy() throws Exception {
SubscriptionPolicy policy = SampleTestObjectCreator.createDefaultSubscriptionPolicy();
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
policyDAO.addSubscriptionPolicy(policy);
String fingerprintBeforeUpdatingPolicy = ETagUtils
.generateETag(policyDAO.getLastUpdatedTimeOfThrottlingPolicy(APIMgtAdminService.PolicyLevel
.subscription, policy.getPolicyName()));
Assert.assertNotNull(fingerprintBeforeUpdatingPolicy);
SubscriptionPolicy updatedPolicy = SampleTestObjectCreator.updateSubscriptionPolicy(policy);
Thread.sleep(100L);
policyDAO.updateSubscriptionPolicy(updatedPolicy);
String fingerprintAfterUpdatingPolicy = ETagUtils
.generateETag(policyDAO.getLastUpdatedTimeOfThrottlingPolicy(APIMgtAdminService.PolicyLevel
.subscription, updatedPolicy.getPolicyName()));
Assert.assertNotNull(fingerprintAfterUpdatingPolicy);
Assert.assertNotEquals(fingerprintBeforeUpdatingPolicy, fingerprintAfterUpdatingPolicy, TestUtil.printDiff
(fingerprintBeforeUpdatingPolicy, fingerprintAfterUpdatingPolicy));
updatedPolicy.setUuid(null);
try {
policyDAO.updateSubscriptionPolicy(updatedPolicy);
} catch (APIMgtDAOException ex) {
Assert.assertEquals(ex.getMessage(),
"Policy uuid is not found, unable to update policy: " + updatedPolicy.getPolicyName());
}
}
@Test (description = "Add, Get and Delete an API policy")
public void testAddGetAndDeleteApiPolicy() throws Exception {
APIPolicy policy = SampleTestObjectCreator.createDefaultAPIPolicy();
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
//add policy
policyDAO.addApiPolicy(policy);
//get added policy
Policy addedPolicy = policyDAO.getApiPolicy(policy.getPolicyName());
Assert.assertNotNull(addedPolicy);
Assert.assertEquals(addedPolicy.getPolicyName(), policy.getPolicyName());
//delete policy
policyDAO.deletePolicy(APIMgtAdminService.PolicyLevel.api, policy.getPolicyName());
//get policy after deletion
try {
policyDAO.getApiPolicy(policy.getPolicyName());
Assert.fail("Exception expected, but not thrown.");
} catch (APIMgtDAOException ex) {
Assert.assertEquals(ex.getMessage(), "API Policy not found for name: " + addedPolicy.getPolicyName());
}
try {
policyDAO.getApiPolicyByUuid(policy.getUuid());
Assert.fail("Exception expected, but not thrown.");
} catch (APIMgtDAOException ex) {
Assert.assertEquals(ex.getMessage(), "API Policy not found for id: " + addedPolicy.getUuid());
}
}
@Test(description = "Add, Get and Delete an Application policy")
public void testAddGetAndDeleteApplicationPolicy() throws Exception {
ApplicationPolicy policy = SampleTestObjectCreator.createDefaultApplicationPolicy();
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
//add policy
policyDAO.addApplicationPolicy(policy);
//get added policy
Policy addedPolicy = policyDAO
.getApplicationPolicy(policy.getPolicyName());
Assert.assertNotNull(addedPolicy);
Assert.assertEquals(addedPolicy.getPolicyName(), policy.getPolicyName());
//delete policy
policyDAO.deletePolicy(APIMgtAdminService.PolicyLevel.application, policy.getPolicyName());
//get policy after deletion
try {
policyDAO.getApplicationPolicy(policy.getPolicyName());
Assert.fail("Exception expected, but not thrown.");
} catch (APIMgtDAOException ex) {
Assert.assertEquals(ex.getMessage(), "Application Policy not found for name: " +
addedPolicy.getPolicyName());
}
try {
policyDAO.getApplicationPolicyByUuid(policy.getUuid());
Assert.fail("Exception expected, but not thrown.");
} catch (APIMgtDAOException ex) {
Assert.assertEquals(ex.getMessage(), "Application Policy not found for id: " + addedPolicy.getUuid());
}
}
@Test(description = "Add,Get and Delete Subscription Policies")
public void testAddGetDeleteSubscriptionPolicies()
throws Exception {
SubscriptionPolicy policy = SampleTestObjectCreator.createDefaultSubscriptionPolicy();
policy.setUuid("3d253272-25b3-11e7-93ae-92361f002671");
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
//add policy
policyDAO.addSubscriptionPolicy(policy);
//get added policy
Policy addedPolicy = policyDAO.getSubscriptionPolicy(policy.getPolicyName());
Assert.assertNotNull(addedPolicy);
Assert.assertEquals(addedPolicy.getPolicyName(), policy.getPolicyName());
//delete policy
policyDAO.deletePolicy(APIMgtAdminService.PolicyLevel.subscription, policy.getPolicyName());
//get policy after deletion
try {
policyDAO.getSubscriptionPolicy(policy.getPolicyName());
Assert.fail("Exception expected, but not thrown.");
} catch (APIMgtDAOException ex) {
Assert.assertEquals(ex.getMessage(), "Subscription Policy not found for name: "
+ addedPolicy.getPolicyName());
}
//test for exception: retrieving not available policy
try {
policyDAO.getSubscriptionPolicyByUuid(policy.getUuid());
Assert.fail("Exception expected, but not thrown.");
} catch (APIMgtDAOException ex) {
Assert.assertEquals(ex.getMessage(),
"Subscription Policy not found for id: " + addedPolicy.getUuid());
}
}
@Test(description = "Get API Policies")
public void testGetAPIPolicies() throws Exception {
APIPolicy policy = SampleTestObjectCreator.createDefaultAPIPolicy();
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
//add policy
policyDAO.addApiPolicy(policy);
List<APIPolicy> policyList = policyDAO.getApiPolicies();
Assert.assertNotNull(policyList);
Assert.assertNotNull(policyDAO.getApiPolicy(policy.getPolicyName()), "Retrieving API policy by name failed "
+ "for policy with name: " + policy.getPolicyName());
Assert.assertNotNull(policyDAO.getApiPolicyByUuid(policy.getUuid()), "Retrieving API policy by id failed for "
+ "policy with id: " + policy.getUuid());
}
@Test(description = "Get Application Policies")
public void testGetApplicationPolicies() throws Exception {
ApplicationPolicy policy = SampleTestObjectCreator.createDefaultApplicationPolicy();
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
//add policy
policyDAO.addApplicationPolicy(policy);
List<ApplicationPolicy> policyList = policyDAO.getApplicationPolicies();
Assert.assertNotNull(policyList);
Assert.assertNotNull(policyDAO.getApplicationPolicy(policy.getPolicyName()), "Retrieving Application policy by "
+ "name failed for policy with name: " + policy.getPolicyName());
Assert.assertNotNull(policyDAO.getApplicationPolicyByUuid(policy.getUuid()), "Retrieving Application policy "
+ "by id failed for policy with id: " + policy.getUuid());
}
@Test(description = "Get Subscription Policies")
public void testGetSubscriptionPolicies() throws Exception {
SubscriptionPolicy policy = SampleTestObjectCreator.createDefaultSubscriptionPolicy();
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
//add policy
policyDAO.addSubscriptionPolicy(policy);
List<SubscriptionPolicy> policyList = policyDAO.getSubscriptionPolicies();
Assert.assertNotNull(policyList);
Assert.assertNotNull(policyDAO.getSubscriptionPolicy(policy.getPolicyName()), "Retrieving Subscription policy "
+ "by name failed for policy with name: " + policy.getPolicyName());
Assert.assertNotNull(policyDAO.getSubscriptionPolicyByUuid(policy.getUuid()), "Retrieving Subscription policy "
+ "by id failed for policy with id: " + policy.getUuid());
}
@Test(description = "Get API Policies with bandwidth limit")
public void testGetAPIPolicyWithBandwidthLimit()
throws Exception {
APIPolicy policy = SampleTestObjectCreator.createDefaultAPIPolicyWithBandwidthLimit();
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
//add policy
policyDAO.addApiPolicy(policy);
Policy policyAdded = policyDAO.getApiPolicy(policy.getPolicyName());
Assert.assertNotNull(policyAdded);
Assert.assertEquals(policyAdded.getPolicyName(), policy.getPolicyName());
}
@Test(description = "policy exists test")
public void testPolicyExists () throws Exception {
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
ApplicationPolicy applicationPolicy = SampleTestObjectCreator.createDefaultApplicationPolicy();
policyDAO.addApplicationPolicy(applicationPolicy);
Assert.assertTrue(policyDAO.policyExists(APIMgtAdminService.PolicyLevel.application,
applicationPolicy.getPolicyName()), "Application policy with name: " + applicationPolicy.getPolicyName()
+ " does not exist");
policyDAO.deletePolicyByUuid(APIMgtAdminService.PolicyLevel.application, applicationPolicy.getUuid());
Assert.assertFalse(policyDAO.policyExists(APIMgtAdminService.PolicyLevel.application,
applicationPolicy.getPolicyName()), "Deleted Application policy with name: "
+ applicationPolicy.getPolicyName() + " still exists");
SubscriptionPolicy subscriptionPolicy = SampleTestObjectCreator.createDefaultSubscriptionPolicy();
policyDAO.addSubscriptionPolicy(subscriptionPolicy);
Assert.assertTrue(policyDAO.policyExists(APIMgtAdminService.PolicyLevel.subscription,
subscriptionPolicy.getPolicyName()), "Subscription policy with name: "
+ subscriptionPolicy.getPolicyName() + " does not exist");
policyDAO.deletePolicyByUuid(APIMgtAdminService.PolicyLevel.subscription, subscriptionPolicy.getUuid());
Assert.assertFalse(policyDAO.policyExists(APIMgtAdminService.PolicyLevel.subscription,
subscriptionPolicy.getPolicyName()), "Deleted Subscription policy with name: "
+ subscriptionPolicy.getPolicyName() + " still exists");
APIPolicy apiPolicy = SampleTestObjectCreator.createDefaultAPIPolicy();
policyDAO.addApiPolicy(apiPolicy);
Assert.assertTrue(policyDAO.policyExists(APIMgtAdminService.PolicyLevel.api, apiPolicy.getPolicyName()), "API"
+ " policy with name: " + apiPolicy.getPolicyName() + " does not exist");
policyDAO.deletePolicyByUuid(APIMgtAdminService.PolicyLevel.api, apiPolicy.getUuid());
Assert.assertFalse(policyDAO.policyExists(APIMgtAdminService.PolicyLevel.api, apiPolicy.getPolicyName()),
"Deleted API policy with name: " + apiPolicy.getPolicyName() + " still exists");
}
@Test(description = "Add, Get, Delete block condition")
public void testAddGetUpdateDeleteBlockConditions() throws Exception {
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
BlockConditions blockConditionsIP = SampleTestObjectCreator
.createDefaultBlockCondition(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_IP);
BlockConditions blockConditionsIpRange = SampleTestObjectCreator
.createDefaultBlockCondition(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITION_IP_RANGE);
BlockConditions blockConditionsApi = SampleTestObjectCreator
.createDefaultBlockCondition(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_API);
BlockConditions blockConditionsApp = SampleTestObjectCreator
.createDefaultBlockCondition(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_APPLICATION);
BlockConditions blockConditionsUser = SampleTestObjectCreator
.createDefaultBlockCondition(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_USER);
String uuidIp = policyDAO.addBlockConditions(blockConditionsIP);
String uuidIpRange = policyDAO.addBlockConditions(blockConditionsIpRange);
String uuidApi = policyDAO.addBlockConditions(blockConditionsApi);
String uuidApp = policyDAO.addBlockConditions(blockConditionsApp);
String uuidUser = policyDAO.addBlockConditions(blockConditionsUser);
BlockConditions blockConditionsAddedIP = policyDAO.getBlockConditionByUUID(uuidIp);
BlockConditions blockConditionsAddedIpRange = policyDAO.getBlockConditionByUUID(uuidIpRange);
BlockConditions blockConditionsAddedApi = policyDAO.getBlockConditionByUUID(uuidApi);
BlockConditions blockConditionsAddedApp = policyDAO.getBlockConditionByUUID(uuidApp);
BlockConditions blockConditionsAddedUser = policyDAO.getBlockConditionByUUID(uuidUser);
Assert.assertEquals(blockConditionsIP.getConditionValue(), blockConditionsAddedIP.getConditionValue());
Assert.assertEquals(blockConditionsApi.getConditionValue(), blockConditionsAddedApi.getConditionValue());
Assert.assertEquals(blockConditionsApp.getConditionValue(), blockConditionsAddedApp.getConditionValue());
Assert.assertEquals(blockConditionsUser.getConditionValue(), blockConditionsAddedUser.getConditionValue());
Assert.assertEquals(blockConditionsIpRange.getStartingIP(), blockConditionsAddedIpRange.getStartingIP());
Assert.assertTrue(policyDAO.updateBlockConditionStateByUUID(uuidIp, true));
Assert.assertTrue(policyDAO.getBlockConditionByUUID(uuidIp).isEnabled());
Assert.assertTrue(policyDAO.getBlockConditions().size() == 5);
Assert.assertTrue(policyDAO.deleteBlockConditionByUuid(uuidIp));
Assert.assertTrue(policyDAO.deleteBlockConditionByUuid(uuidIpRange));
Assert.assertTrue(policyDAO.deleteBlockConditionByUuid(uuidApi));
Assert.assertTrue(policyDAO.deleteBlockConditionByUuid(uuidApp));
Assert.assertTrue(policyDAO.deleteBlockConditionByUuid(uuidUser));
}
@Test
public void testAddGetUpdateDeleteCustomPolicy() throws Exception {
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
CustomPolicy customPolicy = SampleTestObjectCreator.createDefaultCustomPolicy();
String uuid = policyDAO.addCustomPolicy(customPolicy);
CustomPolicy policyAdded = policyDAO.getCustomPolicyByUuid(uuid);
Assert.assertEquals(customPolicy.getSiddhiQuery(), policyAdded.getSiddhiQuery());
policyAdded.setDescription("updated custom policy");
policyDAO.updateCustomPolicy(policyAdded);
Assert.assertEquals(policyDAO.getCustomPolicyByUuid(uuid).getDescription() , "updated custom policy");
policyDAO.deleteCustomPolicy(uuid);
CustomPolicy policyDeletion = policyDAO.getCustomPolicyByUuid(uuid);
Assert.assertNull(policyDeletion);
}
@Test
public void testGetAllPolicies() throws Exception {
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
int size = policyDAO.getAllPolicies().size();
APIPolicy apiPolicy = SampleTestObjectCreator.createDefaultAPIPolicy();
ApplicationPolicy applicationPolicy = SampleTestObjectCreator.createDefaultApplicationPolicy();
SubscriptionPolicy subscriptionPolicy = SampleTestObjectCreator.createDefaultSubscriptionPolicy();
policyDAO.addApiPolicy(apiPolicy);
policyDAO.addApplicationPolicy(applicationPolicy);
policyDAO.addSubscriptionPolicy(subscriptionPolicy);
Set<PolicyValidationData> policyValidationData = policyDAO.getAllPolicies();
Assert.assertTrue(policyValidationData.size() == size + 3);
}
@Test
public void testGetCustomPolicies() throws Exception {
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
int size = policyDAO.getCustomPolicies().size();
CustomPolicy customPolicy = SampleTestObjectCreator.createDefaultCustomPolicy();
policyDAO.addCustomPolicy(customPolicy);
Assert.assertTrue(policyDAO.getCustomPolicies().size() == size + 1);
}
@Test
public void testGetPoliciesByLevel() throws Exception {
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
int policySize;
//api policy by level
policySize = policyDAO.getPoliciesByLevel(APIMgtAdminService.PolicyLevel.api).size();
APIPolicy apiPolicy = SampleTestObjectCreator.createDefaultAPIPolicy();
policyDAO.addApiPolicy(apiPolicy);
Assert.assertTrue(policyDAO.getPoliciesByLevel(APIMgtAdminService.PolicyLevel.api).size() == policySize + 1);
Assert.assertEquals(policyDAO
.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.api, apiPolicy.getPolicyName())
.getUuid(), apiPolicy.getUuid());
Assert.assertEquals(
policyDAO.getPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.api, apiPolicy.getPolicyName())
.getUuid(), apiPolicy.getUuid());
//application policy by level
policySize = policyDAO.getPoliciesByLevel(APIMgtAdminService.PolicyLevel.application).size();
ApplicationPolicy applicationPolicy = SampleTestObjectCreator.createDefaultApplicationPolicy();
policyDAO.addApplicationPolicy(applicationPolicy);
Assert.assertTrue(
policyDAO.getPoliciesByLevel(APIMgtAdminService.PolicyLevel.application).size() == policySize + 1);
Assert.assertEquals(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.application,
applicationPolicy.getPolicyName()).getUuid(), applicationPolicy.getUuid());
Assert.assertEquals(policyDAO.getPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.application,
applicationPolicy.getPolicyName()).getUuid(), applicationPolicy.getUuid());
//subscription policy by level
policySize = policyDAO.getPoliciesByLevel(APIMgtAdminService.PolicyLevel.subscription).size();
SubscriptionPolicy subscriptionPolicy = SampleTestObjectCreator.createDefaultSubscriptionPolicy();
policyDAO.addSubscriptionPolicy(subscriptionPolicy);
Assert.assertTrue(
policyDAO.getPoliciesByLevel(APIMgtAdminService.PolicyLevel.subscription).size() == policySize + 1);
Assert.assertEquals(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription,
subscriptionPolicy.getPolicyName()).getUuid(), subscriptionPolicy.getUuid());
Assert.assertEquals(policyDAO.getPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription,
subscriptionPolicy.getPolicyName()).getUuid(), subscriptionPolicy.getUuid());
//When policy is not in the DB
try {
policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.api, "test");
} catch (APIMgtResourceNotFoundException ex) {
Assert.assertEquals(ex.getMessage(),
"Policy " + APIMgtAdminService.PolicyLevel.api + "Couldn't found " + "test");
}
}
@Test
public void testGetPolicyByLevelAndUUUID() throws Exception {
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
APIPolicy apiPolicy = SampleTestObjectCreator.createDefaultAPIPolicy();
ApplicationPolicy applicationPolicy = SampleTestObjectCreator.createDefaultApplicationPolicy();
SubscriptionPolicy subscriptionPolicy = SampleTestObjectCreator.createDefaultSubscriptionPolicy();
policyDAO.addApiPolicy(apiPolicy);
policyDAO.addApplicationPolicy(applicationPolicy);
policyDAO.addSubscriptionPolicy(subscriptionPolicy);
Assert.assertEquals(policyDAO.getPolicyByLevelAndUUID(APIMgtAdminService.PolicyLevel.api, apiPolicy.getUuid())
.getPolicyName(), apiPolicy.getPolicyName());
Assert.assertEquals(policyDAO
.getPolicyByLevelAndUUID(APIMgtAdminService.PolicyLevel.application, applicationPolicy.getUuid())
.getPolicyName(), applicationPolicy.getPolicyName());
Assert.assertEquals(policyDAO
.getPolicyByLevelAndUUID(APIMgtAdminService.PolicyLevel.subscription, subscriptionPolicy.getUuid())
.getPolicyName(), subscriptionPolicy.getPolicyName());
}
@Test
public void testValidityOfBlockCondition() throws Exception {
PolicyDAO policyDAO = DAOFactory.getPolicyDAO();
BlockConditions blockConditionIPRange = SampleTestObjectCreator
.createDefaultBlockCondition(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITION_IP_RANGE);
BlockConditions blockConditionAPI = SampleTestObjectCreator
.createDefaultBlockCondition(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_API);
BlockConditions blockConditionsApp = SampleTestObjectCreator
.createDefaultBlockCondition(APIMgtConstants.ThrottlePolicyConstants.BLOCKING_CONDITIONS_APPLICATION);
//Making starting IP > ending IP
blockConditionIPRange.setStartingIP("12.34.13.12");
blockConditionIPRange.setEndingIP("10.32.44.32");
//Giving invalid API context
blockConditionAPI.setConditionValue("invalid");
//giving invalid app name and invalid UUID
String appArray[] = blockConditionsApp.getConditionValue().split(":");
UUID appUuid = UUID.randomUUID();
String appName = appArray[1];
blockConditionsApp.setConditionValue(appUuid + ":" + appName);
try {
policyDAO.addBlockConditions(blockConditionIPRange);
} catch (APIMgtDAOException ex) {
Assert.assertEquals(ex.getMessage(),
"Couldn't Save Block Condition Due to Invalid IP Range -> Starting IP : " + blockConditionIPRange
.getStartingIP() + " EndingIP : " + blockConditionIPRange.getEndingIP());
}
try {
policyDAO.addBlockConditions(blockConditionAPI);
} catch (APIMgtDAOException ex) {
Assert.assertEquals(ex.getMessage(),
"Couldn't Save Block Condition Due to Invalid API Context : " + blockConditionAPI
.getConditionValue());
}
try {
policyDAO.addBlockConditions(blockConditionsApp);
} catch (APIMgtDAOException ex) {
Assert.assertEquals(ex.getMessage(),
"Couldn't Save Block Condition Due to Invalid Application : " + appName + ", UUID :"
+ appUuid);
}
//Making IP block condition valid and add twice to check if it shows already existing
blockConditionIPRange.setEndingIP("29.23.12.12");
policyDAO.addBlockConditions(blockConditionIPRange);
try {
policyDAO.addBlockConditions(blockConditionIPRange);
} catch (BlockConditionAlreadyExistsException ex) {
Assert.assertEquals(ex.getMessage(),
"Condition with type: " + blockConditionIPRange.getConditionType() + ", value: "
+ blockConditionIPRange.getConditionValue() + " already exists");
}
}
}
| apache-2.0 |
dump247/aws-sdk-java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/AllocateHostsResult.java | 5385 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.ec2.model;
import java.io.Serializable;
/**
*
*/
public class AllocateHostsResult implements Serializable, Cloneable {
/**
* <p>
* The ID of the allocated Dedicated host. This is used when you want to
* launch an instance onto a specific host.
* </p>
*/
private com.amazonaws.internal.SdkInternalList<String> hostIds;
/**
* <p>
* The ID of the allocated Dedicated host. This is used when you want to
* launch an instance onto a specific host.
* </p>
*
* @return The ID of the allocated Dedicated host. This is used when you
* want to launch an instance onto a specific host.
*/
public java.util.List<String> getHostIds() {
if (hostIds == null) {
hostIds = new com.amazonaws.internal.SdkInternalList<String>();
}
return hostIds;
}
/**
* <p>
* The ID of the allocated Dedicated host. This is used when you want to
* launch an instance onto a specific host.
* </p>
*
* @param hostIds
* The ID of the allocated Dedicated host. This is used when you want
* to launch an instance onto a specific host.
*/
public void setHostIds(java.util.Collection<String> hostIds) {
if (hostIds == null) {
this.hostIds = null;
return;
}
this.hostIds = new com.amazonaws.internal.SdkInternalList<String>(
hostIds);
}
/**
* <p>
* The ID of the allocated Dedicated host. This is used when you want to
* launch an instance onto a specific host.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if
* any). Use {@link #setHostIds(java.util.Collection)} or
* {@link #withHostIds(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param hostIds
* The ID of the allocated Dedicated host. This is used when you want
* to launch an instance onto a specific host.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public AllocateHostsResult withHostIds(String... hostIds) {
if (this.hostIds == null) {
setHostIds(new com.amazonaws.internal.SdkInternalList<String>(
hostIds.length));
}
for (String ele : hostIds) {
this.hostIds.add(ele);
}
return this;
}
/**
* <p>
* The ID of the allocated Dedicated host. This is used when you want to
* launch an instance onto a specific host.
* </p>
*
* @param hostIds
* The ID of the allocated Dedicated host. This is used when you want
* to launch an instance onto a specific host.
* @return Returns a reference to this object so that method calls can be
* chained together.
*/
public AllocateHostsResult withHostIds(java.util.Collection<String> hostIds) {
setHostIds(hostIds);
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getHostIds() != null)
sb.append("HostIds: " + getHostIds());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof AllocateHostsResult == false)
return false;
AllocateHostsResult other = (AllocateHostsResult) obj;
if (other.getHostIds() == null ^ this.getHostIds() == null)
return false;
if (other.getHostIds() != null
&& other.getHostIds().equals(this.getHostIds()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode
+ ((getHostIds() == null) ? 0 : getHostIds().hashCode());
return hashCode;
}
@Override
public AllocateHostsResult clone() {
try {
return (AllocateHostsResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(
"Got a CloneNotSupportedException from Object.clone() "
+ "even though we're Cloneable!", e);
}
}
} | apache-2.0 |
avideoChat/zgrujb | pulzzedproject/src/com/zgrjb/application/BaseApp.java | 1456 | package com.zgrjb.application;
import org.litepal.LitePalApplication;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.android.volley.toolbox.ImageLoader.ImageCache;
import com.zgrjb.utils.MsgDBUtils;
import android.app.Application;
import android.graphics.Bitmap;
public class BaseApp extends LitePalApplication{
// public static ServiceManager serviceManager;
private RequestQueue requestQueue;
public static ImageLoader imageLoader;
public static boolean isQuickIn = false;
public static BaseApp mInstance;
//应该在这里得到自己的信息,全局共享
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mInstance = this;
// serviceManager = new ServiceManager(this);
// serviceManager.setNotificationIcon(R.drawable.notification);
// serviceManager.startService();
initNetworkImageLoader();
}
public static BaseApp getInstance() {
return mInstance;
}
private void initNetworkImageLoader() {
requestQueue = Volley.newRequestQueue(this);
imageLoader = new ImageLoader(requestQueue, new ImageCache() {
@Override
public void putBitmap(String arg0, Bitmap arg1) {
// TODO Auto-generated method stub
}
@Override
public Bitmap getBitmap(String arg0) {
// TODO Auto-generated method stub
return null;
}
});
}
}
| apache-2.0 |
coastland/gsp-dba-maven-plugin | src/test/resources/jp/co/tis/gsp/tools/dba/mojo/GenerateEntity_test/view/mysql/expected/output/jp/co/tis/gsptest/entity/entity/View3.java | 1186 | package jp.co.tis.gsptest.entity.entity;
import java.io.Serializable;
import javax.annotation.Generated;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
*
*
*/
@Generated("GSP")
@Entity
@Table(name = "view3")
public class View3 implements Serializable {
private static final long serialVersionUID = 1L;
/** */
private Long oid;
/** */
private String customerName;
/**
* を返します。
*
* @return
*/
@Column(name = "OID", precision = 19, nullable = false, unique = false)
public Long getOid() {
return oid;
}
/**
* を設定します。
*
* @param oid
*/
public void setOid(Long oid) {
this.oid = oid;
}
/**
* を返します。
*
* @return
*/
@Column(name = "CUSTOMER_NAME", length = 30, nullable = true, unique = false)
public String getCustomerName() {
return customerName;
}
/**
* を設定します。
*
* @param customerName
*/
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
}
| apache-2.0 |
eic-cefet-rj/sagitarii | src/main/java/br/cefetrj/sagitarii/core/statistics/Accumulator.java | 3599 | package br.cefetrj.sagitarii.core.statistics;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import br.cefetrj.sagitarii.core.delivery.DeliveryUnit;
import br.cefetrj.sagitarii.misc.DateLibrary;
import br.cefetrj.sagitarii.persistence.entity.Instance;
import br.cefetrj.sagitarii.persistence.entity.TimeControl;
public class Accumulator {
private Long averageMillis = 0L;
private int calculatedCount = 0;
private String hash;
private Long totalAgeMillis = 0L;
private Long maxAgeMillis = 0L;
private Long minAgeMillis = 0L;
private int idTimeControl = -1;
private String content;
private Logger logger = LogManager.getLogger( this.getClass().getName() );
public int getIdTimeControl() {
return idTimeControl;
}
public void setIdTimeControl(int idTimeControl) {
this.idTimeControl = idTimeControl;
}
public Accumulator( DeliveryUnit du ) {
this.hash = du.getHash();
this.content = du.getInstanceActivities();
addToStack( du );
logger.debug("[AC] new Accumulator for " + content + ": " + averageMillis + " | " + totalAgeMillis + " | " + calculatedCount );
}
public Accumulator( TimeControl tc ) {
this.averageMillis = tc.getAverageMilis();
this.calculatedCount = tc.getCalculatedCount();
this.hash = tc.getHash();
this.idTimeControl = tc.getIdTimeControl();
this.totalAgeMillis = tc.getTotalAgeMilis();
this.minAgeMillis = tc.getMinAgeMilis();
this.maxAgeMillis = tc.getMaxAgeMilis();
this.content = tc.getContent();
logger.debug("[DB] new Accumulator for " + content + ": " + averageMillis + " | " + totalAgeMillis + " | " + calculatedCount );
}
public String getContent() {
return content;
}
public long getAverageMillis() {
return averageMillis;
}
public void addToStack( DeliveryUnit du ) {
Instance instance = du.getInstance();
Long duAgeMillis = instance.getElapsedMillis();
// Long duAgeMillis = du.getAgeMillis();
if ( duAgeMillis == 0 ) {
logger.error("Instance zero age detected: Deliver time " + du.getDeliverTime().getTime() + " | End time " + du.getEndTime().getTime() );
}
if ( duAgeMillis > maxAgeMillis ) {
maxAgeMillis = duAgeMillis;
}
if ( ( minAgeMillis == 0 ) || ( duAgeMillis < minAgeMillis ) ) {
minAgeMillis = duAgeMillis;
}
logger.debug("updating average count for " + content + ": " + averageMillis + " | " + totalAgeMillis + " | " + calculatedCount + " | " + duAgeMillis );
calculatedCount++;
Long newTotalAgeMillis = totalAgeMillis + duAgeMillis;
logger.debug(newTotalAgeMillis + " = " + totalAgeMillis + " + " +duAgeMillis);
averageMillis = newTotalAgeMillis / calculatedCount;
logger.debug("new average count for " + content + ": " + averageMillis + " = " + newTotalAgeMillis + " / " + calculatedCount );
totalAgeMillis = newTotalAgeMillis;
}
public int getCalculatedCount() {
return calculatedCount;
}
public String getAverageAgeAsText() {
return DateLibrary.getInstance().getTimeRepresentation(averageMillis);
}
public String getMinAgeAsText() {
return DateLibrary.getInstance().getTimeRepresentation(minAgeMillis);
}
public String getMaxAgeAsText() {
return DateLibrary.getInstance().getTimeRepresentation(maxAgeMillis);
}
public String getHash() {
return this.hash;
}
public long getTotalAgeMillis() {
return totalAgeMillis;
}
public Long getMinAgeMillis() {
return minAgeMillis;
}
public Long getMaxAgeMillis() {
return maxAgeMillis;
}
}
| apache-2.0 |
currying/molecule | molecule/src/main/java/com/toparchy/molecule/bi/shipBuilding/data/HxjdjhRepository.java | 1893 | package com.toparchy.molecule.bi.shipBuilding.data;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.ApplicationScoped;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import com.toparchy.molecule.bi.shipBuilding.model.Hxjdjh;
import com.toparchy.molecule.bi.shipBuilding.model.HxjdjhDataHandle;
@ApplicationScoped
public class HxjdjhRepository {
@PersistenceUnit(unitName = "bi")
private EntityManagerFactory emf;
private String sql;
private Query query;
private List<Hxjdjh> objecArraytList;
private List<HxjdjhDataHandle> hxjdjhDataHandles;
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
public List<HxjdjhDataHandle> findByGcbh(String gcbh, int start, int max) {
EntityManager em = emf.createEntityManager();
sql = "select ppk_varcode,cxmc,gcbh,gcmc,xmmc,xmbh,xmsx,jhkg1,jhwg1 from JH_D_Hxjdjh_DJ where gcbh =?1 order by xmsx";
query = em.createNativeQuery(sql, Hxjdjh.class);
query.setParameter(1, gcbh);
query.setFirstResult(start);
query.setMaxResults(max);
objecArraytList = query.getResultList();
int i = 1;
hxjdjhDataHandles = new ArrayList<HxjdjhDataHandle>();
for (Hxjdjh hxjdjh : objecArraytList) {
HxjdjhDataHandle hxjdjhDataHandle = new HxjdjhDataHandle();
hxjdjhDataHandle.setId(i);
hxjdjhDataHandle.setStart_date(formatter.format(hxjdjh.getJhkg()));
hxjdjhDataHandle.setEnd_date(formatter.format(hxjdjh.getJhwg()));
hxjdjhDataHandle.setText("项目名称:" + hxjdjh.getXmmc() + "\n计划开工:"
+ hxjdjh.getJhkg() + "\n计划完工:" + hxjdjh.getJhwg());
hxjdjhDataHandles.add(hxjdjhDataHandle);
i++;
}
em.close();
return hxjdjhDataHandles;
}
}
| apache-2.0 |
monkeyk/oauth2-shiro | core/src/main/java/com/monkeyk/os/infrastructure/jdbc/AccessTokenRowMapper.java | 1114 | package com.monkeyk.os.infrastructure.jdbc;
import com.monkeyk.os.domain.oauth.AccessToken;
import org.springframework.jdbc.core.RowMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 15-6-20
*
* @author Shengzhao Li
*/
public class AccessTokenRowMapper implements RowMapper<AccessToken> {
public AccessTokenRowMapper() {
}
@Override
public AccessToken mapRow(ResultSet rs, int rowNum) throws SQLException {
final AccessToken oauthCode = new AccessToken()
.tokenId(rs.getString("token_id"))
.tokenExpiredSeconds(rs.getInt("token_expired_seconds"))
.authenticationId(rs.getString("authentication_id"))
.username(rs.getString("username"))
.clientId(rs.getString("client_id"))
.tokenType(rs.getString("token_type"))
.refreshTokenExpiredSeconds(rs.getInt("refresh_token_expired_seconds"))
.refreshToken(rs.getString("refresh_token"));
oauthCode.createTime(rs.getTimestamp("create_time"));
return oauthCode;
}
}
| apache-2.0 |
ConsecroMUD/ConsecroMUD | com/suscipio_solutions/consecro_mud/Abilities/Thief/Thief_Shadow.java | 8708 | package com.suscipio_solutions.consecro_mud.Abilities.Thief;
import java.util.HashSet;
import java.util.Vector;
import com.suscipio_solutions.consecro_mud.Abilities.interfaces.Ability;
import com.suscipio_solutions.consecro_mud.Commands.interfaces.Command;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CharStats;
import com.suscipio_solutions.consecro_mud.Common.interfaces.PhyStats;
import com.suscipio_solutions.consecro_mud.Exits.interfaces.Exit;
import com.suscipio_solutions.consecro_mud.Locales.interfaces.Room;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.CMParms;
import com.suscipio_solutions.consecro_mud.core.Directions;
import com.suscipio_solutions.consecro_mud.core.interfaces.Environmental;
import com.suscipio_solutions.consecro_mud.core.interfaces.Physical;
import com.suscipio_solutions.consecro_mud.core.interfaces.Tickable;
@SuppressWarnings("rawtypes")
public class Thief_Shadow extends ThiefSkill
{
@Override public String ID() { return "Thief_Shadow"; }
private final static String localizedName = CMLib.lang().L("Shadow");
@Override public String name() { return localizedName; }
// can NOT have a display text since the ability instance
// is shared between the invoker and the target
@Override public String displayText(){return "";}
@Override protected int canAffectCode(){return CAN_MOBS;}
@Override protected int canTargetCode(){return CAN_MOBS;}
@Override public int abstractQuality(){return Ability.QUALITY_OK_OTHERS;}
@Override public int classificationCode(){return Ability.ACODE_THIEF_SKILL|Ability.DOMAIN_STEALTHY;}
private static final String[] triggerStrings =I(new String[] {"SHADOW"});
@Override public String[] triggerStrings(){return triggerStrings;}
public MOB shadowing=null;
protected Room lastRoom=null;
private long lastTogether=0;
@Override public int usageType(){return USAGE_MOVEMENT|USAGE_MANA;}
public int code=0;
@Override public int abilityCode(){return code;}
@Override public void setAbilityCode(int newCode){code=newCode;}
public boolean stillAShadower()
{
if(invoker==null) return false;
final MOB mob=invoker;
if(mob.amDead()) return false;
if(mob.isInCombat()) return false;
if(mob.location()==null) return false;
if(!CMLib.flags().aliveAwakeMobile(mob,true)) return false;
return true;
}
public boolean stillAShadowee()
{
if(shadowing==null) return false;
if(shadowing.amDead()) return false;
if(shadowing.isInCombat()&&(shadowing.getVictim()==invoker)) return false;
if(shadowing.location()==null) return false;
if(!CMLib.flags().aliveAwakeMobile(shadowing,true)) return false;
return true;
}
public boolean canShadow()
{
if(!stillAShadower()) return false;
if(!stillAShadowee()) return false;
final MOB mob=invoker;
if(CMLib.flags().canBeSeenBy(mob,shadowing)) return false;
if(!CMLib.flags().canBeSeenBy(shadowing,mob)) return false;
if(mob.location()!=shadowing.location()) return false;
if(mob.getGroupMembers(new HashSet<MOB>()).size()>1) return false;
return true;
}
@Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
super.executeMsg(myHost,msg);
if(((msg.targetMinor()==CMMsg.TYP_LEAVE)
||(msg.targetMinor()==CMMsg.TYP_FLEE))
&&(stillAShadower())
&&(stillAShadowee())
&&(msg.amISource(shadowing))
&&(msg.amITarget(shadowing.location()))
&&(!CMLib.flags().isSneaking(shadowing))
&&(msg.tool()!=null)
&&(msg.tool() instanceof Exit)
&&((shadowing.riding()==null)||(msg.source().riding()!=shadowing.riding())))
{
int dir=-1;
for(int d=Directions.NUM_DIRECTIONS()-1;d>=0;d--)
if(shadowing.location().getReverseExit(d)==msg.tool())
dir=d;
if((dir>=0)&&(msg.source().location()!=lastRoom))
{
final String directionWent=Directions.getDirectionName(dir);
final MOB mob=invoker;
lastRoom=msg.source().location();
if(!mob.isMonster())
mob.enqueCommand(CMParms.parse(directionWent),Command.METAFLAG_FORCED,0);
else
CMLib.tracking().walk(mob,dir,false,false);
}
}
if((shadowing!=null)&&(invoker!=null)&&(shadowing.location()==invoker.location()))
lastTogether=System.currentTimeMillis();
}
@Override
public boolean tick(Tickable ticking, int tickID)
{
if(!super.tick(ticking,tickID)) return false;
if(lastTogether==0) return true;
if((shadowing!=null)&&(invoker!=null)&&(shadowing.location()==invoker.location()))
lastTogether=System.currentTimeMillis();
final long secondsago=System.currentTimeMillis()-10000;
if(lastTogether<secondsago)
{
if((invoker!=null)&&(shadowing!=null))
{
invoker.tell(L("You lost @x1.",shadowing.charStats().himher()));
unInvoke();
return false;
}
}
return true;
}
@Override
public void affectCharStats(MOB affected, CharStats affectableStats)
{
super.affectCharStats(affected,affectableStats);
if((shadowing!=null)&&(shadowing.location()==affected.location()))
affectableStats.setStat(CharStats.STAT_SAVE_DETECTION,
25
+proficiency()
+affectableStats.getStat(CharStats.STAT_SAVE_DETECTION));
else
affectableStats.setStat(CharStats.STAT_SAVE_DETECTION,
+proficiency()
+affectableStats.getStat(CharStats.STAT_SAVE_DETECTION));
}
@Override
public void affectPhyStats(Physical affected, PhyStats affectableStats)
{
super.affectPhyStats(affected,affectableStats);
if(affected==invoker)
{
affectableStats.setDisposition(affectableStats.disposition()|PhyStats.IS_HIDDEN);
affectableStats.setDisposition(affectableStats.disposition()|PhyStats.IS_SNEAKING);
}
if((shadowing!=null)&&(invoker!=null)&&(shadowing.location()==invoker.location()))
lastTogether=System.currentTimeMillis();
}
@Override
public void unInvoke()
{
if(canBeUninvoked())
{
if((invoker!=null)&&(shadowing!=null))
{
invoker.delEffect(this);
setAffectedOne(shadowing);
invoker.tell(L("You are no longer shadowing @x1.",shadowing.name()));
}
shadowing=null;
}
super.unInvoke();
}
@Override
public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
{
Thief_Shadow A=(Thief_Shadow)mob.fetchEffect(ID());
if(A!=null)
{
if(A.shadowing==null)
mob.delEffect(A);
else
{
final Ability AA=A.shadowing.fetchEffect(ID());
if((AA!=null)&&(AA.invoker()==mob))
{
AA.unInvoke();
return true;
}
mob.delEffect(A);
}
}
if(commands.size()<1)
{
mob.tell(L("Shadow whom?"));
return false;
}
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null) return false;
if(target==mob)
{
mob.tell(L("You cannot shadow yourself?!"));
return false;
}
if(mob.getGroupMembers(new HashSet<MOB>()).size()>1)
{
mob.tell(L("You cannot shadow someone while part of a group."));
return false;
}
if(mob.isInCombat())
{
mob.tell(L("Not while you are fighting!"));
return false;
}
if(CMLib.flags().canBeSeenBy(mob,target))
{
mob.tell(L("@x1 is watching you too closely.",target.name(mob)));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
shadowing=null;
final int levelDiff=target.phyStats().level()-(mob.phyStats().level()+abilityCode()+(super.getXLEVELLevel(mob)*2));
final boolean success=proficiencyCheck(mob,-(levelDiff*10),auto);
if(!success)
{
final CMMsg msg=CMClass.getMsg(mob,target,null,CMMsg.MSG_OK_VISUAL,auto?"":L("Your attempt to shadow <T-NAMESELF> fails; <T-NAME> spots you!"),CMMsg.MSG_OK_VISUAL,auto?"":L("You spot <S-NAME> trying to shadow you."),CMMsg.NO_EFFECT,null);
if(mob.location().okMessage(mob,msg))
mob.location().send(mob,msg);
}
else
{
final CMMsg msg=CMClass.getMsg(mob,target,this,auto?CMMsg.MSG_OK_VISUAL:CMMsg.MSG_THIEF_ACT,L("You are now shadowing <T-NAME>. Enter 'shadow' again to disengage."),CMMsg.NO_EFFECT,null,CMMsg.NO_EFFECT,null);
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
shadowing=target;
if(beneficialAffect(mob,target,asLevel,Ability.TICKS_FOREVER)!=null)
{
A=(Thief_Shadow)target.fetchEffect(ID());
if(A!=null)
{
mob.addEffect(A);
A.shadowing=target;
A.setAffectedOne(target);
A.lastTogether=System.currentTimeMillis();
mob.recoverPhyStats();
}
else
{
A=(Thief_Shadow)mob.fetchEffect(ID());
if(A!=null)
A.unInvoke();
}
}
}
}
return success;
}
}
| apache-2.0 |
yokichan/coolweather | app/src/main/java/com/coolweather/android/gson/Suggestion.java | 577 | package com.coolweather.android.gson;
import com.google.gson.annotations.SerializedName;
/**
* Created by yokichan on 04/07/2017.
*/
public class Suggestion {
@SerializedName("comf")
public Comfort comfort;
@SerializedName("cw")
public CarWash carWash;
public Sport sport;
public class Comfort{
@SerializedName("txt")
public String info;
}
public class CarWash{
@SerializedName("txt")
public String info;
}
public class Sport{
@SerializedName("txt")
public String info;
}
}
| apache-2.0 |
lessthanoptimal/BoofCV | main/boofcv-geo/src/main/java/boofcv/factory/geo/ConfigBundleAdjustment.java | 1391 | /*
* 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.factory.geo;
import org.ddogleg.optimization.lm.ConfigLevenbergMarquardt;
/**
* Configuration for {@link boofcv.abst.geo.bundle.BundleAdjustment}
*
* @author Peter Abeles
*/
public class ConfigBundleAdjustment {
/**
* Used to specify which optimization routine to use and how to configure it.
*
* @see ConfigLevenbergMarquardt
* @see org.ddogleg.optimization.trustregion.ConfigTrustRegion
*/
public Object configOptimizer = new ConfigLevenbergMarquardt();
public ConfigBundleAdjustment setTo( ConfigBundleAdjustment src ) {
// it should copy / overwrite but that isn't possible/easy. So this is the compromise
this.configOptimizer = src.configOptimizer;
return this;
}
}
| apache-2.0 |
JoeBeeton/BigMethodScanner | src/test/java/uk/org/freedonia/bigmethods/ProjectScannerTest.java | 1321 |
package uk.org.freedonia.bigmethods;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import uk.org.freedonia.bigmethods.results.ScanResultsAsList;
import uk.org.freedonia.bigmethods.scanner.ProjectScanner;
public class ProjectScannerTest {
@Test
public void testScanner() throws IOException, InterruptedException, ExecutionException, URISyntaxException {
Path path = getPathToResources();
ProjectScanner scanner = new ProjectScanner();
ScanResultsAsList list = new ScanResultsAsList();
scanner.scanPath( path, list, 8000 );
assertEquals( 3, list.getLargeMethodLists().size() );
assertTrue( list.getLargeMethodLists().contains(
"org.apache.commons.compress.compressors.snappy.PureJavaCrc32C.<clinit>() size : 16243") );
assertTrue( list.getLargeMethodLists().contains(
"uk.org.freedonia.bigmethods.testdata.TestData.largeMethod() size : 46333") );
}
private Path getPathToResources() throws URISyntaxException {
return Paths.get( ProjectScannerTest.class.getResource("/dataset.jar").toURI() ).getParent();
}
}
| apache-2.0 |
consulo/consulo-android | tools-base/perflib/src/main/java/com/android/tools/perflib/vmtrace/VmTraceData.java | 11234 | /*
* 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.android.tools.perflib.vmtrace;
import com.android.utils.SparseArray;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* The {@link VmTraceData} class stores all the information from a Dalvik method trace file.
* Specifically, it provides:
* <ul>
* <li>A mapping from thread ids to thread names.</li>
* <li>A mapping from method ids to {@link MethodInfo}</li>
* <li>A mapping from each thread to the top level call on that thread.</li>
* </ul>
*/
public class VmTraceData {
public enum VmClockType { THREAD_CPU, WALL, DUAL }
private final int mVersion;
private final boolean mDataFileOverflow;
private final VmClockType mVmClockType;
private final String mVm;
private final Map<String, String> mTraceProperties;
/** Map from method id to method info. */
private final Map<Long,MethodInfo> mMethods;
/** Map from thread name to thread info. */
private final Map<String, ThreadInfo> mThreadInfo;
private VmTraceData(Builder b) {
mVersion = b.mVersion;
mDataFileOverflow = b.mDataFileOverflow;
mVmClockType = b.mVmClockType;
mVm = b.mVm;
mTraceProperties = b.mProperties;
mMethods = b.mMethods;
mThreadInfo = Maps.newHashMapWithExpectedSize(b.mThreads.size());
for (int i = 0; i < b.mThreads.size(); i++) {
int id = b.mThreads.keyAt(i);
String name = b.mThreads.valueAt(i);
ThreadInfo info = mThreadInfo.get(name);
if (info != null) {
// there is alread a thread with the same name
name = String.format("%1$s-%2$d", name, id);
}
info = new ThreadInfo(id, name, b.mTopLevelCalls.get(id));
mThreadInfo.put(name, info);
}
}
public int getVersion() {
return mVersion;
}
public boolean isDataFileOverflow() {
return mDataFileOverflow;
}
public VmClockType getVmClockType() {
return mVmClockType;
}
public String getVm() {
return mVm;
}
public Map<String, String> getTraceProperties() {
return mTraceProperties;
}
public static TimeUnit getDefaultTimeUnits() {
// The traces from the VM currently use microseconds.
// TODO: figure out if this can be obtained/inferred from the trace itself
return TimeUnit.MICROSECONDS;
}
public Collection<ThreadInfo> getThreads() {
return mThreadInfo.values();
}
public List<ThreadInfo> getThreads(boolean excludeThreadsWithNoActivity) {
Collection<ThreadInfo> allThreads = getThreads();
if (!excludeThreadsWithNoActivity) {
return ImmutableList.copyOf(allThreads);
}
return Lists.newArrayList(Iterables.filter(allThreads, new Predicate<ThreadInfo>() {
@Override
public boolean apply(
com.android.tools.perflib.vmtrace.ThreadInfo input) {
return input.getTopLevelCall() != null;
}
}));
}
public ThreadInfo getThread(String name) {
return mThreadInfo.get(name);
}
public Map<Long,MethodInfo> getMethods() {
return mMethods;
}
public MethodInfo getMethod(long methodId) {
return mMethods.get(methodId);
}
/** Returns the duration of this call as a percentage of the duration of the top level call. */
public double getDurationPercentage(Call call, ThreadInfo thread, ClockType clockType,
boolean inclusiveTime) {
MethodInfo methodInfo = getMethod(call.getMethodId());
TimeSelector selector = TimeSelector.create(clockType, inclusiveTime);
long methodTime = selector.get(methodInfo, thread, TimeUnit.NANOSECONDS);
return getDurationPercentage(methodTime, thread, clockType);
}
/**
* Returns the given duration as a percentage of the duration of the top level call
* in given thread.
*/
public double getDurationPercentage(long methodTime, ThreadInfo thread, ClockType clockType) {
Call topCall = getThread(thread.getName()).getTopLevelCall();
if (topCall == null) {
return 100.;
}
MethodInfo topInfo = getMethod(topCall.getMethodId());
// always use inclusive time to obtain the top level's time when computing percentages
TimeSelector selector = TimeSelector.create(clockType, true);
long topLevelTime = selector.get(topInfo, thread, TimeUnit.NANOSECONDS);
return (double) methodTime/topLevelTime * 100;
}
public SearchResult searchFor(String pattern, ThreadInfo thread) {
pattern = pattern.toLowerCase(Locale.US);
Set<MethodInfo> methods = new HashSet<MethodInfo>();
Set<Call> calls = new HashSet<Call>();
Call topLevelCall = getThread(thread.getName()).getTopLevelCall();
if (topLevelCall == null) {
// no matches
return new SearchResult(methods, calls);
}
// Find all methods matching given pattern called on given thread
for (MethodInfo method: getMethods().values()) {
String fullName = method.getFullName().toLowerCase(Locale.US);
if (fullName.contains(pattern)) { // method name matches
long inclusiveTime = method.getProfileData()
.getInclusiveTime(thread, ClockType.GLOBAL, TimeUnit.NANOSECONDS);
if (inclusiveTime > 0) {
// method was called in this thread
methods.add(method);
}
}
}
// Find all invocations of the matched methods
Iterator<Call> iterator = topLevelCall.getCallHierarchyIterator();
while (iterator.hasNext()) {
Call c = iterator.next();
MethodInfo method = getMethod(c.getMethodId());
if (methods.contains(method)) {
calls.add(c);
}
}
return new SearchResult(methods, calls);
}
public static class Builder {
private static final boolean DEBUG = false;
private int mVersion;
private boolean mDataFileOverflow;
private VmClockType mVmClockType = VmClockType.THREAD_CPU;
private String mVm = "";
private final Map<String, String> mProperties = new HashMap<String, String>(10);
/** Map from thread ids to thread names. */
private final SparseArray<String> mThreads = new SparseArray<String>(10);
/** Map from method id to method info. */
private final Map<Long,MethodInfo> mMethods = new HashMap<Long, MethodInfo>(100);
/** Map from thread id to per thread stack call reconstructor. */
private final SparseArray<CallStackReconstructor> mStackReconstructors
= new SparseArray<CallStackReconstructor>(10);
/** Map from thread id to the top level call for that thread. */
private final SparseArray<Call> mTopLevelCalls = new SparseArray<Call>(10);
public void setVersion(int version) {
mVersion = version;
}
public int getVersion() {
return mVersion;
}
public void setDataFileOverflow(boolean dataFileOverflow) {
mDataFileOverflow = dataFileOverflow;
}
public void setVmClockType(VmClockType vmClockType) {
mVmClockType = vmClockType;
}
public VmClockType getVmClockType() {
return mVmClockType;
}
public void setProperty(String key, String value) {
mProperties.put(key, value);
}
public void setVm(String vm) {
mVm = vm;
}
public void addThread(int id, String name) {
mThreads.put(id, name);
}
public void addMethod(long id, MethodInfo info) {
mMethods.put(id, info);
}
public void addMethodAction(int threadId, long methodId, TraceAction methodAction,
int threadTime, int globalTime) {
// create thread info if it doesn't exist
if (mThreads.get(threadId) == null) {
mThreads.put(threadId, String.format("Thread id: %1$d", threadId));
}
// create method info if it doesn't exist
if (mMethods.get(methodId) == null) {
MethodInfo info = new MethodInfo(methodId, "unknown", "unknown", "unknown",
"unknown", -1);
mMethods.put(methodId, info);
}
if (DEBUG) {
MethodInfo methodInfo = mMethods.get(methodId);
System.out.printf("Thread %1$30s: (%2$8x) %3$-40s %4$20s\n",
mThreads.get(threadId), methodId, methodInfo.getShortName(), methodAction);
}
CallStackReconstructor reconstructor = mStackReconstructors.get(threadId);
if (reconstructor == null) {
long topLevelCallId = createUniqueMethodIdForThread(threadId);
reconstructor = new CallStackReconstructor(topLevelCallId);
mStackReconstructors.put(threadId, reconstructor);
}
reconstructor.addTraceAction(methodId, methodAction, threadTime, globalTime);
}
private long createUniqueMethodIdForThread(int threadId) {
long id = Long.MAX_VALUE - mThreads.indexOfKey(threadId);
assert mMethods.get(id) == null :
"Unexpected error while attempting to create a unique key - key already exists";
MethodInfo info = new MethodInfo(id, mThreads.get(threadId), "", "", "", 0);
mMethods.put(id, info);
return id;
}
public VmTraceData build() {
for (int i = 0; i < mStackReconstructors.size(); i++) {
int threadId = mStackReconstructors.keyAt(i);
CallStackReconstructor reconstructor = mStackReconstructors.valueAt(i);
mTopLevelCalls.put(threadId, reconstructor.getTopLevel());
}
return new VmTraceData(this);
}
}
}
| apache-2.0 |
Doi9t/binclassreader | src/main/java/ca/watier/binclassreader/structs/ConstAccessFlagsInfo.java | 1453 | /*
* Copyright 2014 - 2017 Yannick Watier
*
* 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 ca.watier.binclassreader.structs;
import ca.watier.binclassreader.annotations.BinClassParser;
import ca.watier.binclassreader.enums.ClassAccessFlagsEnum;
import ca.watier.binclassreader.utils.BaseUtils;
/**
* Created by Yannick on 1/29/2016.
*/
//https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.1-200-E.1
public class ConstAccessFlagsInfo {
@BinClassParser(byteToRead = 2)
private byte[] flags;
private int getFlagIndex() {
return BaseUtils.combineBytesToInt(flags);
}
public ClassAccessFlagsEnum getAccessFlag() {
return ClassAccessFlagsEnum.getFlagById((byte) getFlagIndex());
}
@Override
public String toString() {
return "ConstAccessFlagsInfo{" +
"flag=" + getAccessFlag() +
'}';
}
}
| apache-2.0 |
xjdr/xio2 | src/main/java/com/xjeffrose/xio2/http/HttpRequestParser.java | 9106 | /*
* Copyright (C) 2015 Jeff Rose
*
* 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.xjeffrose.xio2.http;
import com.xjeffrose.log.Log;
import java.nio.ByteBuffer;
import java.util.logging.Logger;
@SuppressWarnings (value = "fallthrough")
public class HttpRequestParser {
private static final Logger log = Log.getLogger(HttpRequestParser.class.getName());
private int lastByteRead;
private HttpRequest req;
private state state_ = state.method_start;
public boolean done = false;
public HttpRequestParser() {
lastByteRead = -1;
}
private enum state {
method_start,
method,
uri,
http_version_h,
http_version_t_1,
http_version_t_2,
http_version_p,
http_version_slash,
http_version_major_start,
http_version_major,
http_version_minor_start,
http_version_minor,
expecting_newline_1,
header_line_start,
header_lws,
header_name,
space_before_header_value,
header_value,
expecting_newline_2,
expecting_newline_3
}
public boolean parse(HttpRequest req) {
this.req = req;
final ByteBuffer temp = req.inputBuffer.duplicate();
ParseState result = ParseState.good;
temp.flip();
temp.position(lastByteRead + 1);
while (temp.hasRemaining() && !done) {
lastByteRead = temp.position();
result = parseSegment(temp.get());
}
if (result == ParseState.good) {
return true;
}
return false;
}
// public HttpRequest request() {
// return req;
// }
private boolean is_char(int c) {
return c >= 0 && c <= 127;
}
private boolean is_ctl(int c) {
return (c >= 0 && c <= 31) || (c == 127);
}
private boolean is_tspecial(int c) {
switch (c) {
case '(': case ')': case '<': case '>': case '@':
case ',': case ';': case ':': case '\\': case '"':
case '/': case '[': case ']': case '?': case '=':
case '{': case '}': case ' ': case '\t':
return true;
default:
return false;
}
}
private boolean is_digit(char c) {
return c >= '0' && c <= '9';
}
private enum ParseState {
good,
bad,
indeterminate;
private static ParseState fromBoolean(boolean state) {
if (state) {
return ParseState.good;
} else {
return ParseState.bad;
}
}
}
private ParseState parseSegment(byte input) {
switch (state_) {
case method_start:
if (!is_char(input) || is_ctl(input) || is_tspecial(input)) {
return ParseState.bad;
} else {
state_ = state.method;
req.method.tick(lastByteRead);
return ParseState.indeterminate;
}
case method:
if (input == ' ') {
state_ = state.uri;
return ParseState.indeterminate;
} else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) {
return ParseState.bad;
} else {
req.method.tick(lastByteRead);
return ParseState.indeterminate;
}
case uri:
if (input == ' ') {
state_ = state.http_version_h;
return ParseState.indeterminate;
} else if (is_ctl(input)) {
return ParseState.bad;
} else {
req.setMethod();
req.uri.tick(lastByteRead);
return ParseState.indeterminate;
}
case http_version_h:
if (input == 'H') {
state_ = state.http_version_t_1;
return ParseState.indeterminate;
} else {
return ParseState.bad;
}
case http_version_t_1:
if (input == 'T') {
state_ = state.http_version_t_2;
return ParseState.indeterminate;
} else {
return ParseState.bad;
}
case http_version_t_2:
if (input == 'T') {
state_ = state.http_version_p;
return ParseState.indeterminate;
} else {
return ParseState.bad;
}
case http_version_p:
if (input == 'P') {
state_ = state.http_version_slash;
return ParseState.indeterminate;
} else {
return ParseState.bad;
}
case http_version_slash:
if (input == '/') {
state_ = state.http_version_major_start;
return ParseState.indeterminate;
} else {
return ParseState.bad;
}
case http_version_major_start:
if (is_digit((char) input)) {
req.http_version_major = (char) input - '0';
state_ = state.http_version_major;
return ParseState.indeterminate;
} else {
return ParseState.bad;
}
case http_version_major:
if (input == '.') {
state_ = state.http_version_minor_start;
return ParseState.indeterminate;
} else if (is_digit((char) input)) {
req.http_version_major = req.http_version_major * 10 + (char) input - '0';
return ParseState.indeterminate;
} else {
return ParseState.bad;
}
case http_version_minor_start:
if (is_digit((char) input)) {
req.http_version_minor = (char) input - '0';
state_ = state.http_version_minor;
return ParseState.indeterminate;
} else {
return ParseState.bad;
}
case http_version_minor:
if (input == '\r') {
state_ = state.expecting_newline_1;
return ParseState.indeterminate;
} else if (is_digit((char) input)) {
req.http_version_minor = req.http_version_minor * 10 + (char) input - '0';
return ParseState.indeterminate;
} else {
return ParseState.bad;
}
case expecting_newline_1:
if (input == '\n') {
state_ = state.header_line_start;
return ParseState.indeterminate;
} else {
return ParseState.bad;
}
case header_line_start:
if (input == '\r') {
state_ = state.expecting_newline_3;
return ParseState.indeterminate;
} else if (!req.headers.empty() && (input == ' ' || input == '\t')) {
state_ = state.header_lws;
return ParseState.indeterminate;
} else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) {
return ParseState.bad;
} else {
req.headers.newHeader();
req.headers.tick(lastByteRead);
state_ = state.header_name;
return ParseState.indeterminate;
}
case header_lws:
if (input == '\r') {
state_ = state.expecting_newline_2;
return ParseState.indeterminate;
} else if (input == ' ' || input == '\t') {
return ParseState.indeterminate;
} else if (is_ctl(input)) {
return ParseState.bad;
} else {
state_ = state.header_value;
req.headers.newValue();
req.headers.tick(lastByteRead);
return ParseState.indeterminate;
}
case header_name:
if (input == ':') {
state_ = state.space_before_header_value;
return ParseState.indeterminate;
} else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) {
return ParseState.bad;
} else {
req.headers.tick(lastByteRead);
return ParseState.indeterminate;
}
case space_before_header_value:
if (input == ' ') {
state_ = state.header_value;
req.headers.newValue();
return ParseState.indeterminate;
} else {
return ParseState.bad;
}
case header_value:
if (input == '\r') {
state_ = state.expecting_newline_2;
return ParseState.indeterminate;
} else if (is_ctl(input)) {
return ParseState.bad;
} else {
req.headers.tick(lastByteRead);
return ParseState.indeterminate;
}
case expecting_newline_2:
if (input == '\n') {
state_ = state.header_line_start;
return ParseState.indeterminate;
} else {
return ParseState.bad;
}
case expecting_newline_3:
finish();
return ParseState.fromBoolean(input == '\n');
default:
return ParseState.bad;
}
}
private void finish() {
req.headers.done();
done = true;
switch (req.method_) {
case GET:
return;
case POST:
req.body.set(lastByteRead);
return;
case PUT:
return;
case DELETE:
return;
default:
return;
}
}
}
| apache-2.0 |
bbossgroups/bboss | bboss-persistent/src/org/frameworkset/persitent/type/Ref_int_RefTypeMethod.java | 1382 | package org.frameworkset.persitent.type;
/**
* Copyright 2022 bboss
* <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.
*/
import com.frameworkset.common.poolman.Param;
import com.frameworkset.common.poolman.StatementInfo;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.SQLException;
import java.util.List;
/**
* <p>Description: </p>
* <p></p>
* <p>Copyright (c) 2020</p>
* @Date 2022/3/2
* @author biaoping.yin
* @version 1.0
*/
public class Ref_int_RefTypeMethod extends BaseTypeMethod{
@Override
public void action(StatementInfo stmtInfo, Param param, PreparedStatement statement, PreparedStatement statement_count, List resources) throws SQLException {
statement.setRef(param.getIndex(), (Ref)param.getData());
if(statement_count != null)
{
statement_count.setRef(param.getIndex(), (Ref)param.getData());
}
}
}
| apache-2.0 |
openaire/iis | iis-wf/iis-wf-referenceextraction/src/main/java/eu/dnetlib/iis/wf/referenceextraction/patent/parser/PatentMetadataParser.java | 536 | package eu.dnetlib.iis.wf.referenceextraction.patent.parser;
import java.io.Serializable;
import eu.dnetlib.iis.referenceextraction.patent.schemas.Patent;
/**
* Patent metadata parser.
*
* @author mhorst
*
*/
public interface PatentMetadataParser extends Serializable {
/**
* Parses XML file and produces {@link Patent.Builder} object by supplementing
* the object provided as parameter.
*/
Patent.Builder parse(CharSequence source, Patent.Builder patentBuilder) throws PatentMetadataParserException;
}
| apache-2.0 |
livetribe/livetribe-slp | osgi/bundle/src/main/java/org/livetribe/slp/osgi/ServiceAgentManagedService.java | 5594 | /**
*
* Copyright 2009 (C) The original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.livetribe.slp.osgi;
import java.io.Closeable;
import java.util.Dictionary;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.livetribe.slp.SLP;
import org.livetribe.slp.osgi.util.DictionarySettings;
import org.livetribe.slp.sa.IServiceAgent;
import org.livetribe.slp.sa.ServiceAgent;
/**
* Instances of {@link ServiceAgent} can be created and configured using OSGi's
* Configuration Admin Service.
* <p/>
* A default {@link ServiceAgent} instance can be created at construction which
* can be replaced when the OSGi service's configuration is updated or no
* {@link ServiceAgent} instance until the service's configuration is updated.
*
* @see ManagedService
* @see ServiceAgent
*/
public class ServiceAgentManagedService implements ManagedService, Closeable
{
private final static String CLASS_NAME = ServiceAgentManagedService.class.getName();
private final static Logger LOGGER = Logger.getLogger(CLASS_NAME);
private final Object lock = new Object();
private final BundleContext bundleContext;
private ServiceAgent serviceAgent;
private ServiceRegistration serviceRegistration;
/**
* Create a <code>ServiceAgentManagedService</code> which will be used to
* manage and configure instances of {@link ServiceAgent} using OSGi's
* Configuration Admin Service.
*
* @param bundleContext The OSGi {@link BundleContext} used to register OSGi service instances.
* @param startDefault Start a default instance of {@link ServiceAgent} if <code>true</code> or wait until the service's configuration is updated otherwise.
*/
public ServiceAgentManagedService(BundleContext bundleContext, boolean startDefault)
{
if (bundleContext == null) throw new IllegalArgumentException("Bundle context cannot be null");
this.bundleContext = bundleContext;
if (startDefault)
{
if (LOGGER.isLoggable(Level.FINER)) LOGGER.finer("Server " + this + " starting...");
serviceAgent = SLP.newServiceAgent(null);
serviceAgent.start();
if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Server " + this + " started successfully");
serviceRegistration = bundleContext.registerService(IServiceAgent.class.getName(), serviceAgent, null);
}
if (LOGGER.isLoggable(Level.CONFIG))
{
LOGGER.config("bundleContext: " + bundleContext);
LOGGER.config("startDefault: " + startDefault);
}
}
/**
* Update the SLP service agent's configuration, unregistering from the
* OSGi service registry and stopping it if it had already started. The
* new SLP service agent will be started with the new configuration and
* registered in the OSGi service registry using the configuration
* parameters as service properties.
*
* @param dictionary The dictionary used to configure the SLP service agent.
* @throws ConfigurationException Thrown if an error occurs during the SLP service agent's configuration.
*/
public void updated(Dictionary dictionary) throws ConfigurationException
{
LOGGER.entering(CLASS_NAME, "updated", dictionary);
synchronized (lock)
{
if (serviceAgent != null)
{
serviceRegistration.unregister();
if (LOGGER.isLoggable(Level.FINER)) LOGGER.finer("Server " + this + " stopping...");
serviceAgent.stop();
if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Server " + this + " stopped successfully");
}
serviceAgent = SLP.newServiceAgent(dictionary == null ? null : DictionarySettings.from(dictionary));
if (LOGGER.isLoggable(Level.FINER)) LOGGER.finer("Server " + this + " starting...");
serviceAgent.start();
if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Server " + this + " started successfully");
serviceRegistration = bundleContext.registerService(IServiceAgent.class.getName(), serviceAgent, dictionary);
}
LOGGER.exiting(CLASS_NAME, "updated");
}
/**
* Shuts down the user agent if one exists.
*/
public void close()
{
LOGGER.entering(CLASS_NAME, "close");
synchronized (lock)
{
if (serviceAgent != null)
{
serviceRegistration.unregister();
if (LOGGER.isLoggable(Level.FINER)) LOGGER.finer("Service Agent " + this + " stopping...");
serviceAgent.stop();
if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Service Agent " + this + " stopped successfully");
}
}
LOGGER.exiting(CLASS_NAME, "close");
}
}
| apache-2.0 |
mfazekas/safaridriver | remote/common/src/java/org/openqa/selenium/remote/JsonToBeanConverter.java | 8809 | /*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.openqa.selenium.remote;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static java.util.Collections.unmodifiableMap;
import static java.util.Collections.unmodifiableSet;
public class JsonToBeanConverter {
@SuppressWarnings("unchecked")
public <T> T convert(Class<T> clazz, Object text) throws Exception {
if (text == null) {
return null;
}
if (String.class.equals(clazz)) {
return (T) text;
}
if (isPrimitive(clazz)) {
return (T) text;
}
if (text instanceof Number) {
// Thank you type erasure.
if (text instanceof Double || text instanceof Float) {
return (T) Double.valueOf(String.valueOf(text));
}
return (T) Long.valueOf(String.valueOf(text));
}
if (isPrimitive(text.getClass())) {
return (T) text;
}
if (isEnum(clazz, text)) {
return (T) convertEnum(clazz, text);
}
if ("".equals(String.valueOf(text))) {
return (T) text;
}
if (Command.class.equals(clazz)) {
JSONObject rawCommand = new JSONObject((String) text);
SessionId sessionId = null;
if (rawCommand.has("sessionId"))
sessionId = convert(SessionId.class, rawCommand.getString("sessionId"));
DriverCommand name = DriverCommand.fromName(rawCommand.getString("name"));
if (rawCommand.has("parameters")) {
Map<String, ?> args =
(Map<String, ?>) convert(HashMap.class, rawCommand.getJSONObject("parameters"));
return (T) new Command(sessionId, name, args);
}
return (T) new Command(sessionId, name);
}
if (SessionId.class.equals(clazz)) {
JSONObject object = new JSONObject((String) text);
String value = object.getString("value");
return (T) new SessionId(value);
}
if (Capabilities.class.equals(clazz)) {
JSONObject object = new JSONObject((String) text);
DesiredCapabilities caps = new DesiredCapabilities();
Iterator allKeys = object.keys();
while (allKeys.hasNext()) {
String key = (String) allKeys.next();
caps.setCapability(key, object.get(key));
}
return (T) caps;
}
if (ProxyPac.class.equals(clazz)) {
JSONObject object = new JSONObject((String) text);
ProxyPac pac = new ProxyPac();
if (object.has("directUrls")) {
JSONArray allUrls = object.getJSONArray("directUrls");
for (int i = 0; i < allUrls.length(); i++) {
pac.map(allUrls.getString(i)).toNoProxy();
}
}
if (object.has("directHosts")) {
JSONArray allHosts = object.getJSONArray("directHosts");
for (int i = 0; i < allHosts.length(); i++) {
pac.mapHost(allHosts.getString(i)).toNoProxy();
}
}
if (object.has("proxiedHosts")) {
JSONObject proxied = object.getJSONObject("proxiedHosts");
Iterator allHosts = proxied.keys();
while (allHosts.hasNext()) {
String host = (String) allHosts.next();
pac.mapHost(host).toProxy(proxied.getString(host));
}
}
if (object.has("proxiedUrls")) {
JSONObject proxied = object.getJSONObject("proxiedUrls");
Iterator allUrls = proxied.keys();
while (allUrls.hasNext()) {
String host = (String) allUrls.next();
pac.map(host).toProxy(proxied.getString(host));
}
}
if (object.has("proxiedRegexUrls")) {
JSONObject proxied = object.getJSONObject("proxiedRegexUrls");
Iterator allUrls = proxied.keys();
while (allUrls.hasNext()) {
String host = (String) allUrls.next();
pac.map(host).toProxy(proxied.getString(host));
}
}
if (object.has("defaultProxy")) {
if ("'DIRECT'".equals(object.getString("defaultProxy"))) {
pac.defaults().toNoProxy();
} else {
pac.defaults().toProxy(object.getString("defaultProxy"));
}
}
if (object.has("deriveFrom")) {
pac.deriveFrom(new URI(object.getString("deriveFrom")));
}
return (T) pac;
}
if (text != null && text instanceof String && !((String) text).startsWith("{") && Object.class
.equals(clazz)) {
return (T) text;
}
if (text instanceof JSONArray) {
return (T) convertList((JSONArray) text);
}
if (text == JSONObject.NULL) {
return null;
}
JSONObject o;
try {
if (text instanceof JSONObject)
o = (JSONObject) text;
else if (text != null && text instanceof String) {
if (((String) text).startsWith("[")) {
return (T) convert(List.class, new JSONArray((String) text));
}
}
o = new JSONObject(String.valueOf(text));
} catch (JSONException e) {
return (T) text;
}
if (Map.class.isAssignableFrom(clazz)) {
return (T) convertMap(o);
}
if (isPrimitive(o.getClass())) {
return (T) o;
}
if (Object.class.equals(clazz)) {
return (T) convertMap(o);
}
return convertBean(clazz, o);
}
@SuppressWarnings("unchecked")
private Enum convertEnum(Class clazz, Object text) {
if (clazz.isEnum()) {
return Enum.valueOf(clazz, String.valueOf(text));
}
Class[] allClasses = clazz.getClasses();
for (Class current : allClasses) {
if (current.isEnum()) {
return Enum.valueOf(current, String.valueOf(text));
}
}
return null;
}
private boolean isEnum(Class<?> clazz, Object text) {
return clazz.isEnum() || text instanceof Enum<?>;
}
private Object convert(Object toConvert) throws Exception {
return toConvert;
}
public <T> T convertBean(Class<T> clazz, JSONObject toConvert) throws Exception {
T t = clazz.newInstance();
PropertyDescriptor[] allProperties = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
for (PropertyDescriptor property : allProperties) {
if (!toConvert.has(property.getName()))
continue;
Object value = toConvert.get(property.getName());
Method write = property.getWriteMethod();
if (write == null) {
continue;
}
Class<?> type = write.getParameterTypes()[0];
try {
write.invoke(t, convert(type, value));
} catch (Exception e) {
throw new Exception(
String.format("Property name: %s -> %s on class %s", property.getName(), value, type),
e);
}
}
return t;
}
@SuppressWarnings("unchecked")
private Map convertMap(JSONObject toConvert) throws Exception {
Map map = new HashMap();
Iterator allEntries = toConvert.keys();
while (allEntries.hasNext()) {
String key = (String) allEntries.next();
map.put(key, convert(Object.class, toConvert.get(key)));
}
return map;
}
@SuppressWarnings("unchecked")
private List convertList(JSONArray toConvert) throws Exception {
ArrayList list = new ArrayList(toConvert.length());
for (int i = 0; i < toConvert.length(); i++) {
list.add(convert(Object.class, toConvert.get(i)));
}
return list;
}
private boolean isPrimitive(Class<?> clazz) {
if (clazz.isPrimitive()) {
return true;
}
if (Boolean.class.isAssignableFrom(clazz)) {
return true;
}
if (Byte.class.isAssignableFrom(clazz)) {
return true;
}
if (Character.class.isAssignableFrom(clazz)) {
return true;
}
if (Double.class.isAssignableFrom(clazz)) {
return true;
}
if (Float.class.isAssignableFrom(clazz)) {
return true;
}
if (Integer.class.isAssignableFrom(clazz)) {
return true;
}
if (Long.class.isAssignableFrom(clazz)) {
return true;
}
if (Short.class.isAssignableFrom(clazz)) {
return true;
}
if (Void.class.isAssignableFrom(clazz)) {
return true;
}
return false;
}
}
| apache-2.0 |
javasoze/clue | src/main/java/io/dashbase/clue/api/DefaultIndexReaderFactory.java | 873 | package io.dashbase.clue.api;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.store.Directory;
public class DefaultIndexReaderFactory implements IndexReaderFactory {
private Directory idxDir = null;
private IndexReader reader = null;
public DefaultIndexReaderFactory() {
}
@Override
public void initialize(Directory idxDir) throws Exception {
this.idxDir = idxDir;
refreshReader();
}
@Override
public void refreshReader() throws Exception {
if (reader != null) {
reader.close();
}
reader = DirectoryReader.open(idxDir);
}
@Override
public IndexReader getIndexReader() {
return reader;
}
@Override
public void shutdown() throws Exception {
if (reader != null) {
reader.close();
reader = null;
}
}
}
| apache-2.0 |
JDevlieghere/MAS | rinsim/src/main/java/rinde/sim/examples/core/package-info.java | 147 | /**
* @author Rinde van Lon <rinde.vanlon@cs.kuleuven.be>
*
*/
@javax.annotation.ParametersAreNonnullByDefault
package rinde.sim.examples.core; | apache-2.0 |
localmatters/lesscss4j | src/test/java/org/localmatters/lesscss4j/compile/AbstractLessCssCompilerTest.java | 3418 | /*
Copyright 2010-present Local Matters, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.localmatters.lesscss4j.compile;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Comparator;
import junit.framework.TestCase;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.localmatters.lesscss4j.error.ErrorHandler;
import org.localmatters.lesscss4j.output.PrettyPrintOptions;
import org.localmatters.lesscss4j.parser.UrlStyleSheetResource;
import org.localmatters.lesscss4j.spring.LessCssCompilerFactoryBean;
public abstract class AbstractLessCssCompilerTest extends TestCase {
public static final String ENCODING = "UTF-8";
protected LessCssCompiler _compiler;
protected PrettyPrintOptions _printOptions;
protected ErrorHandler _errorHandler;
@Override
protected void setUp() throws Exception {
_printOptions = new PrettyPrintOptions();
_printOptions.setSingleDeclarationOnOneLine(true);
_printOptions.setLineBetweenRuleSets(false);
_printOptions.setOpeningBraceOnNewLine(false);
_printOptions.setIndentSize(2);
LessCssCompilerFactoryBean factoryBean = new LessCssCompilerFactoryBean();
factoryBean.setDefaultEncoding(ENCODING);
factoryBean.setPrettyPrintEnabled(true);
factoryBean.setPrettyPrintOptions(_printOptions);
factoryBean.afterPropertiesSet();
_compiler = (LessCssCompiler) factoryBean.getObject();
}
protected String readCss(String cssFile) throws IOException {
InputStream input = null;
try {
input = getClass().getClassLoader().getResourceAsStream(cssFile);
assertNotNull("Unable to open " + cssFile, input);
return IOUtils.toString(input, ENCODING);
}
finally {
IOUtils.closeQuietly(input);
}
}
protected void compileAndValidate(String lessFile, String cssFile) throws IOException {
compileAndValidate(lessFile, cssFile, null);
}
protected void compileAndValidate(String lessFile, String cssFile, Comparator<String> comparator) throws IOException {
URL url = getClass().getClassLoader().getResource(lessFile);
assertNotNull("Unable to open " + lessFile, url);
ByteArrayOutputStream output = new ByteArrayOutputStream();
_compiler.compile(new UrlStyleSheetResource(url), output, _errorHandler);
output.close();
if (_errorHandler == null || _errorHandler.getErrorCount() == 0) {
String expected = readCss(cssFile);
String actual = output.toString(ENCODING);
if (comparator == null) {
assertEquals(expected, actual);
}
else {
comparator.compare(expected, actual);
}
}
}
}
| apache-2.0 |
bobmcwhirter/drools | drools-process/drools-process-enterprise/src/test/java/org/drools/process/enterprise/client/ProcessServiceClient.java | 486 | package org.drools.process.enterprise.client;
import javax.naming.InitialContext;
import org.drools.process.enterprise.processinstance.ProcessService;
public class ProcessServiceClient {
public static void main(String[] args) throws Exception {
InitialContext ctx = new InitialContext();
ProcessService processService = (ProcessService)
ctx.lookup("ProcessServiceBean/remote");
System.out.println(processService.startProcess("com.sample.ruleflow"));
}
} | apache-2.0 |
erikdw/storm | storm-client/src/jvm/org/apache/storm/Thrift.java | 13460 | /*
* 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.storm;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.storm.generated.Bolt;
import org.apache.storm.generated.ComponentCommon;
import org.apache.storm.generated.ComponentObject;
import org.apache.storm.generated.GlobalStreamId;
import org.apache.storm.generated.Grouping;
import org.apache.storm.generated.JavaObject;
import org.apache.storm.generated.JavaObjectArg;
import org.apache.storm.generated.NullStruct;
import org.apache.storm.generated.SpoutSpec;
import org.apache.storm.generated.StateSpoutSpec;
import org.apache.storm.generated.StormTopology;
import org.apache.storm.generated.StormTopology._Fields;
import org.apache.storm.generated.StreamInfo;
import org.apache.storm.shade.org.json.simple.JSONValue;
import org.apache.storm.task.IBolt;
import org.apache.storm.topology.BoltDeclarer;
import org.apache.storm.topology.IBasicBolt;
import org.apache.storm.topology.IRichBolt;
import org.apache.storm.topology.IRichSpout;
import org.apache.storm.topology.SpoutDeclarer;
import org.apache.storm.topology.TopologyBuilder;
import org.apache.storm.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Thrift {
private static Logger LOG = LoggerFactory.getLogger(Thrift.class);
private static StormTopology._Fields[] STORM_TOPOLOGY_FIELDS = null;
private static StormTopology._Fields[] SPOUT_FIELDS =
{ StormTopology._Fields.SPOUTS, StormTopology._Fields.STATE_SPOUTS };
static {
Set<_Fields> keys = StormTopology.metaDataMap.keySet();
keys.toArray(STORM_TOPOLOGY_FIELDS = new StormTopology._Fields[keys.size()]);
}
public static StormTopology._Fields[] getTopologyFields() {
return STORM_TOPOLOGY_FIELDS;
}
public static StormTopology._Fields[] getSpoutFields() {
return SPOUT_FIELDS;
}
public static StreamInfo directOutputFields(List<String> fields) {
return new StreamInfo(fields, true);
}
public static StreamInfo outputFields(List<String> fields) {
return new StreamInfo(fields, false);
}
public static Grouping prepareShuffleGrouping() {
return Grouping.shuffle(new NullStruct());
}
public static Grouping prepareLocalOrShuffleGrouping() {
return Grouping.local_or_shuffle(new NullStruct());
}
public static Grouping prepareFieldsGrouping(List<String> fields) {
return Grouping.fields(fields);
}
public static Grouping prepareGlobalGrouping() {
return prepareFieldsGrouping(new ArrayList<String>());
}
public static Grouping prepareDirectGrouping() {
return Grouping.direct(new NullStruct());
}
public static Grouping prepareAllGrouping() {
return Grouping.all(new NullStruct());
}
public static Grouping prepareNoneGrouping() {
return Grouping.none(new NullStruct());
}
public static Grouping prepareCustomStreamGrouping(Object obj) {
return Grouping.custom_serialized(Utils.javaSerialize(obj));
}
public static Grouping prepareCustomJavaObjectGrouping(JavaObject obj) {
return Grouping.custom_object(obj);
}
public static Object instantiateJavaObject(JavaObject obj) {
List<JavaObjectArg> args = obj.get_args_list();
Class[] paraTypes = new Class[args.size()];
Object[] paraValues = new Object[args.size()];
for (int i = 0; i < args.size(); i++) {
JavaObjectArg arg = args.get(i);
paraValues[i] = arg.getFieldValue();
if (arg.getSetField().equals(JavaObjectArg._Fields.INT_ARG)) {
paraTypes[i] = Integer.class;
} else if (arg.getSetField().equals(JavaObjectArg._Fields.LONG_ARG)) {
paraTypes[i] = Long.class;
} else if (arg.getSetField().equals(JavaObjectArg._Fields.STRING_ARG)) {
paraTypes[i] = String.class;
} else if (arg.getSetField().equals(JavaObjectArg._Fields.BOOL_ARG)) {
paraTypes[i] = Boolean.class;
} else if (arg.getSetField().equals(JavaObjectArg._Fields.BINARY_ARG)) {
paraTypes[i] = ByteBuffer.class;
} else if (arg.getSetField().equals(JavaObjectArg._Fields.DOUBLE_ARG)) {
paraTypes[i] = Double.class;
} else {
paraTypes[i] = Object.class;
}
}
try {
Class clazz = Class.forName(obj.get_full_class_name());
Constructor cons = clazz.getConstructor(paraTypes);
return cons.newInstance(paraValues);
} catch (Exception e) {
LOG.error("java object instantiation failed", e);
}
return null;
}
public static Grouping._Fields groupingType(Grouping grouping) {
return grouping.getSetField();
}
public static List<String> fieldGrouping(Grouping grouping) {
if (!Grouping._Fields.FIELDS.equals(groupingType(grouping))) {
throw new IllegalArgumentException("Tried to get grouping fields from non fields grouping");
}
return grouping.get_fields();
}
public static boolean isGlobalGrouping(Grouping grouping) {
if (Grouping._Fields.FIELDS.equals(groupingType(grouping))) {
return fieldGrouping(grouping).isEmpty();
}
return false;
}
public static int getParallelismHint(ComponentCommon componentCommon) {
if (!componentCommon.is_set_parallelism_hint()) {
return 1;
} else {
return componentCommon.get_parallelism_hint();
}
}
public static ComponentObject serializeComponentObject(Object obj) {
return ComponentObject.serialized_java(Utils.javaSerialize(obj));
}
public static Object deserializeComponentObject(ComponentObject obj) {
if (obj.getSetField() != ComponentObject._Fields.SERIALIZED_JAVA) {
throw new RuntimeException("Cannot deserialize non-java-serialized object");
}
return Utils.javaDeserialize(obj.get_serialized_java(), Serializable.class);
}
public static ComponentCommon prepareComponentCommon(Map<GlobalStreamId, Grouping> inputs, Map<String,
StreamInfo> outputs, Integer parallelismHint) {
return prepareComponentCommon(inputs, outputs, parallelismHint, null);
}
public static ComponentCommon prepareComponentCommon(Map<GlobalStreamId, Grouping> inputs, Map<String, StreamInfo> outputs,
Integer parallelismHint, Map<String, Object> conf) {
Map<GlobalStreamId, Grouping> mappedInputs = new HashMap<>();
Map<String, StreamInfo> mappedOutputs = new HashMap<>();
if (inputs != null && !inputs.isEmpty()) {
mappedInputs.putAll(inputs);
}
if (outputs != null && !outputs.isEmpty()) {
mappedOutputs.putAll(outputs);
}
ComponentCommon component = new ComponentCommon(mappedInputs, mappedOutputs);
if (parallelismHint != null) {
component.set_parallelism_hint(parallelismHint);
}
if (conf != null) {
component.set_json_conf(JSONValue.toJSONString(conf));
}
return component;
}
public static SpoutSpec prepareSerializedSpoutDetails(IRichSpout spout, Map<String, StreamInfo> outputs) {
return new SpoutSpec(ComponentObject.serialized_java
(Utils.javaSerialize(spout)), prepareComponentCommon(new HashMap<>(), outputs, null, null));
}
public static Bolt prepareSerializedBoltDetails(Map<GlobalStreamId, Grouping> inputs, IBolt bolt, Map<String, StreamInfo> outputs,
Integer parallelismHint, Map<String, Object> conf) {
ComponentCommon common = prepareComponentCommon(inputs, outputs, parallelismHint, conf);
return new Bolt(ComponentObject.serialized_java(Utils.javaSerialize(bolt)), common);
}
public static BoltDetails prepareBoltDetails(Map<GlobalStreamId, Grouping> inputs, Object bolt) {
return prepareBoltDetails(inputs, bolt, null, null);
}
public static BoltDetails prepareBoltDetails(Map<GlobalStreamId, Grouping> inputs, Object bolt,
Integer parallelismHint) {
return prepareBoltDetails(inputs, bolt, parallelismHint, null);
}
public static BoltDetails prepareBoltDetails(Map<GlobalStreamId, Grouping> inputs, Object bolt,
Integer parallelismHint, Map<String, Object> conf) {
BoltDetails details = new BoltDetails(bolt, conf, parallelismHint, inputs);
return details;
}
public static SpoutDetails prepareSpoutDetails(IRichSpout spout) {
return prepareSpoutDetails(spout, null, null);
}
public static SpoutDetails prepareSpoutDetails(IRichSpout spout, Integer parallelismHint) {
return prepareSpoutDetails(spout, parallelismHint, null);
}
public static SpoutDetails prepareSpoutDetails(IRichSpout spout, Integer parallelismHint, Map<String, Object> conf) {
SpoutDetails details = new SpoutDetails(spout, parallelismHint, conf);
return details;
}
public static StormTopology buildTopology(HashMap<String, SpoutDetails> spoutMap,
HashMap<String, BoltDetails> boltMap, HashMap<String, StateSpoutSpec> stateMap) {
return buildTopology(spoutMap, boltMap);
}
private static void addInputs(BoltDeclarer declarer, Map<GlobalStreamId, Grouping> inputs) {
for (Entry<GlobalStreamId, Grouping> entry : inputs.entrySet()) {
declarer.grouping(entry.getKey(), entry.getValue());
}
}
public static StormTopology buildTopology(Map<String, SpoutDetails> spoutMap, Map<String, BoltDetails> boltMap) {
TopologyBuilder builder = new TopologyBuilder();
for (Entry<String, SpoutDetails> entry : spoutMap.entrySet()) {
String spoutId = entry.getKey();
SpoutDetails spec = entry.getValue();
SpoutDeclarer spoutDeclarer = builder.setSpout(spoutId, spec.getSpout(), spec.getParallelism());
spoutDeclarer.addConfigurations(spec.getConf());
}
for (Entry<String, BoltDetails> entry : boltMap.entrySet()) {
String spoutId = entry.getKey();
BoltDetails spec = entry.getValue();
BoltDeclarer boltDeclarer = null;
if (spec.bolt instanceof IRichBolt) {
boltDeclarer = builder.setBolt(spoutId, (IRichBolt) spec.getBolt(), spec.getParallelism());
} else {
boltDeclarer = builder.setBolt(spoutId, (IBasicBolt) spec.getBolt(), spec.getParallelism());
}
boltDeclarer.addConfigurations(spec.getConf());
addInputs(boltDeclarer, spec.getInputs());
}
return builder.createTopology();
}
public static class SpoutDetails {
private IRichSpout spout;
private Integer parallelism;
private Map<String, Object> conf;
public SpoutDetails(IRichSpout spout, Integer parallelism, Map<String, Object> conf) {
this.spout = spout;
this.parallelism = parallelism;
this.conf = conf;
}
public IRichSpout getSpout() {
return spout;
}
public Integer getParallelism() {
return parallelism;
}
public Map<String, Object> getConf() {
return conf;
}
}
public static class BoltDetails {
private Object bolt;
private Map<String, Object> conf;
private Integer parallelism;
private Map<GlobalStreamId, Grouping> inputs;
public BoltDetails(Object bolt, Map<String, Object> conf, Integer parallelism,
Map<GlobalStreamId, Grouping> inputs) {
this.bolt = bolt;
this.conf = conf;
this.parallelism = parallelism;
this.inputs = inputs;
}
public Object getBolt() {
return bolt;
}
public Map<String, Object> getConf() {
return conf;
}
public Map<GlobalStreamId, Grouping> getInputs() {
return inputs;
}
public Integer getParallelism() {
return parallelism;
}
}
}
| apache-2.0 |
tectronics/tpt | modules/tpt-demo/src/java/eu/livotov/tpt/demo/widgets/SizerDemoItem.java | 3235 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eu.livotov.tpt.demo.widgets;
import com.vaadin.terminal.Resource;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import eu.livotov.tpt.TPTApplication;
import eu.livotov.tpt.demo.api.DemoItem;
import eu.livotov.tpt.gui.widgets.TPTSizer;
import eu.livotov.tpt.i18n.TM;
import java.io.Serializable;
/**
*
* @author dll
*/
public class SizerDemoItem implements DemoItem, Serializable
{
public boolean hasSourceCode ()
{
return true;
}
public boolean hasShowCase ()
{
return true;
}
public String getItemName ()
{
return TM.get ( "sizer.title" );
}
public String getItemDescription ()
{
return TM.get ( "sizer.info" );
}
public String getItemSourceCode ()
{
return "public class SizerDemoWindow extends Window\n" +
" {\n" +
"\n" +
" private VerticalLayout root = new VerticalLayout ();\n" +
"\n" +
" public SizerDemoWindow ()\n" +
" {\n" +
" super ( \"TPTSizer Demo\" );\n" +
" initUI ();\n" +
" }\n" +
"\n" +
" private void initUI ()\n" +
" {\n" +
" setSizeFull ();\n" +
" root.setSizeFull ();\n" +
" root.setMargin ( true );\n" +
" root.setSpacing ( true );\n" +
" setContent ( root );\n" +
"\n" +
" addComponent ( new Label ( \"Label 1\") );\n" +
" addComponent ( new TPTSizer ( null, \"30px\"));\n" +
" addComponent ( new Label ( \"Label 2. Im standing exactly 30 pixels below Label 1, thanks to TPTSizer between us !\"));\n" +
" }\n" +
" }";
}
public void performShowCase ()
{
SizerDemoWindow w = new SizerDemoWindow ();
w.setWidth ( "400px" );
w.setHeight ( "200px" );
w.setModal ( true );
TPTApplication.getCurrentApplication ().getMainWindow ().addWindow ( w );
}
public Resource getIcon ()
{
return new ThemeResource ( "icons/sizer.png" );
}
public class SizerDemoWindow extends Window
{
private VerticalLayout root = new VerticalLayout ();
public SizerDemoWindow ()
{
super ( TM.get ( "sizer.caption" ) );
initUI ();
}
private void initUI ()
{
setSizeFull ();
root.setSizeFull ();
root.setMargin ( true );
root.setSpacing ( true );
setContent ( root );
addComponent ( new Label ( TM.get ( "sizer.label1" ) ) );
addComponent ( new TPTSizer ( null, "30px" ) );
addComponent ( new Label ( TM.get ( "sizer.label2" ) ) );
}
}
}
| apache-2.0 |
gdbaker/gdbaker-SizeBook | app/build/generated/source/buildConfig/debug/com/example/gdbaker_sizebook/BuildConfig.java | 463 | /**
* Automatically generated file. DO NOT MODIFY
*/
package com.example.gdbaker_sizebook;
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.example.gdbaker_sizebook";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0";
}
| apache-2.0 |
codyer/CleanFramework | app/src/main/java/com/cody/app/framework/upgrade/UpdateDelegate.java | 8828 | package com.cody.app.framework.upgrade;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import com.cody.app.R;
import com.cody.handler.framework.viewmodel.UpdateViewModel;
import com.cody.xf.utils.CommonUtil;
import com.cody.xf.utils.LogUtil;
import com.cody.xf.utils.ResourceUtil;
import com.cody.xf.utils.ToastUtil;
import com.cody.xf.widget.dialog.AlertDialog;
/**
* 版本更新
*/
public class UpdateDelegate {
private final Activity mActivity;
private final UpdateViewModel mUpdateViewModel;
private ProgressDialog mProgressDialog;
private OnUpdateListener mOnUpdateListener;
private boolean isBindService;
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
DownloadService.DownloadBinder binder = (DownloadService.DownloadBinder) service;
DownloadService downloadService = binder.getService();
if (downloadService.isDownloaded()) {
stopDownLoadService();
mOnUpdateListener.onUpdateFinish();
mProgressDialog.dismiss();
}
//接口回调,下载进度
downloadService.setOnProgressListener(new DownloadService.OnDownloadListener() {
@Override
public void onStart() {
}
@Override
public void onProgress(int size, int total) {
String progress = String.format(ResourceUtil.getString(R.string.download_progress_format), CommonUtil.formatSize(size), CommonUtil.formatSize(total));
LogUtil.d("download", progress);
mProgressDialog.setMax(total);
mProgressDialog.setProgress(size);
mProgressDialog.setMessage(progress);
}
@Override
public void onFinish() {
ToastUtil.showToast(ResourceUtil.getString(R.string.download_finished));
stopDownLoadService();
mProgressDialog.dismiss();
mOnUpdateListener.onUpdateFinish();
}
@Override
public void onFailure() {
ToastUtil.showToast("更新失败!");
stopDownLoadService();
mProgressDialog.dismiss();
mOnUpdateListener.onUpdateFinish();
}
});
isBindService = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
isBindService = false;
}
};
private UpdateDelegate(Activity activity, UpdateViewModel viewModel, OnUpdateListener onUpdateListener) {
mActivity = activity;
mUpdateViewModel = viewModel;
mOnUpdateListener = onUpdateListener;
mProgressDialog = new ProgressDialog(activity);
mProgressDialog.setTitle(ResourceUtil.getString(R.string.version_update));
mProgressDialog.setMessage(ResourceUtil.getString(R.string.update_progress));
mProgressDialog.setProgressNumberFormat(null);
mProgressDialog.setCancelable(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
if (mUpdateViewModel.isForceUpdate()) {
forceUpdate();
} else if (mUpdateViewModel.isOptionalUpdate()) {
optionalUpdate();
} else {
// ToastUtil.showToast(ResourceUtil.getString(R.string.the_best_version));
mOnUpdateListener.onUpdateFinish();
}
}
public static void delegate(Activity activity, UpdateViewModel viewModel, OnUpdateListener onUpdateListener) {
new UpdateDelegate(activity, viewModel, onUpdateListener);
}
/**
* 选择更新
*/
private void optionalUpdate() {
new AlertDialog(mActivity).builder()
.setTitle(mActivity.getString(R.string.upgrade_title))
.setMsg(mUpdateViewModel.getUpdateInfo())
.setCancelable(false)
.setPositiveButton(ResourceUtil.getString(R.string.update_now), new View.OnClickListener() {
@Override
public void onClick(View v) {
bindDownLoadService();
}
})
.setNegativeButton(ResourceUtil.getString(R.string.not_now), new View.OnClickListener() {
@Override
public void onClick(View v) {
mOnUpdateListener.onUpdateFinish();
}
}).show();
}
/**
* 强制更新
*/
private void forceUpdate() {
final AlertDialog alertDialog = new AlertDialog(mActivity).builder()
.setTitle(mActivity.getString(R.string.upgrade_title))
.setMsg(mUpdateViewModel.getUpdateInfo())
.setCancelable(false)
.setPositiveButton(ResourceUtil.getString(R.string.update_now), new View.OnClickListener() {
@Override
public void onClick(View v) {
bindDownLoadService();
}
});
alertDialog.show();
alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
((Activity) alertDialog.getContext()).finish();
}
return false;
}
});
}
/**
* DownloadManager是否可用
*
* @param context
* @return
*/
private boolean isDownLoadMangerEnable(Context context) {
int state = context.getApplicationContext().getPackageManager()
.getApplicationEnabledSetting("com.android.providers.downloads");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
return !(state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED ||
state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
|| state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED);
} else {
return !(state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED ||
state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER);
}
}
private void bindDownLoadService() {
if (isDownLoadMangerEnable(mActivity)) {
Intent intent = new Intent(mActivity, DownloadService.class);
intent.putExtra(DownloadService.DOWNLOAD, mUpdateViewModel.getApkUrl());
intent.putExtra(DownloadService.APK_NAME, mUpdateViewModel.getApkName());
intent.putExtra(DownloadService.IS_FORCE, mUpdateViewModel.isForceUpdate());
mActivity.startService(intent);
mProgressDialog.show();
mActivity.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
} else {//下载管理器被禁用时跳转浏览器下载
try {
if (!TextUtils.isEmpty(mUpdateViewModel.getApkUrl()) && mActivity != null) {
Intent intent = new Intent();
Uri uri = Uri.parse(mUpdateViewModel.getApkUrl());
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
if (intent.resolveActivity(mActivity.getPackageManager()) != null) {
mActivity.startActivity(Intent.createChooser(intent, "请选择浏览器进行下载更新"));
System.exit(0);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void stopDownLoadService() {
try {
Intent intent = new Intent(mActivity, DownloadService.class);
if (isBindService) {
mActivity.unbindService(mServiceConnection);
isBindService = false;
}
mActivity.stopService(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
public interface OnUpdateListener {
void onUpdateFinish();
}
} | apache-2.0 |
casimirenslip/java-libpst | com/pff/parsing/DescriptorIndexNode.java | 4097 | /**
* Copyright 2010 Richard Johnson & Orin Eman
*
* 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 file is part of java-libpst.
*
* java-libpst 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.
*
* java-libpst 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 java-libpst. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.pff.parsing;
import java.io.IOException;
import com.pff.PSTUtils;
import com.pff.exceptions.PSTException;
import com.pff.source.PSTSource;
/**
* DescriptorIndexNode is a leaf item from the Descriptor index b-tree
* It is like a pointer to an element in the PST file, everything has one...
* @author Richard Johnson
*/
public class DescriptorIndexNode {
public int descriptorIdentifier;
public long dataOffsetIndexIdentifier;
public long localDescriptorsOffsetIndexIdentifier;
public int parentDescriptorIndexIdentifier;
public int itemType;
//PSTFile.PSTFileBlock dataBlock = null;
/**
* parse the data out into something meaningful
* @param data
*/
public DescriptorIndexNode(byte[] data, int pstFileType) {
// parse it out
// first 4 bytes
if (pstFileType == PSTSource.PST_TYPE_ANSI) {
descriptorIdentifier = (int)PSTUtils.convertLittleEndianBytesToLong(data, 0, 4);
dataOffsetIndexIdentifier = (int)PSTUtils.convertLittleEndianBytesToLong(data, 4, 8);
localDescriptorsOffsetIndexIdentifier = (int)PSTUtils.convertLittleEndianBytesToLong(data, 8, 12);
parentDescriptorIndexIdentifier = (int)PSTUtils.convertLittleEndianBytesToLong(data, 12, 16);
//itemType = (int)PSTObject.convertLittleEndianBytesToLong(data, 28, 32);
} else {
descriptorIdentifier = (int)PSTUtils.convertLittleEndianBytesToLong(data, 0, 4);
dataOffsetIndexIdentifier = (int)PSTUtils.convertLittleEndianBytesToLong(data, 8, 16);
localDescriptorsOffsetIndexIdentifier = (int)PSTUtils.convertLittleEndianBytesToLong(data, 16, 24);
parentDescriptorIndexIdentifier = (int)PSTUtils.convertLittleEndianBytesToLong(data, 24, 28);
itemType = (int)PSTUtils.convertLittleEndianBytesToLong(data, 28, 32);
}
}
/*
void readData(PSTFile file)
throws IOException, PSTException
{
if ( dataBlock == null ) {
dataBlock = file.readLeaf(dataOffsetIndexIdentifier);
}
}
*
*/
PSTNodeInputStream getNodeInputStream(PSTSource pstFile)
throws IOException, PSTException
{
return new PSTNodeInputStream(pstFile,pstFile.getOffsetIndexNode(dataOffsetIndexIdentifier));
}
public String toString() {
return "DescriptorIndexNode\n" +
"Descriptor Identifier: "+descriptorIdentifier+" (0x"+Long.toHexString(descriptorIdentifier)+")\n"+
"Data offset identifier: "+dataOffsetIndexIdentifier+" (0x"+Long.toHexString(dataOffsetIndexIdentifier)+")\n"+
"Local descriptors offset index identifier: "+localDescriptorsOffsetIndexIdentifier+" (0x"+Long.toHexString(localDescriptorsOffsetIndexIdentifier)+")\n"+
"Parent Descriptor Index Identifier: "+parentDescriptorIndexIdentifier+" (0x"+Long.toHexString(parentDescriptorIndexIdentifier)+")\n"+
"Item Type: "+itemType+" (0x"+Long.toHexString(itemType)+")";
}
}
| apache-2.0 |
adithnaveen/SdetBatch2 | SDET-2 Workspace/MVCWorks/src/com/fannie/controller/GetAllAccountsController.java | 734 | package com.fannie.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fannie.bl.AccountBL;
@WebServlet("/showall.do")
public class GetAllAccountsController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("ACCS", new AccountBL().getAllAccounts());
request.getRequestDispatcher("/WEB-INF/view/ShowAll1.jsp").forward(request, response);
}
}
| apache-2.0 |
lakshmiDRIP/DRIP | src/main/java/org/drip/market/otc/SwapOptionSettlement.java | 4387 |
package org.drip.market.otc;
/*
* -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*/
/*!
* Copyright (C) 2016 Lakshmi Krishnamurthy
* Copyright (C) 2015 Lakshmi Krishnamurthy
*
* This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model
* libraries targeting analysts and developers
* https://lakshmidrip.github.io/DRIP/
*
* DRIP is composed of four main libraries:
*
* - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/
* - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/
* - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/
* - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/
*
* - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options,
* Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA
* Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV
* Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM
* Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics.
*
* - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy
* Incorporator, Holdings Constraint, and Transaction Costs.
*
* - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality.
*
* - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* SwapOptionSettlement contains the details of the OTC Swap Option Settlements.
*
* @author Lakshmi Krishnamurthy
*/
public class SwapOptionSettlement {
/**
* Swap Option Settlement Type - Cash Settled
*/
public static final int SETTLEMENT_TYPE_CASH_SETTLED = 1;
/**
* Swap Option Settlement Type - Physical Delivery
*/
public static final int SETTLEMENT_TYPE_PHYSICAL_DELIVERY = 2;
/**
* Swap Option Cash Settlement Quote Method - Internal Rate of Return
*/
public static final int SETTLEMENT_QUOTE_IRR = 1;
/**
* Swap Option Cash Settlement Quote Method - Exact Curve
*/
public static final int SETTLEMENT_QUOTE_EXACT_CURVE = 2;
private int _iSettlementType = -1;
private int _iSettlementQuote = -1;
/**
* SwapOptionSettlement Constructor
*
* @param iSettlementType Settlement Type
* @param iSettlementQuote Settlement Quote
*
* @throws java.lang.Exception Thrown if the Inputs are Invalid
*/
public SwapOptionSettlement (
final int iSettlementType,
final int iSettlementQuote)
throws java.lang.Exception
{
if (SETTLEMENT_TYPE_CASH_SETTLED != (_iSettlementType = iSettlementType) &&
SETTLEMENT_TYPE_PHYSICAL_DELIVERY != _iSettlementType)
throw new java.lang.Exception ("SwapOptionSettlement ctr: Invalid Settlement Type");
if (SETTLEMENT_TYPE_CASH_SETTLED == _iSettlementType && SETTLEMENT_QUOTE_IRR != (_iSettlementQuote =
iSettlementQuote) && SETTLEMENT_QUOTE_EXACT_CURVE != _iSettlementQuote)
throw new java.lang.Exception ("SwapOptionSettlement ctr: Invalid Settlement Quote");
}
/**
* Retrieve the Settlement Type
*
* @return The Settlement Type
*/
public int settlementType()
{
return _iSettlementType;
}
/**
* Retrieve the Settlement Quote
*
* @return The Settlement Quote
*/
public int settlementQuote()
{
return _iSettlementQuote;
}
@Override public java.lang.String toString()
{
if (SETTLEMENT_TYPE_PHYSICAL_DELIVERY == _iSettlementType) return "PHYSICAL DELIVERY";
return "CASH SETTLED | " + (SETTLEMENT_QUOTE_IRR == _iSettlementQuote ? "INTERNAL RATE OF RETURN" :
"EXACT CURVE");
}
}
| apache-2.0 |
mesosphere/usergrid | stack/core/src/main/java/org/apache/usergrid/persistence/query/ir/NotNode.java | 1855 | /*
* 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.usergrid.persistence.query.ir;
/** @author tnine */
public class NotNode extends QueryNode {
protected QueryNode subtractNode, keepNode;
/** @param keepNode may be null if there are parents to this */
public NotNode( QueryNode subtractNode, QueryNode keepNode ) {
this.subtractNode = subtractNode;
this.keepNode = keepNode;
// throw new RuntimeException( "I'm a not node" );
}
/** @return the child */
public QueryNode getSubtractNode() {
return subtractNode;
}
/** @return the all */
public QueryNode getKeepNode() {
return keepNode;
}
/*
* (non-Javadoc)
*
* @see
* org.apache.usergrid.persistence.query.ir.QueryNode#visit(org.apache.usergrid.persistence
* .query.ir.NodeVisitor)
*/
@Override
public void visit( NodeVisitor visitor ) throws Exception {
visitor.visit( this );
}
@Override
public String toString() {
return "NotNode [child=" + subtractNode + "]";
}
}
| apache-2.0 |
irudyak/ant-toolkit | dev/modules/native/general/src/main/java/com/anttoolkit/general/entities/PropertyEntityType.java | 344 | package com.anttoolkit.general.entities;
public class PropertyEntityType extends EntityType
{
public static final PropertyEntityType instance = new PropertyEntityType();
private PropertyEntityType() {}
@Override
public String getName()
{
return "PROPERTY";
}
@Override
public boolean allowedForRootScope()
{
return false;
}
}
| apache-2.0 |
longjiazuo/java-project | j2se-project/java-exception/src/main/java/org/light4j/exception/access/AccessExceptionMsg.java | 415 | package org.light4j.exception.access;
import java.io.FileInputStream;
import java.io.IOException;
public class AccessExceptionMsg
{
public static void main(String[] args)
{
try
{
FileInputStream fis = new FileInputStream("a.txt");
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
System.out.println(ioe.getStackTrace());
ioe.printStackTrace();
}
}
} | apache-2.0 |
klr8/svn-logstats | src/test/java/com/ervacon/svn/logstats/UtilTest.java | 1295 | /*
* Copyright 2017 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.ervacon.svn.logstats;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test;
public class UtilTest {
@Test
public void testReadClassPathResource() throws Exception {
assertNotNull(Util.readClassPathResource("/style.css"));
}
@Test
public void testGetFilenameExtension() {
assertEquals("java", Util.getFilenameExtension("Test.java"));
assertEquals("java", Util.getFilenameExtension("/foo/bar/Test.java"));
assertEquals("java", Util.getFilenameExtension("/foo/bar-1.0.0/Test.java"));
assertNull(Util.getFilenameExtension("/foo/bar/startup"));
}
}
| apache-2.0 |
markflyhigh/incubator-beam | sdks/java/testing/nexmark/src/main/java/org/apache/beam/sdk/nexmark/queries/Query10.java | 16954 | /*
* 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.beam.sdk.nexmark.queries;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ThreadLocalRandom;
import javax.annotation.Nullable;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.extensions.gcp.options.GcsOptions;
import org.apache.beam.sdk.metrics.Counter;
import org.apache.beam.sdk.metrics.Metrics;
import org.apache.beam.sdk.nexmark.NexmarkConfiguration;
import org.apache.beam.sdk.nexmark.model.Done;
import org.apache.beam.sdk.nexmark.model.Event;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.GroupByKey;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.windowing.AfterEach;
import org.apache.beam.sdk.transforms.windowing.AfterFirst;
import org.apache.beam.sdk.transforms.windowing.AfterPane;
import org.apache.beam.sdk.transforms.windowing.AfterProcessingTime;
import org.apache.beam.sdk.transforms.windowing.AfterWatermark;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.transforms.windowing.FixedWindows;
import org.apache.beam.sdk.transforms.windowing.PaneInfo;
import org.apache.beam.sdk.transforms.windowing.PaneInfo.Timing;
import org.apache.beam.sdk.transforms.windowing.Repeatedly;
import org.apache.beam.sdk.transforms.windowing.Window;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Query "10", 'Log to sharded files' (Not in original suite.)
*
* <p>Every windowSizeSec, save all events from the last period into 2*maxWorkers log files.
*/
public class Query10 extends NexmarkQueryTransform<Done> {
private static final Logger LOG = LoggerFactory.getLogger(Query10.class);
private static final int NUM_SHARDS_PER_WORKER = 5;
private static final Duration LATE_BATCHING_PERIOD = Duration.standardSeconds(10);
private final NexmarkConfiguration configuration;
/** Capture everything we need to know about the records in a single output file. */
private static class OutputFile implements Serializable {
/** Maximum possible timestamp of records in file. */
private final Instant maxTimestamp;
/** Shard within window. */
private final String shard;
/** Index of file in all files in shard. */
private final long index;
/** Timing of records in this file. */
private final PaneInfo.Timing timing;
/** Path to file containing records, or {@literal null} if no output required. */
@Nullable private final String filename;
public OutputFile(
Instant maxTimestamp,
String shard,
long index,
PaneInfo.Timing timing,
@Nullable String filename) {
this.maxTimestamp = maxTimestamp;
this.shard = shard;
this.index = index;
this.timing = timing;
this.filename = filename;
}
@Override
public String toString() {
return String.format("%s %s %d %s %s%n", maxTimestamp, shard, index, timing, filename);
}
}
/** GCS uri prefix for all log and 'finished' files. If null they won't be written. */
@Nullable private String outputPath;
/** Maximum number of workers, used to determine log sharding factor. */
private int maxNumWorkers;
public Query10(NexmarkConfiguration configuration) {
super("Query10");
this.configuration = configuration;
}
public void setOutputPath(@Nullable String outputPath) {
this.outputPath = outputPath;
}
public void setMaxNumWorkers(int maxNumWorkers) {
this.maxNumWorkers = maxNumWorkers;
}
/** Return channel for writing bytes to GCS. */
private WritableByteChannel openWritableGcsFile(GcsOptions options, String filename)
throws IOException {
// TODO
// Fix after PR: right now this is a specific Google added use case
// Discuss it on ML: shall we keep GCS or use HDFS or use a generic beam filesystem way.
throw new UnsupportedOperationException("Disabled after removal of GcsIOChannelFactory");
}
/** Return a short string to describe {@code timing}. */
private String timingToString(PaneInfo.Timing timing) {
switch (timing) {
case EARLY:
return "E";
case ON_TIME:
return "O";
case LATE:
return "L";
case UNKNOWN:
return "U";
}
throw new RuntimeException(); // cases are exhaustive
}
/** Construct an {@link OutputFile} for {@code pane} in {@code window} for {@code shard}. */
private OutputFile outputFileFor(BoundedWindow window, String shard, PaneInfo pane) {
@Nullable
String filename =
outputPath == null
? null
: String.format(
"%s/LOG-%s-%s-%03d-%s-%x",
outputPath,
window.maxTimestamp(),
shard,
pane.getIndex(),
timingToString(pane.getTiming()),
ThreadLocalRandom.current().nextLong());
return new OutputFile(
window.maxTimestamp(), shard, pane.getIndex(), pane.getTiming(), filename);
}
/**
* Return path to which we should write the index for {@code window}, or {@literal null} if no
* output required.
*/
@Nullable
private String indexPathFor(BoundedWindow window) {
if (outputPath == null) {
return null;
}
return String.format("%s/INDEX-%s", outputPath, window.maxTimestamp());
}
@Override
public PCollection<Done> expand(PCollection<Event> events) {
final int numLogShards = maxNumWorkers * NUM_SHARDS_PER_WORKER;
return events
.apply(
name + ".ShardEvents",
ParDo.of(
new DoFn<Event, KV<String, Event>>() {
private final Counter lateCounter = Metrics.counter(name, "actuallyLateEvent");
private final Counter onTimeCounter = Metrics.counter(name, "onTimeCounter");
@ProcessElement
public void processElement(ProcessContext c) {
if (c.element().hasAnnotation("LATE")) {
lateCounter.inc();
LOG.info("Observed late: %s", c.element());
} else {
onTimeCounter.inc();
}
int shardNum = (int) Math.abs((long) c.element().hashCode() % numLogShards);
String shard = String.format("shard-%05d-of-%05d", shardNum, numLogShards);
c.output(KV.of(shard, c.element()));
}
}))
.apply(
name + ".WindowEvents",
Window.<KV<String, Event>>into(
FixedWindows.of(Duration.standardSeconds(configuration.windowSizeSec)))
.triggering(
AfterEach.inOrder(
Repeatedly.forever(
AfterPane.elementCountAtLeast(configuration.maxLogEvents))
.orFinally(AfterWatermark.pastEndOfWindow()),
Repeatedly.forever(
AfterFirst.of(
AfterPane.elementCountAtLeast(configuration.maxLogEvents),
AfterProcessingTime.pastFirstElementInPane()
.plusDelayOf(LATE_BATCHING_PERIOD)))))
.discardingFiredPanes()
// Use a 1 day allowed lateness so that any forgotten hold will stall the
// pipeline for that period and be very noticeable.
.withAllowedLateness(Duration.standardDays(1)))
.apply(name + ".GroupByKey", GroupByKey.create())
.apply(
name + ".CheckForLateEvents",
ParDo.of(
new DoFn<KV<String, Iterable<Event>>, KV<String, Iterable<Event>>>() {
private final Counter earlyCounter = Metrics.counter(name, "earlyShard");
private final Counter onTimeCounter = Metrics.counter(name, "onTimeShard");
private final Counter lateCounter = Metrics.counter(name, "lateShard");
private final Counter unexpectedLatePaneCounter =
Metrics.counter(name, "ERROR_unexpectedLatePane");
private final Counter unexpectedOnTimeElementCounter =
Metrics.counter(name, "ERROR_unexpectedOnTimeElement");
@ProcessElement
public void processElement(ProcessContext c, BoundedWindow window) {
int numLate = 0;
int numOnTime = 0;
for (Event event : c.element().getValue()) {
if (event.hasAnnotation("LATE")) {
numLate++;
} else {
numOnTime++;
}
}
String shard = c.element().getKey();
LOG.info(
String.format(
"%s with timestamp %s has %d actually late and %d on-time "
+ "elements in pane %s for window %s",
shard,
c.timestamp(),
numLate,
numOnTime,
c.pane(),
window.maxTimestamp()));
if (c.pane().getTiming() == PaneInfo.Timing.LATE) {
if (numLate == 0) {
LOG.error("ERROR! No late events in late pane for %s", shard);
unexpectedLatePaneCounter.inc();
}
if (numOnTime > 0) {
LOG.error(
"ERROR! Have %d on-time events in late pane for %s", numOnTime, shard);
unexpectedOnTimeElementCounter.inc();
}
lateCounter.inc();
} else if (c.pane().getTiming() == PaneInfo.Timing.EARLY) {
if (numOnTime + numLate < configuration.maxLogEvents) {
LOG.error(
"ERROR! Only have %d events in early pane for %s",
numOnTime + numLate, shard);
}
earlyCounter.inc();
} else {
onTimeCounter.inc();
}
c.output(c.element());
}
}))
.apply(
name + ".UploadEvents",
ParDo.of(
new DoFn<KV<String, Iterable<Event>>, KV<Void, OutputFile>>() {
private final Counter savedFileCounter = Metrics.counter(name, "savedFile");
private final Counter writtenRecordsCounter =
Metrics.counter(name, "writtenRecords");
@ProcessElement
public void processElement(ProcessContext c, BoundedWindow window)
throws IOException {
String shard = c.element().getKey();
GcsOptions options = c.getPipelineOptions().as(GcsOptions.class);
OutputFile outputFile = outputFileFor(window, shard, c.pane());
LOG.info(
String.format(
"Writing %s with record timestamp %s, window timestamp %s, pane %s",
shard, c.timestamp(), window.maxTimestamp(), c.pane()));
if (outputFile.filename != null) {
LOG.info("Beginning write to '%s'", outputFile.filename);
int n = 0;
try (OutputStream output =
Channels.newOutputStream(
openWritableGcsFile(options, outputFile.filename))) {
for (Event event : c.element().getValue()) {
Event.CODER.encode(event, output, Coder.Context.OUTER);
writtenRecordsCounter.inc();
if (++n % 10000 == 0) {
LOG.info("So far written %d records to '%s'", n, outputFile.filename);
}
}
}
LOG.info("Written all %d records to '%s'", n, outputFile.filename);
}
savedFileCounter.inc();
c.output(KV.of(null, outputFile));
}
}))
// Clear fancy triggering from above.
.apply(
name + ".WindowLogFiles",
Window.<KV<Void, OutputFile>>into(
FixedWindows.of(Duration.standardSeconds(configuration.windowSizeSec)))
.triggering(AfterWatermark.pastEndOfWindow())
// We expect no late data here, but we'll assume the worst so we can detect any.
.withAllowedLateness(Duration.standardDays(1))
.discardingFiredPanes())
// this GroupByKey allows to have one file per window
.apply(name + ".GroupByKey2", GroupByKey.create())
.apply(
name + ".Index",
ParDo.of(
new DoFn<KV<Void, Iterable<OutputFile>>, Done>() {
private final Counter unexpectedLateCounter =
Metrics.counter(name, "ERROR_unexpectedLate");
private final Counter unexpectedEarlyCounter =
Metrics.counter(name, "ERROR_unexpectedEarly");
private final Counter unexpectedIndexCounter =
Metrics.counter(name, "ERROR_unexpectedIndex");
private final Counter finalizedCounter = Metrics.counter(name, "indexed");
@ProcessElement
public void processElement(ProcessContext c, BoundedWindow window)
throws IOException {
if (c.pane().getTiming() == Timing.LATE) {
unexpectedLateCounter.inc();
LOG.error("ERROR! Unexpected LATE pane: %s", c.pane());
} else if (c.pane().getTiming() == Timing.EARLY) {
unexpectedEarlyCounter.inc();
LOG.error("ERROR! Unexpected EARLY pane: %s", c.pane());
} else if (c.pane().getTiming() == Timing.ON_TIME && c.pane().getIndex() != 0) {
unexpectedIndexCounter.inc();
LOG.error("ERROR! Unexpected ON_TIME pane index: %s", c.pane());
} else {
GcsOptions options = c.getPipelineOptions().as(GcsOptions.class);
LOG.info(
"Index with record timestamp %s, window timestamp %s, pane %s",
c.timestamp(), window.maxTimestamp(), c.pane());
@Nullable String filename = indexPathFor(window);
if (filename != null) {
LOG.info("Beginning write to '%s'", filename);
int n = 0;
try (OutputStream output =
Channels.newOutputStream(openWritableGcsFile(options, filename))) {
for (OutputFile outputFile : c.element().getValue()) {
output.write(outputFile.toString().getBytes(StandardCharsets.UTF_8));
n++;
}
}
LOG.info("Written all %d lines to '%s'", n, filename);
}
c.output(new Done("written for timestamp " + window.maxTimestamp()));
finalizedCounter.inc();
}
}
}));
}
}
| apache-2.0 |
hectorlarios/turtle-blog | src/com/csc/web/data/PostData.java | 4103 | package com.csc.web.data;
import java.sql.Timestamp;
import com.csc.web.utils.DateUtil;
import com.csc.web.data.AbstractData;
/**
* @author Hector
* @date Jul 27, 2011
*/
//
public class PostData extends AbstractData
{
//-------------------------
//booleans
//-------------------------
public Boolean blogUpdated = false;
public Boolean dateUpdated = false;
public Boolean titleUpdated = false;
public Boolean publishedUpdated = false;
//-------------------------
//numbers
//-------------------------
public int commentCount = 0;
//-------------------------
//strings
//-------------------------
final private String TRUE = "true";
//****************************************************************************************************
//Begin - Constructor
//****************************************************************************************************
public PostData(){}
//****************************************************************************************************
//End - Constructor
//****************************************************************************************************
//****************************************************************************************************
//Begin - Get/Set Methods
//****************************************************************************************************
private String _blog;
public String getBlog() {return _blog;}
public void setBlog(String value) {setBlog(value,false);}
public void setBlog(String value, Boolean isUpdate)
{
blogUpdated = valueUpdated(_blog, value, isUpdate);;
_blog = value;
}
protected Timestamp _date;
public Timestamp getDate(){return _date;}
public void setDate(Timestamp value)
{
setDate(value, false);
}
public void setDate(String value)
{
setDate(value, false);
}
public void setDate(String value,Boolean isUpdate)
{
Timestamp _newDate = DateUtil.getSqlTimestampFromShortDate(value);
setDate(_newDate, isUpdate);
}
public void setDate(Timestamp value,Boolean isUpdate)
{
String _oldValue = DateUtil.getShortDate(_date);
String _newValue = DateUtil.getShortDate(value);
dateUpdated = valueUpdated(_oldValue, _newValue, isUpdate);
if(!isUpdate||(isUpdate&&dateUpdated))_date = value;
}
protected String _title;
public String getTitle() {return _title;}
public void setTitle(String value){setTitle(value, false);}
public void setTitle(String value, Boolean isUpdate)
{
titleUpdated = valueUpdated(_title, value, isUpdate);
_title = value;
}
protected Boolean _published = false;
public Boolean getPublished() {return _published;}
public void setPublished(String value){setPublished(value, false);}
public void setPublished(String value, Boolean isUpdate)
{
Boolean _value = TRUE.equals(value);
setPublished(_value,isUpdate);
}
public void setPublished(Boolean value){setPublished(value, false);}
public void setPublished(Boolean value, Boolean isUpdate)
{
String _oldValue = _published.toString();
String _newValue = value.toString();
publishedUpdated = valueUpdated(_oldValue, _newValue, isUpdate);
_published = value;
}
public String getDateString()
{
String _value = DateUtil.getShortDate(_date);
return _value;
}
public String getYear()
{
String _value = DateUtil.getYear(_date);
return _value;
}
public String getMonthName()
{
String _value = DateUtil.getMonthName(_date);
return _value;
}
public String getDay()
{
String _value = DateUtil.getDay(_date);
return _value;
}
public String getDayName()
{
String _value = DateUtil.getDayName(_date);
return _value;
}
//****************************************************************************************************
//End - Get/Set Methods
//****************************************************************************************************
}
| apache-2.0 |
IAAS/BPEL-splitting | src/org.bpel4chor.splitProcess.test/src/org/bpel4chor/splitprocess/test/utils/NameGeneratorTest.java | 6089 | package org.bpel4chor.splitprocess.test.utils;
import static org.junit.Assert.*;
import java.io.File;
import java.util.Set;
import org.bpel4chor.splitprocess.utils.NameGenerator;
import org.bpel4chor.utils.BPEL4ChorReader;
import org.eclipse.bpel.model.BPELPlugin;
import org.eclipse.bpel.model.Process;
import org.eclipse.bpel.model.resource.BPELResourceFactoryImpl;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.wst.wsdl.Definition;
import org.eclipse.wst.wsdl.internal.util.WSDLResourceFactoryImpl;
import org.eclipse.xsd.util.XSDResourceFactoryImpl;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import de.uni_stuttgart.iaas.bpel.model.utilities.MyWSDLUtil;
public class NameGeneratorTest {
static File testFileDir = null;
static NameGenerator ng = null;
static Process process = null;
static Definition defn = null;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
File projectDir = new File("");
testFileDir = new File(projectDir.getAbsolutePath(), "files");
// init
BPELPlugin bpelPlugin = new BPELPlugin();
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("bpel", new BPELResourceFactoryImpl());
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("wsdl", new WSDLResourceFactoryImpl());
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("xsd", new XSDResourceFactoryImpl());
// load bpel resource
ResourceSet resourceSet = new ResourceSetImpl();
URI uri = URI.createFileURI(testFileDir.getAbsolutePath() + "\\OrderInfo\\bpelContent\\OrderingProcess.bpel");
Resource resource = resourceSet.getResource(uri, true);
process = (Process) resource.getContents().get(0);
defn = MyWSDLUtil.readWSDL(testFileDir.getAbsolutePath()
+ "\\OrderInfo\\bpelContent\\OrderingProcess.wsdl");
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
testFileDir = null;
ng = null;
process = null;
defn = null;
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testNameGeneratorProcess() {
try {
NameGenerator myNG = new NameGenerator(process);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void testNameGeneratorDefinition() {
try {
NameGenerator myNG = new NameGenerator(defn);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Test
public void testInitExistedVariableNames() {
MyNameGenerator myNG = new MyNameGenerator(process);
Set<String> variableNames = myNG.getExistedVariablesNames();
assertNotNull(variableNames);
assertEquals(true, variableNames.size()==5);
assertEquals(true, variableNames.contains("processOrderPLRequest"));
}
@Test
public void testInitExistedActivityNames() {
MyNameGenerator myNG = new MyNameGenerator(process);
Set<String> actNames = myNG.getExistedActivityNames();
assertNotNull(actNames);
assertEquals(true, actNames.size()==9);
assertEquals(true, actNames.contains("D"));
}
@Test
public void testInitExistedPortTypeNames() {
MyNameGenerator myNG = new MyNameGenerator(defn);
Set<String> ptNames = myNG.getExistedPortTypeNames();
assertNotNull(ptNames);
assertEquals(true, ptNames.size()==1);
assertEquals(true, ptNames.contains("OrderingProcess"));
}
@Test
public void testInitExistedOperationNames() {
MyNameGenerator ng = new MyNameGenerator(defn);
Set<String> opNames = ng.getExistedOperationNames();
assertNotNull(opNames);
assertEquals(true, opNames.size()==1);
assertEquals(true, opNames.contains("order"));
}
@Test
public void testGetUniqueVariableName() {
NameGenerator ng = new NameGenerator(process);
String sugguest = "orderInfo";
String uniqueName = ng.getUniqueVariableName(sugguest);
assertNotNull(uniqueName);
assertEquals(false, uniqueName.isEmpty());
assertEquals(false, uniqueName.equals(sugguest));
}
@Test
public void testGetUniqueActivityName() {
NameGenerator ng = new NameGenerator(process);
String sugguest = "MyNameIsUnique";
String uniqueName = ng.getUniqueActivityName(sugguest);
assertNotNull(uniqueName);
assertEquals(true, uniqueName.equals(sugguest));
sugguest = "H";
uniqueName = ng.getUniqueActivityName(sugguest);
assertEquals(false, uniqueName.equals(sugguest));
}
@Test
public void testGetUniquePortTypeName() {
NameGenerator ng = new NameGenerator(defn);
String sugguest = "OrderingProcess";
String uniqueName = ng.getUniquePortTypeName(sugguest);
assertNotNull(uniqueName);
assertEquals(false, uniqueName.isEmpty());
assertEquals(false, uniqueName.equals(sugguest));
}
@Test
public void testGetUniqueOperationName() {
NameGenerator ng = new NameGenerator(defn);
String sugguest = "order";
String uniqueName = ng.getUniqueOperationName(sugguest);
assertNotNull(uniqueName);
assertEquals(false, uniqueName.isEmpty());
assertEquals(false, uniqueName.equals(sugguest));
}
@Test
public void testGetUniqueRoleName() {
NameGenerator ng = new NameGenerator(defn);
String sugguest = "OrderProcessCallback";
String uniqueName = ng.getUniqueRoleName(sugguest);
assertNotNull(uniqueName);
assertEquals(false, uniqueName.isEmpty());
assertEquals(false, uniqueName.equals(sugguest));
}
}
class MyNameGenerator extends NameGenerator {
public MyNameGenerator(Process process) {
super(process);
}
public MyNameGenerator(Definition defn) {
super(defn);
}
public Set<String> getExistedVariablesNames() {
return super.existedVariableNames;
}
public Set<String> getExistedOperationNames() {
return super.existedOperationNames;
}
public Set<String> getExistedPortTypeNames() {
return super.existedPortTypeNames;
}
public Set<String> getExistedActivityNames() {
return super.existedActivityNames;
}
}
| apache-2.0 |
shahankhatch/ScalableGraphSummaries | SGBHadoop/src/main/java/edu/toronto/cs/sgbhadoop/hadoop220/SplitKeyValueInputFormat.java | 1176 | package edu.toronto.cs.sgbhadoop.hadoop220;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import com.google.common.base.Charsets;
public class SplitKeyValueInputFormat extends TextInputFormat {
@Override
public RecordReader<LongWritable, Text> createRecordReader(InputSplit split, TaskAttemptContext context) {
FileSplit fileSplit = (FileSplit) split;
String fileName = fileSplit.getPath().toString();
String taskName = context.getTaskAttemptID().toString();
System.out.println("Handling [Taskname,Filename]:[" + taskName + "," + fileName + "]");
String delimiter = context.getConfiguration().get("textinputformat.record.delimiter");
byte[] recordDelimiterBytes = null;
if (null != delimiter)
recordDelimiterBytes = delimiter.getBytes(Charsets.UTF_8);
return new SplitKeyValueRecordReader(recordDelimiterBytes);
}
}
| apache-2.0 |
shankar-reddy/eVillage | src/main/java/com/itreddys/evillage/util/Adaptor.java | 72 | package com.itreddys.evillage.util;
public interface Adaptor {
}
| apache-2.0 |
wburns/radargun | core/src/main/java/org/radargun/stages/cache/stresstest/FixedSetSharedOperationLogic.java | 3583 | package org.radargun.stages.cache.stresstest;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicLong;
import org.radargun.stages.cache.generators.KeyGenerator;
import org.radargun.logging.Log;
import org.radargun.logging.LogFactory;
import org.radargun.traits.BasicOperations;
/**
* All threads execute the operations on shared set of keys.
* Therefore, locking conflicts can happen in the underlying cache.
*
* @author Radim Vansa <rvansa@redhat.com>
*/
class FixedSetSharedOperationLogic extends FixedSetOperationLogic {
private static Log log = LogFactory.getLog(StressTestStage.class);
private ArrayList<Object> sharedKeys;
private AtomicLong keysLoaded = new AtomicLong(0);
public FixedSetSharedOperationLogic(StressTestStage stage, ArrayList<Object> sharedKeys) {
super(stage);
this.sharedKeys = sharedKeys;
}
@Override
public Object getKey(int keyId, int threadIndex) {
if (stage.poolKeys) {
return sharedKeys.get(keyId);
} else {
return stage.keyGenerator.generateKey(keyId);
}
}
@Override
public void init(int threadIndex, int nodeIndex, int numNodes) {
if (stage.poolKeys) {
synchronized (sharedKeys) {
// no point in doing this in parallel, too much overhead in synchronization
if (threadIndex == 0) {
if (sharedKeys.size() != stage.numEntries) {
sharedKeys.clear();
KeyGenerator keyGenerator = stage.getKeyGenerator();
for (int keyIndex = 0; keyIndex < stage.numEntries; ++keyIndex) {
sharedKeys.add(keyGenerator.generateKey(keyIndex));
}
}
sharedKeys.notifyAll();
} else {
while (sharedKeys.size() != stage.numEntries) {
try {
sharedKeys.wait();
} catch (InterruptedException e) {
}
}
}
}
}
int loadedEntryCount, keyIndex, loadingThreads;
if (stage.loadAllKeys) {
loadedEntryCount = stage.numEntries;
loadingThreads = stage.numThreads;
keyIndex = threadIndex;
} else {
loadedEntryCount = stage.numEntries / numNodes + (nodeIndex < stage.numEntries % numNodes ? 1 : 0);
loadingThreads = stage.numThreads * numNodes;
keyIndex = threadIndex + nodeIndex * stage.numThreads;
}
if (threadIndex == 0) {
log.info(String.format("We have loaded %d keys, expecting %d locally loaded",
keysLoaded.get(), loadedEntryCount));
}
if (keysLoaded.get() >= loadedEntryCount) {
return;
}
BasicOperations.Cache cache = stage.basicOperations.getCache(stage.bucketPolicy.getBucketName(threadIndex));
for (; keyIndex < stage.numEntries; keyIndex += loadingThreads) {
try {
Object key = getKey(keyIndex, threadIndex);
cache.put(key, stage.generateValue(key, Integer.MAX_VALUE));
long loaded = keysLoaded.incrementAndGet();
if (loaded % 100000 == 0) {
Runtime runtime = Runtime.getRuntime();
log.info(String.format("Loaded %d/%d entries (on this node), free %d MB/%d MB",
loaded, loadedEntryCount, runtime.freeMemory() / 1048576, runtime.maxMemory() / 1048576));
}
} catch (Exception e) {
log.error("Failed to insert shared key " + keyIndex, e);
}
}
}
}
| apache-2.0 |
tokee/lucene | src/java/org/apache/lucene/util/English.java | 4816 | package org.apache.lucene.util;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* <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.
*/
/**
* @lucene.internal
*/
public class English {
public static String longToEnglish(long i) {
StringBuilder result = new StringBuilder();
longToEnglish(i, result);
return result.toString();
}
public static void longToEnglish(long i, StringBuilder result) {
if (i == 0) {
result.append("zero");
return;
}
if (i < 0) {
result.append("minus ");
i = -i;
}
if (i >= 1000000000000000000l) { // quadrillion
longToEnglish(i / 1000000000000000000l, result);
result.append("quintillion, ");
i = i % 1000000000000000000l;
}
if (i >= 1000000000000000l) { // quadrillion
longToEnglish(i / 1000000000000000l, result);
result.append("quadrillion, ");
i = i % 1000000000000000l;
}
if (i >= 1000000000000l) { // trillions
longToEnglish(i / 1000000000000l, result);
result.append("trillion, ");
i = i % 1000000000000l;
}
if (i >= 1000000000) { // billions
longToEnglish(i / 1000000000, result);
result.append("billion, ");
i = i % 1000000000;
}
if (i >= 1000000) { // millions
longToEnglish(i / 1000000, result);
result.append("million, ");
i = i % 1000000;
}
if (i >= 1000) { // thousands
longToEnglish(i / 1000, result);
result.append("thousand, ");
i = i % 1000;
}
if (i >= 100) { // hundreds
longToEnglish(i / 100, result);
result.append("hundred ");
i = i % 100;
}
//we know we are smaller here so we can cast
if (i >= 20) {
switch (((int) i) / 10) {
case 9:
result.append("ninety");
break;
case 8:
result.append("eighty");
break;
case 7:
result.append("seventy");
break;
case 6:
result.append("sixty");
break;
case 5:
result.append("fifty");
break;
case 4:
result.append("forty");
break;
case 3:
result.append("thirty");
break;
case 2:
result.append("twenty");
break;
}
i = i % 10;
if (i == 0)
result.append(" ");
else
result.append("-");
}
switch ((int) i) {
case 19:
result.append("nineteen ");
break;
case 18:
result.append("eighteen ");
break;
case 17:
result.append("seventeen ");
break;
case 16:
result.append("sixteen ");
break;
case 15:
result.append("fifteen ");
break;
case 14:
result.append("fourteen ");
break;
case 13:
result.append("thirteen ");
break;
case 12:
result.append("twelve ");
break;
case 11:
result.append("eleven ");
break;
case 10:
result.append("ten ");
break;
case 9:
result.append("nine ");
break;
case 8:
result.append("eight ");
break;
case 7:
result.append("seven ");
break;
case 6:
result.append("six ");
break;
case 5:
result.append("five ");
break;
case 4:
result.append("four ");
break;
case 3:
result.append("three ");
break;
case 2:
result.append("two ");
break;
case 1:
result.append("one ");
break;
case 0:
result.append("");
break;
}
}
public static String intToEnglish(int i) {
StringBuilder result = new StringBuilder();
longToEnglish(i, result);
return result.toString();
}
public static void intToEnglish(int i, StringBuilder result) {
longToEnglish(i, result);
}
public static void main(String[] args) {
System.out.println(longToEnglish(Long.parseLong(args[0])));
}
}
| apache-2.0 |
timothymiko/narrate-android | app/src/main/java/com/datonicgroup/narrate/app/models/comparators/EntryAlphabetComparator.java | 332 | package com.datonicgroup.narrate.app.models.comparators;
import com.datonicgroup.narrate.app.models.Entry;
/**
* Created by timothymiko on 12/28/14.
*/
public class EntryAlphabetComparator extends BaseEntryComparator {
@Override
public int compare(Entry lhs, Entry rhs) {
return cp(lhs.title, rhs.title);
}
} | apache-2.0 |
springer63/hibatis | src/main/java/com/yaoa/hibatis/serializer/StringSerializer.java | 502 | /*
* Copyright 2015-2016 Yaoa & Co., Ltd.
*/
package com.yaoa.hibatis.serializer;
import java.nio.charset.Charset;
/**
*
*
* @author kingsy.lin
* @version 1.0 , 2016年10月28日
*/
@SuppressWarnings("unchecked")
public class StringSerializer<T> implements Serializer<T> {
private Charset charset = Charset.forName("utf-8");
public byte[] serialize(T t) {
return t.toString().getBytes(charset);
}
public T deserialize(byte[] bytes) {
return (T)new String(bytes, charset);
}
} | apache-2.0 |
SmartDeveloperHub/sdh-ci-harvester | backend/core/src/main/java/org/smartdeveloperhub/harvesters/ci/backend/jpa/CriteriaHelper.java | 3513 | /**
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* This file is part of the Smart Developer Hub Project:
* http://www.smartdeveloperhub.org/
*
* Center for Open Middleware
* http://www.centeropenmiddleware.com/
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* Copyright (C) 2015-2016 Center for Open Middleware.
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* 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.
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
* Artifact : org.smartdeveloperhub.harvesters.ci.backend:ci-backend-core:0.3.0
* Bundle : ci-backend-core-0.3.0.jar
* #-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=#
*/
package org.smartdeveloperhub.harvesters.ci.backend.jpa;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.ParameterExpression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
final class CriteriaHelper<E> {
private final EntityManager entityManager;
private final CriteriaBuilder cb;
private final Root<?> entity;
private final List<Predicate> criteria;
private final Map<String,Object> arguments;
private final CriteriaQuery<E> query;
CriteriaHelper(final EntityManager entityManager, final CriteriaQuery<E> query, final Root<?> entity) {
this.entityManager = entityManager;
this.cb = entityManager.getCriteriaBuilder();
this.query = query;
this.entity = entity;
this.criteria=Lists.newArrayList();
this.arguments=Maps.newLinkedHashMap();
}
private EntityManager entityManager() {
return this.entityManager;
}
public <T> void registerCriteria(final String parameterName, final String fieldName, final T argument) {
if(argument!=null) {
@SuppressWarnings("unchecked")
final ParameterExpression<? extends T> p=this.cb.parameter((Class<? extends T>)argument.getClass(), parameterName);
this.criteria.add(this.cb.equal(this.entity.get(fieldName),p));
this.arguments.put(parameterName, argument);
}
}
private void updateCriteria() {
if (this.criteria.isEmpty()) {
// Nothing to do
} else if (this.criteria.size() == 1) {
this.query.where(this.criteria.get(0));
} else {
this.query.where(this.cb.and(this.criteria.toArray(new Predicate[this.criteria.size()])));
}
}
public TypedQuery<E> getQuery() {
updateCriteria();
final TypedQuery<E> result=entityManager().createQuery(this.query);
for(final Entry<String,Object> entry:this.arguments.entrySet()) {
result.setParameter(entry.getKey(),entry.getValue());
}
return result;
}
} | apache-2.0 |
YoungDigitalPlanet/empiria.player | src/test/gwt/eu/ydp/empiria/player/client/controller/report/table/modification/ItemIndexToLinkTagsAppenderGWTTestCase.java | 2438 | /*
* Copyright 2017 Young Digital Planet S.A.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.ydp.empiria.player.client.controller.report.table.modification;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.XMLParser;
import eu.ydp.empiria.player.client.EmpiriaPlayerGWTTestCase;
public class ItemIndexToLinkTagsAppenderGWTTestCase extends EmpiriaPlayerGWTTestCase {
private ItemIndexAppender testObj;
//@formatter:off
private final String INPUT = "" +
"<rd>" +
"<div class=\"emp_content_icon\">" +
"<link itemIndex=\"1\">" +
"<info class=\"info_content_title\"/>" +
"</link>" +
"<link>" +
"<info class=\"info_content_title\"/>" +
"</link>" +
"<link url=\"adres\">" +
"<info class=\"info_content_title\"/>" +
"</link>" +
"</div>" +
"</rd>";
private final String OUTPUT = "" +
"<rd>" +
"<div class=\"emp_content_icon\">" +
"<link itemIndex=\"1\">" +
"<info class=\"info_content_title\"/>" +
"</link>" +
"<link itemIndex=\"2\">" +
"<info class=\"info_content_title\"/>" +
"</link>" +
"<link url=\"adres\">" +
"<info class=\"info_content_title\"/>" +
"</link>" +
"</div>" +
"</rd>";
private Element cellElement;
//@formatter:on
@Override
protected void gwtSetUp() {
testObj = new ItemIndexAppender();
}
public void testAppendToLinkTags() {
// given
int ITEM_INDEX = 2;
cellElement = XMLParser.parse(INPUT).getDocumentElement();
// when
testObj.appendToLinkTags(ITEM_INDEX, cellElement);
// then
assertEquals(cellElement.toString(), OUTPUT);
}
}
| apache-2.0 |
wanggc/mongo-java-driver | src/test/com/mongodb/MongoClientTest.java | 7011 | /**
* Copyright (c) 2008 - 2012 10gen, Inc. <http://10gen.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.mongodb;
import junit.framework.Assert;
import org.junit.Test;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
public class MongoClientTest {
@Test
@SuppressWarnings("deprecation")
public void testConstructors() throws UnknownHostException {
MongoClientOptions customClientOptions = new MongoClientOptions.Builder().connectionsPerHost(500).build();
MongoOptions customOptions = new MongoOptions(customClientOptions);
MongoOptions defaultOptions = new MongoOptions(new MongoClientOptions.Builder().build());
List<MongoCredential> emptyCredentials = Arrays.asList();
MongoClient mc;
mc = new MongoClient();
Assert.assertEquals(new ServerAddress(), mc.getAddress());
Assert.assertEquals(defaultOptions, mc.getMongoOptions());
Assert.assertEquals(emptyCredentials, mc.getCredentialsList());
Assert.assertEquals(MongoClientOptions.builder().build(), mc.getMongoClientOptions());
mc.close();
mc = new MongoClient("127.0.0.1");
Assert.assertEquals(new ServerAddress("127.0.0.1"), mc.getAddress());
Assert.assertEquals(defaultOptions, mc.getMongoOptions());
Assert.assertEquals(emptyCredentials, mc.getCredentialsList());
Assert.assertEquals(MongoClientOptions.builder().build(), mc.getMongoClientOptions());
mc.close();
mc = new MongoClient("127.0.0.1", customClientOptions);
Assert.assertEquals(new ServerAddress("127.0.0.1"), mc.getAddress());
Assert.assertEquals(customOptions, mc.getMongoOptions());
Assert.assertEquals(emptyCredentials, mc.getCredentialsList());
Assert.assertEquals(customClientOptions, mc.getMongoClientOptions());
mc.close();
mc = new MongoClient("127.0.0.1", 27017);
Assert.assertEquals(new ServerAddress("127.0.0.1", 27017), mc.getAddress());
Assert.assertEquals(defaultOptions, mc.getMongoOptions());
Assert.assertEquals(emptyCredentials, mc.getCredentialsList());
Assert.assertEquals(MongoClientOptions.builder().build(), mc.getMongoClientOptions());
mc.close();
mc = new MongoClient(new ServerAddress("127.0.0.1"));
Assert.assertEquals(new ServerAddress("127.0.0.1"), mc.getAddress());
Assert.assertEquals(defaultOptions, mc.getMongoOptions());
Assert.assertEquals(emptyCredentials, mc.getCredentialsList());
Assert.assertEquals(MongoClientOptions.builder().build(), mc.getMongoClientOptions());
mc.close();
final List<MongoCredential> credentialsList = Arrays.asList(
MongoCredential.createMongoCRCredential("user1", "test", "pwd".toCharArray()));
mc = new MongoClient(new ServerAddress("127.0.0.1"), credentialsList);
Assert.assertEquals(new ServerAddress("127.0.0.1"), mc.getAddress());
Assert.assertEquals(defaultOptions, mc.getMongoOptions());
Assert.assertEquals(credentialsList, mc.getCredentialsList());
Assert.assertEquals(MongoClientOptions.builder().build(), mc.getMongoClientOptions());
mc.close();
mc = new MongoClient(new ServerAddress("127.0.0.1"), customClientOptions);
Assert.assertEquals(new ServerAddress("127.0.0.1"), mc.getAddress());
Assert.assertEquals(customOptions, mc.getMongoOptions());
Assert.assertEquals(emptyCredentials, mc.getCredentialsList());
Assert.assertEquals(customClientOptions, mc.getMongoClientOptions());
mc.close();
mc = new MongoClient(new ServerAddress("127.0.0.1"), credentialsList, customClientOptions);
Assert.assertEquals(new ServerAddress("127.0.0.1"), mc.getAddress());
Assert.assertEquals(customOptions, mc.getMongoOptions());
Assert.assertEquals(credentialsList, mc.getCredentialsList());
Assert.assertEquals(customClientOptions, mc.getMongoClientOptions());
mc.close();
mc = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017), new ServerAddress("127.0.0.1", 27018)));
Assert.assertEquals(Arrays.asList(new ServerAddress("localhost", 27017), new ServerAddress("127.0.0.1", 27018)), mc.getAllAddress());
Assert.assertEquals(defaultOptions, mc.getMongoOptions());
Assert.assertEquals(emptyCredentials, mc.getCredentialsList());
Assert.assertEquals(MongoClientOptions.builder().build(), mc.getMongoClientOptions());
mc.close();
mc = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017), new ServerAddress("127.0.0.1", 27018)), customClientOptions);
Assert.assertEquals(Arrays.asList(new ServerAddress("localhost", 27017), new ServerAddress("127.0.0.1", 27018)), mc.getAllAddress());
Assert.assertEquals(customOptions, mc.getMongoOptions());
Assert.assertEquals(emptyCredentials, mc.getCredentialsList());
Assert.assertEquals(customClientOptions, mc.getMongoClientOptions());
mc.close();
mc = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017), new ServerAddress("127.0.0.1", 27018)), credentialsList, customClientOptions);
Assert.assertEquals(Arrays.asList(new ServerAddress("localhost", 27017), new ServerAddress("127.0.0.1", 27018)), mc.getAllAddress());
Assert.assertEquals(customOptions, mc.getMongoOptions());
Assert.assertEquals(credentialsList, mc.getCredentialsList());
Assert.assertEquals(customClientOptions, mc.getMongoClientOptions());
mc.close();
mc = new MongoClient(new MongoClientURI("mongodb://127.0.0.1"));
Assert.assertEquals(new ServerAddress("127.0.0.1"), mc.getAddress());
Assert.assertEquals(defaultOptions, mc.getMongoOptions());
Assert.assertEquals(emptyCredentials, mc.getCredentialsList());
Assert.assertEquals(MongoClientOptions.builder().build(), mc.getMongoClientOptions());
mc.close();
mc = new MongoClient(new MongoClientURI("mongodb://user1:pwd@127.0.0.1/test?maxPoolSize=500"));
Assert.assertEquals(new ServerAddress("127.0.0.1"), mc.getAddress());
Assert.assertEquals(customOptions, mc.getMongoOptions());
Assert.assertEquals(credentialsList, mc.getCredentialsList());
Assert.assertEquals(customClientOptions, mc.getMongoClientOptions());
mc.close();
}
}
| apache-2.0 |
jjeb/kettle-trunk | plugins/kettle-palo-plugin/src/org/pentaho/di/ui/job/entries/palo/JobEntryCubeCreate/PaloCubeCreateDialog.java | 12178 | /*
* This file is part of PaloKettlePlugin.
*
* PaloKettlePlugin 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.
*
* PaloKettlePlugin 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 PaloKettlePlugin. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2011 De Bortoli Wines Pty Limited (Australia)
*/
package org.pentaho.di.ui.job.entries.palo.JobEntryCubeCreate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.logging.DefaultLogLevel;
import org.pentaho.di.palo.core.PaloHelper;
import org.pentaho.di.palo.core.PaloNameComparator;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entries.palo.JobEntryCubeCreate.PaloCubeCreate;
import org.pentaho.di.job.entry.JobEntryDialogInterface;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.gui.WindowProperty;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.job.dialog.JobDialog;
import org.pentaho.di.ui.job.entry.JobEntryDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
/**
* This dialog allows you to define the palo cube you want to create
*
* @author Pieter van der Merwe
* @since 03-08-2011
*/
public class PaloCubeCreateDialog extends JobEntryDialog implements JobEntryDialogInterface
{
private static Class<?> PKG = PaloCubeCreate.class;
private Text textStepName;
private Label labelStepName;
private CCombo addConnectionLine;
private Label labelCubeName;
private Text textCubeName;
private ColumnInfo[] colinf;
private TableView tableViewFields;
private Button wOK, wCancel;
private Listener lsOK, lsCancel;
private PaloCubeCreate jobEntry;
private Shell shell;
private PropsUI props;
private ColumnInfo comboDropDown;
private SelectionAdapter lsDef;
private boolean changed;
private JobMeta jobMeta;
public PaloCubeCreateDialog(Shell parent, JobEntryInterface jobEntryInt, Repository rep, JobMeta jobMeta)
{
super(parent, jobEntryInt, rep, jobMeta);
props=PropsUI.getInstance();
this.jobEntry=(PaloCubeCreate) jobEntryInt;
if (this.jobEntry.getName() == null) this.jobEntry.setName(jobEntryInt.getName());
this.jobMeta = jobMeta;
}
public JobEntryInterface open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN);
props.setLook(shell);
JobDialog.setShellImage(shell, jobEntry);
ModifyListener lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
jobEntry.setChanged();
}
};
changed = jobEntry.hasChanged();
FormLayout formLayout = new FormLayout ();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(BaseMessages.getString(PKG,"PaloCubeCreateDialog.PaloCubeCreate")); //$NON-NLS-1$
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Stepname line
labelStepName=new Label(shell, SWT.RIGHT);
labelStepName.setText(BaseMessages.getString(PKG,"PaloCubeCreateDialog.StepName")); //$NON-NLS-1$
props.setLook( labelStepName );
FormData fd = new FormData();
fd.left = new FormAttachment(0, 0);
fd.right= new FormAttachment(middle, -margin);
fd.top = new FormAttachment(0, margin);
labelStepName.setLayoutData(fd);
textStepName=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
textStepName.setText(jobEntry.getName());
props.setLook( textStepName );
textStepName.addModifyListener(lsMod);
fd=new FormData();
fd.left = new FormAttachment(middle, 0);
fd.top = new FormAttachment(0, margin);
fd.right= new FormAttachment(100, 0);
textStepName.setLayoutData(fd);
addConnectionLine = addConnectionLine(shell, textStepName, Const.MIDDLE_PCT, margin);
addConnectionLine.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
doSelectConnection(false);
}
});
props.setLook(addConnectionLine);
// Get cube name to delete
labelCubeName = new Label(shell, SWT.RIGHT);
labelCubeName.setText(BaseMessages.getString(PKG,"PaloCubeCreateDialog.CubeName")); //$NON-NLS-1$
props.setLook(labelCubeName);
fd = new FormData();
fd.left = new FormAttachment(0, 0);
fd.right= new FormAttachment(middle, -margin);
fd.top = new FormAttachment(addConnectionLine, margin);
labelCubeName.setLayoutData(fd);
textCubeName=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
textCubeName.addModifyListener(lsMod);
props.setLook(textCubeName);
fd = new FormData();
fd.left = new FormAttachment(middle, 0);
fd.right= new FormAttachment(100, 0);
fd.top = new FormAttachment(addConnectionLine, margin);
textCubeName.setLayoutData(fd);
colinf=new ColumnInfo[] {
new ColumnInfo(getLocalizedColumn(0), ColumnInfo.COLUMN_TYPE_CCOMBO, new String[] {}, false)
};
tableViewFields = new TableView(null, shell,
SWT.NONE | SWT.BORDER,
colinf,
10, true,
lsMod,
props
);
tableViewFields.setSize(477, 105);
tableViewFields.setBounds(5, 250, 477, 105);
tableViewFields.setReadonly(false);
tableViewFields.table.removeAll();
tableViewFields.optWidth(true);
fd=new FormData();
fd.left = new FormAttachment(0, margin);
fd.top = new FormAttachment(textCubeName, 3*margin);
fd.right = new FormAttachment(100, 0);
fd.bottom= new FormAttachment(100, -50);
tableViewFields.setLayoutData(fd);
tableViewFields.table.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent arg0) {
}
public void focusGained(FocusEvent arg0) {
doBuildDimensionList();
}
});
props.setLook(tableViewFields);
// Some buttons
wOK=new Button(shell, SWT.PUSH);
wOK.setText(BaseMessages.getString(PKG,"System.Button.OK")); //$NON-NLS-1$
wCancel=new Button(shell, SWT.PUSH);
wCancel.setText(BaseMessages.getString(PKG,"System.Button.Cancel")); //$NON-NLS-1$
BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wCancel}, margin, tableViewFields);
// Add listeners
lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } };
lsOK = new Listener() { public void handleEvent(Event e) { ok(); } };
wCancel.addListener(SWT.Selection, lsCancel);
wOK.addListener (SWT.Selection, lsOK );
lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } };
textStepName.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } );
getData();
BaseStepDialog.setSize(shell);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch()) display.sleep();
}
return jobEntry;
}
private String getLocalizedColumn(int columnIndex) {
switch(columnIndex) {
case 0:
return BaseMessages.getString(PKG,"PaloCellCreateDialog.ColumnDimension");
default:
return "";
}
}
public void dispose()
{
WindowProperty winprop = new WindowProperty(shell);
props.setScreen(winprop);
shell.dispose();
}
private void doBuildDimensionList() {
if(comboDropDown == null && addConnectionLine.getText() != null) {
DatabaseMeta dbMeta = DatabaseMeta.findDatabase(jobMeta.getDatabases(), addConnectionLine.getText());
if (dbMeta != null) {
PaloHelper helper = new PaloHelper(dbMeta, DefaultLogLevel.getLogLevel());
try{
helper.connect();
List<String> dimensionNames = helper.getDimensionsNames();
List <String> dimensions = helper.getDimensionsNames();
Collections.sort(dimensions, new PaloNameComparator());
comboDropDown = new ColumnInfo("Field", ColumnInfo.COLUMN_TYPE_CCOMBO, dimensions.toArray(new String[dimensionNames.size()]), true);
tableViewFields.setColumnInfo(0, comboDropDown);
}
catch (Exception ex) {
new ErrorDialog(shell, BaseMessages.getString(PKG,"PaloCellOutputDialog.RetreiveCubesErrorTitle") , BaseMessages.getString(PKG,"PaloCellOutputDialog.RetreiveCubesError") , ex);
}
finally
{
helper.disconnect();
}
}
}
}
private void doSelectConnection(boolean clearCurrentData ) {
comboDropDown = null;
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
if (jobEntry.getName() != null)
textStepName.setText( jobEntry.getName() );
textStepName.selectAll();
int index = addConnectionLine.indexOf(jobEntry.getDatabaseMeta() != null ? jobEntry.getDatabaseMeta().getName() : "");
if (index >=0)
addConnectionLine.select(index);
if (jobEntry.getCubeName() != null)
textCubeName.setText(jobEntry.getCubeName());
tableViewFields.table.removeAll();
if(jobEntry.getDimensionNames() != null
&& jobEntry.getDimensionNames().size() > 0)
for (String dimensionName : jobEntry.getDimensionNames())
tableViewFields.add(dimensionName);
if (tableViewFields.table.getItemCount() == 0)
tableViewFields.add("");
tableViewFields.setRowNums();
}
private void cancel()
{
jobEntry.setChanged(changed);
jobEntry=null;
dispose();
}
private void ok()
{
tableViewFields.removeEmptyRows();
List <String> dimensionNames = new ArrayList<String>();
for (int i = 0; i < tableViewFields.table.getItemCount(); i++)
dimensionNames.add(tableViewFields.table.getItem(i).getText(1));
jobEntry.setName(textStepName.getText());
jobEntry.setDatabaseMeta(DatabaseMeta.findDatabase(jobMeta.getDatabases(), addConnectionLine.getText()));
jobEntry.setCubeName(textCubeName.getText());
jobEntry.setDimensionNames(dimensionNames);
dispose();
}
public String toString()
{
return this.getClass().getName();
}
public boolean evaluates()
{
return true;
}
public boolean isUnconditional()
{
return false;
}
}
| apache-2.0 |
nafae/developer | modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201411/TimeUnit.java | 3362 | /**
* TimeUnit.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.axis.v201411;
public class TimeUnit implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected TimeUnit(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _MINUTE = "MINUTE";
public static final java.lang.String _HOUR = "HOUR";
public static final java.lang.String _DAY = "DAY";
public static final java.lang.String _WEEK = "WEEK";
public static final java.lang.String _MONTH = "MONTH";
public static final java.lang.String _LIFETIME = "LIFETIME";
public static final java.lang.String _POD = "POD";
public static final java.lang.String _STREAM = "STREAM";
public static final TimeUnit MINUTE = new TimeUnit(_MINUTE);
public static final TimeUnit HOUR = new TimeUnit(_HOUR);
public static final TimeUnit DAY = new TimeUnit(_DAY);
public static final TimeUnit WEEK = new TimeUnit(_WEEK);
public static final TimeUnit MONTH = new TimeUnit(_MONTH);
public static final TimeUnit LIFETIME = new TimeUnit(_LIFETIME);
public static final TimeUnit POD = new TimeUnit(_POD);
public static final TimeUnit STREAM = new TimeUnit(_STREAM);
public java.lang.String getValue() { return _value_;}
public static TimeUnit fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
TimeUnit enumeration = (TimeUnit)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static TimeUnit fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(TimeUnit.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "TimeUnit"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
| apache-2.0 |
jkatzer/jkatzer-wave | src/org/waveprotocol/wave/examples/client/console/ConsoleScrollable.java | 2195 | /**
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.waveprotocol.wave.examples.client.console;
import java.util.List;
/**
* Abstract implementation of {@link ConsoleRenderable} that supports scrolling.
*
*
*/
public abstract class ConsoleScrollable implements ConsoleRenderable {
/** Amount scrolled, starting from 0. */
private int scrollLevel = 0;
/**
* Scroll a list of lines based on the value of scrollLevel.
*
* @param height of the scroll window
* @param lines to scroll
* @return list of at most height lines, scrolled based on the value of scrollLevel
*/
public synchronized List<String> scroll(int height, List<String> lines) {
if (scrollLevel > lines.size() - height) {
scrollLevel = Math.max(0, lines.size() - height);
}
return lines.subList(scrollLevel, Math.min(lines.size(), scrollLevel + height));
}
@Override
public synchronized void scrollDown(int lines) {
if (scrollLevel < Integer.MAX_VALUE - lines) {
scrollLevel += lines;
} else {
scrollLevel = Integer.MAX_VALUE;
}
}
@Override
public synchronized void scrollToTop() {
scrollLevel = 0;
}
@Override
public synchronized void scrollToBottom() {
// Hack, but easier that the alternative (rendering whole wave to find end, or setting a flag)
// This will be set to a sane height we re-rendered so it should be safe, unless scrolling up
// in between... but that isn't happening at the moment
scrollLevel = Integer.MAX_VALUE;
}
@Override
public synchronized void scrollUp(int lines) {
scrollLevel = Math.max(0, scrollLevel - lines);
}
}
| apache-2.0 |
AndamanTech/ThaiMCH | src/main/java/com/google/tmch/dao/impl/ChildDaoImpl.java | 5021 | package com.google.tmch.dao.impl;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import com.google.tmch.dao.ChildDao;
import com.google.tmch.model.Child;
import com.google.tmch.model.Child_vaccine;
public class ChildDaoImpl extends JdbcDaoSupport implements ChildDao {
@Override
public Child findChildById(String childid) throws Exception {
String sql="select * from child where child_id=?";
Child child=(Child) this.getJdbcTemplate().queryForObject(sql, new Object[] {childid},new BeanPropertyRowMapper<Child>(Child.class));
return child;
}
@Override
public boolean updateChildProfile(final Child child) throws Exception {
try{
StringBuilder build=new StringBuilder();
build.append("UPDATE `child` SET \n" +
"child.child_firstname= ?,\n" +//1
"child.child_lastname=? ,\n" +//2
"child.child_blood= ?,\n" +//3
"child.child_id13= ?,\n" +//4
"child.child_region= ?,\n" +//5
"child.child_gender= ?,\n" +//6
"child.child_birthday= ?,\n" +//7
"child.child_weight= ?,\n" +//8
"child.child_height= ?,\n" +//9
"child.child_length_of_head= ?,\n" +//10
"child.child_false_born = ?, \n"+//11
"child.child_health_born = ?, \n"+//12
"child.child_uptd_time = ?\n"+//13
"where (child.child_id= ?)");//14
this.getJdbcTemplate().batchUpdate(build.toString(), new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setString(1,child.getChild_firstname());
ps.setString(2,child.getChild_lastname());
ps.setString(3,child.getChild_blood());
ps.setString(4,child.getChild_id13());
ps.setString(5,child.getChild_region());
ps.setString(6,child.getChild_gender());
ps.setString(7,child.getChild_birthday());
ps.setDouble(8,child.getChild_weight());
ps.setDouble(9,child.getChild_height());
ps.setDouble(10,child.getChild_length_of_head());
ps.setString(11,child.getChild_false_born());
ps.setString(12,child.getChild_health_born());
ps.setString(13,child.getChild_uptd_time());
ps.setString(14,child.getChild_id());
}
@Override
public int getBatchSize() {
return 1;
}
});
return true;
}catch(DataAccessException e){
System.out.println(e.getMessage());
return false;
}
}
@Override
public boolean updateChildVaccine(final Child_vaccine vaccine) throws Exception {
try{
StringBuilder build=new StringBuilder();
build.append("UPDATE `child_vaccine` SET \n" +
"child_vaccine.hb_vac_1= ?,\n" +//1
"child_vaccine.hb_vac_2= ?,\n" +//2
"child_vaccine.opv_vac_1= ?,\n" +//3
"child_vaccine.opv_vac_2= ?,\n" +//4
"child_vaccine.opv_vac_3= ?,\n" +//5
"child_vaccine.opv_vac_4= ?,\n" +//6
"child_vaccine.opv_vac_5= ?,\n" +//7
"child_vaccine.mmr_vac_1= ?,\n" +//10
"child_vaccine.mmr_vac_2= ?,\n" +//11
"child_vaccine.je_vac_1= ?,\n" +//12
"child_vaccine.je_vac_2= ?,\n" +//13
"child_vaccine.dt_1= ?,\n" +//14
"child_vaccine.updt_time= ? ,\n" + //15
"child_vaccine.bcg1= ? ,\n" +//16
"child_vaccine.je_vac_3= ? \n"+//17
"WHERE (child_vaccine.child_vaccine_id = ? )");//18
this.getJdbcTemplate().batchUpdate(build.toString(), new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setString(1, vaccine.getHb_vac_1());
ps.setString(2, vaccine.getHb_vac_2());
ps.setString(3, vaccine.getOpv_vac_1());
ps.setString(4, vaccine.getOpv_vac_2());
ps.setString(5, vaccine.getOpv_vac_3());
ps.setString(6, vaccine.getOpv_vac_4());
ps.setString(7, vaccine.getOpv_vac_5());
ps.setString(8, vaccine.getMmr_vac_1());
ps.setString(9, vaccine.getMmr_vac_2());
ps.setString(10, vaccine.getJe_vac_1());
ps.setString(11, vaccine.getJe_vac_2());
ps.setString(12, vaccine.getDt_1());
ps.setString(13, vaccine.getUpdt_time());
ps.setString(14, vaccine.getBcg1());
ps.setString(15, vaccine.getJe_vac_3());
ps.setString(16, vaccine.getChild_id());
}
@Override
public int getBatchSize() {
return 1;
}
});
return true;
}catch(Exception e){
System.out.println(e.getMessage());
return false;
}
}
@Override
public Child_vaccine getChild_vaccine(String child_id) throws Exception {
String sql="select * from child_vaccine where child_vaccine.child_id = ?";
Child_vaccine child_vaccine=(Child_vaccine) this.getJdbcTemplate().queryForObject(sql, new Object[] {child_id},new BeanPropertyRowMapper<Child_vaccine>(Child_vaccine.class));
return child_vaccine;
}
}
| apache-2.0 |
Xpitfire/ufo | UFO.Web/WebServiceClient/src/at/fhooe/hgb/wea5/ufo/web/generated/GetVenues.java | 1382 |
package at.fhooe.hgb.wea5.ufo.web.generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="page" type="{http://ufo.at/}PagingData" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"page"
})
@XmlRootElement(name = "GetVenues")
public class GetVenues {
protected PagingData page;
/**
* Gets the value of the page property.
*
* @return
* possible object is
* {@link PagingData }
*
*/
public PagingData getPage() {
return page;
}
/**
* Sets the value of the page property.
*
* @param value
* allowed object is
* {@link PagingData }
*
*/
public void setPage(PagingData value) {
this.page = value;
}
}
| apache-2.0 |
LoveReadingLoveLife/BookTrace | app/src/main/java/cn/lemene/BookTrace/module/User.java | 5246 | package cn.lemene.BookTrace.module;
/**
* Created by xu on 2016/11/25.
*/
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* 用户实体类
* @author snail 2016/11/25 17:55
* @version v1.0
*/
public class User implements Serializable {
/** ID */
@SerializedName("id")
private String mId;
/** 用户名 */
@SerializedName("username")
private String mUsername;
/** 想读的书 */
@SerializedName("bookWant")
private List<String> mBookWant;
/** 在读的书 */
@SerializedName("bookReading")
static List<String> mBookReading;
/** 读过的书 */
@SerializedName("bookRead")
static List<String> mBookRead;
public User() {
mUsername = UserContainer.username;
mId =UserContainer.userID;
mBookWant = UserContainer.wantReadList;
mBookReading = UserContainer.readingList;
mBookRead = UserContainer.hasReadList;
}
public String getId() {
return mId;
}
public void setId(String id) {
mId = id;
}
public String getUsername() {
return mUsername;
}
public void setUsername(String username) {
mUsername = username;
}
public List<String> getBookWant() {
return mBookWant;
}
public void setBookWant(List<String> bookWant) {
mBookWant = bookWant;
}
public List<String> getBookReading() {
return mBookReading;
}
public void setBookReading(List<String> bookReading) {
mBookReading = bookReading;
}
public List<String> getBookRead() {
return mBookRead;
}
public void setBookRead(List<String> bookRead) {
mBookRead = bookRead;
}
public String getBookWantString() {
String tmp="Please login in.";
String tmp2 = "No book.";
if(UserContainer.username.equals("DefaultUser")) {
return tmp;
}
if(mBookWant!=null) {
return list2String(mBookWant);
}
else{return tmp2;}
}
public String getBookReadingString() {
String tmp = "Please login in.";
String tmp2 = "No book.";
if(UserContainer.username.equals("DefaultUser")) {
return tmp;
}
if(mBookReading!=null) {
return list2String(mBookReading);
}
else{return tmp2;}
}
public String getBookReadString() {
String tmp="Please login in.";
String tmp2 = "No book.";
if(UserContainer.username.equals("DefaultUser")) {
return tmp;
}
if(mBookRead!=null) {
return list2String(mBookRead);
}
else{return tmp2;}
}
/**
* 字符串列表转换为字符串
* @param list
* @return
*/
public String list2String(List<?> list) {
StringBuilder builder = new StringBuilder();
if (list != null && list.size() > 0) {
int i;
for (i = 0; i < list.size() - 2; i++) {
builder.append(list.get(i));
builder.append('\n');
}
builder.append(list.get(i));
}
return builder.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return mId != null ? mId.equals(user.mId) : user.mId == null;
}
@Override
public int hashCode() {
return mId != null ? mId.hashCode() : 0;
}
/*public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
setId("ZHEER_XU!"); //初始化全局变量
List<String> list_book = null;
list_book.add("Ocean");
setBookWant(list_book);
setBookReading(list_book);
setBookRead(list_book);
}*/
/*@Override
/*public String toString() {
return "DBBook{" +
"mId='" + mId + '\'' +
", mRating=" + mRating +
", mTitle='" + mTitle + '\'' +
", mSubtile='" + mSubtile + '\'' +
", mAuthors=" + mAuthors +
", mPUbDate='" + mPUbDate + '\'' +
", mTagses=" + mTagses +
", mOriginTitle='" + mOriginTitle + '\'' +
", mCover='" + mCover + '\'' +
", mBinding='" + mBinding + '\'' +
", mTranslators=" + mTranslators +
", mCatalog='" + mCatalog + '\'' +
", mPages='" + mPages + '\'' +
", mCoveres=" + mCoveres +
", mWebLink='" + mWebLink + '\'' +
", mWebTitle='" + mWebTitle + '\'' +
", mApiUrl='" + mApiUrl + '\'' +
", mPUblisher='" + mPUblisher + '\'' +
", mIsbn10='" + mIsbn10 + '\'' +
", mIsbn13='" + mIsbn13 + '\'' +
", mAuthorIntro='" + mAuthorIntro + '\'' +
", mSummary='" + mSummary + '\'' +
", mPrice='" + mPrice + '\'' +
", mComments='" + mComments + '\'' +
'}';
}*/
} | apache-2.0 |
Brunel-Visualization/Brunel | core/src/main/java/org/brunel/model/VisItem.java | 1428 | /*
* Copyright (c) 2015 IBM Corporation 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.brunel.model;
import org.brunel.data.Dataset;
/* A visualization; either a single element, or a composition */
public abstract class VisItem {
/* Returns null for no composition */
public abstract VisTypes.Composition compositionMethod();
/* This is the last element in the composition, or this item if we are a VisSingle */
public abstract VisElement getSingle();
/* Return child parts -- will be null for a VisSingle */
public abstract VisItem[] children();
/* Define anything undefined, make defaults and return a new ready-to-use item (may be the same object) */
public abstract VisItem makeCanonical();
/* Return a string containing validation errors, or NULL if there are no errors */
public abstract String validate();
public abstract Dataset[] getDataSets();
}
| apache-2.0 |
tkaczmarzyk/specification-arg-resolver | src/test/java/net/kaczmarzyk/spring/data/jpa/domain/LikeTest.java | 2686 | /**
* Copyright 2014-2020 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 net.kaczmarzyk.spring.data.jpa.domain;
import static net.kaczmarzyk.spring.data.jpa.CustomerBuilder.customer;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import net.kaczmarzyk.spring.data.jpa.Customer;
import net.kaczmarzyk.spring.data.jpa.IntegrationTestBase;
import org.junit.Before;
import org.junit.Test;
/**
* @author Tomasz Kaczmarzyk
*/
public class LikeTest extends IntegrationTestBase {
Customer homerSimpson;
Customer margeSimpson;
Customer moeSzyslak;
@Before
public void initData() {
homerSimpson = customer("Homer", "Simpson").street("Evergreen Terrace").build(em);
margeSimpson = customer("Marge", "Simpson").street("Evergreen Terrace").build(em);
moeSzyslak = customer("Moe", "Szyslak").street("Unknown").build(em);
}
@Test
public void filtersByFirstLevelProperty() {
Like<Customer> lastNameSimpson = new Like<>(queryCtx, "lastName", "Simpson");
List<Customer> result = customerRepo.findAll(lastNameSimpson);
assertThat(result)
.hasSize(2)
.containsOnly(homerSimpson, margeSimpson);
Like<Customer> firstNameWithO = new Like<>(queryCtx, "firstName", "o");
result = customerRepo.findAll(firstNameWithO);
assertThat(result)
.hasSize(2)
.containsOnly(homerSimpson, moeSzyslak);
}
@Test
public void filtersByNestedProperty() {
Like<Customer> streetWithEvergreen = new Like<>(queryCtx, "address.street", "Evergreen");
List<Customer> result = customerRepo.findAll(streetWithEvergreen);
assertThat(result).hasSize(2).containsOnly(homerSimpson, margeSimpson);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsMissingArgument() {
new Like<>(queryCtx, "path", new String[] {});
}
@Test(expected = IllegalArgumentException.class)
public void rejectsInvalidNumberOfArguments() {
new Like<>(queryCtx, "path", new String[] {"a", "b"});
}
}
| apache-2.0 |
spoole167/JavaOne2016-Furby | src/main/java/com/ibm/javaone2016/demo/furby/sensor/HeartBeat.java | 1422 | package com.ibm.javaone2016.demo.furby.sensor;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.ibm.javaone2016.demo.furby.AbstractPassiveSensor;
public class HeartBeat extends AbstractPassiveSensor{
private static JsonArray addresses=new JsonArray();
static {
try {
captureIPAddresses();
} catch(IOException e) {
}
}
public HeartBeat() {
super();
}
private static void captureIPAddresses() throws IOException {
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements())
{
NetworkInterface ni = e.nextElement();
Enumeration<InetAddress> addrs = ni.getInetAddresses();
while (addrs.hasMoreElements())
{
InetAddress i = (InetAddress) addrs.nextElement();
String host_address=i.getHostAddress();
if(host_address.contains(":")) continue; // ignore ipv6 addrs
if(host_address.startsWith("127.")) continue; // ignore local addr
addresses.add(i.getHostAddress());
}
}
}
@Override
public void start() {
JsonObject event = new JsonObject();
event.add("addresses",addresses);
while (isAlive()) {
publishEvent("hb","status", event);
pause(10);
}
}
}
| apache-2.0 |
lsimons/phloc-schematron-standalone | phloc-schematron/jing/src/main/java/com/thaiopensource/validate/auto/SchemaFuture.java | 444 | package com.thaiopensource.validate.auto;
import java.io.IOException;
import org.xml.sax.SAXException;
import com.thaiopensource.validate.IncorrectSchemaException;
import com.thaiopensource.validate.Schema;
public interface SchemaFuture
{
Schema getSchema () throws IncorrectSchemaException, SAXException, IOException;
RuntimeException unwrapException (RuntimeException e) throws SAXException, IOException, IncorrectSchemaException;
}
| apache-2.0 |
gesneriana/CoolWeather | app/src/main/java/com/coolweather/app/model/City.java | 1084 | package com.coolweather.app.model;
/**
* Created by Administrator on 2016-05-03.
* 城市表的实体类
*/
public class City {
/**
* 主键,自增长的标识列,城市编号
*/
private int id;
/**
* 城市名称
*/
private String cityName;
/**
* 城市代码,从服务器获取的数据
*/
private String cityCode;
/**
* 省份编号,外键
*/
private int provinceId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public int getProvinceId() {
return provinceId;
}
public void setProvinceId(int provinceId) {
this.provinceId = provinceId;
}
}
| apache-2.0 |
equella/Equella | Source/Plugins/Core/com.equella.core/src/com/tle/core/taxonomy/wizard/WidePopupBrowserWebControl.java | 1113 | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0, (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tle.core.taxonomy.wizard;
import com.tle.core.guice.Bind;
import javax.inject.Inject;
@Bind
class WidePopupBrowserWebControl extends AbstractPopupBrowserWebControl {
@Inject
public WidePopupBrowserWebControl(WidePopupBrowserDialog popupBrowserDialog) {
super(popupBrowserDialog);
}
}
| apache-2.0 |
leafclick/intellij-community | platform/execution-impl/src/com/intellij/diagnostic/logging/LogConfigurationPanel.java | 16735 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.diagnostic.logging;
import com.intellij.diagnostic.DiagnosticBundle;
import com.intellij.execution.ExecutionBundle;
import com.intellij.execution.configurations.LogFileOptions;
import com.intellij.execution.configurations.PredefinedLogFile;
import com.intellij.execution.configurations.RunConfigurationBase;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.ui.TextComponentAccessor;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.BooleanTableCellRenderer;
import com.intellij.ui.TableUtil;
import com.intellij.ui.ToolbarDecorator;
import com.intellij.ui.components.JBCheckBox;
import com.intellij.ui.table.TableView;
import com.intellij.util.SmartList;
import com.intellij.util.ui.AbstractTableCellEditor;
import com.intellij.util.ui.CellEditorComponentWithBrowseButton;
import com.intellij.util.ui.ColumnInfo;
import com.intellij.util.ui.ListTableModel;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class LogConfigurationPanel<T extends RunConfigurationBase> extends SettingsEditor<T> {
private final TableView<LogFileOptions> myFilesTable;
private final ListTableModel<LogFileOptions> myModel;
private JPanel myWholePanel;
private JPanel myScrollPanel;
private JBCheckBox myRedirectOutputCb;
private TextFieldWithBrowseButton myOutputFile;
private JCheckBox myShowConsoleOnStdOutCb;
private JCheckBox myShowConsoleOnStdErrCb;
private final Map<LogFileOptions, PredefinedLogFile> myLog2Predefined = new THashMap<>();
private final List<PredefinedLogFile> myUnresolvedPredefined = new SmartList<>();
public LogConfigurationPanel() {
ColumnInfo<LogFileOptions, Boolean> IS_SHOW = new MyIsActiveColumnInfo();
ColumnInfo<LogFileOptions, LogFileOptions> FILE = new MyLogFileColumnInfo();
ColumnInfo<LogFileOptions, Boolean> IS_SKIP_CONTENT = new MyIsSkipColumnInfo();
myModel = new ListTableModel<>(IS_SHOW, FILE, IS_SKIP_CONTENT);
myFilesTable = new TableView<>(myModel);
myFilesTable.getEmptyText().setText(DiagnosticBundle.message("log.monitor.no.files"));
final JTableHeader tableHeader = myFilesTable.getTableHeader();
final FontMetrics fontMetrics = tableHeader.getFontMetrics(tableHeader.getFont());
int preferredWidth = fontMetrics.stringWidth(IS_SHOW.getName()) + 20;
setUpColumnWidth(tableHeader, preferredWidth, 0);
preferredWidth = fontMetrics.stringWidth(IS_SKIP_CONTENT.getName()) + 20;
setUpColumnWidth(tableHeader, preferredWidth, 2);
myFilesTable.setColumnSelectionAllowed(false);
myFilesTable.setShowGrid(false);
myFilesTable.setDragEnabled(false);
myFilesTable.setShowHorizontalLines(false);
myFilesTable.setShowVerticalLines(false);
myFilesTable.setIntercellSpacing(new Dimension(0, 0));
myScrollPanel.add(
ToolbarDecorator.createDecorator(myFilesTable)
.setAddAction(button -> {
ArrayList<LogFileOptions> newList = new ArrayList<>(myModel.getItems());
LogFileOptions newOptions = new LogFileOptions("", "", true);
if (showEditorDialog(newOptions)) {
newList.add(newOptions);
myModel.setItems(newList);
int index = myModel.getRowCount() - 1;
myModel.fireTableRowsInserted(index, index);
myFilesTable.setRowSelectionInterval(index, index);
}
}).setRemoveAction(button -> {
TableUtil.stopEditing(myFilesTable);
final int[] selected = myFilesTable.getSelectedRows();
if (selected.length == 0) return;
for (int i = selected.length - 1; i >= 0; i--) {
myModel.removeRow(selected[i]);
}
for (int i = selected.length - 1; i >= 0; i--) {
int idx = selected[i];
myModel.fireTableRowsDeleted(idx, idx);
}
int selection = selected[0];
if (selection >= myModel.getRowCount()) {
selection = myModel.getRowCount() - 1;
}
if (selection >= 0) {
myFilesTable.setRowSelectionInterval(selection, selection);
}
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(myFilesTable, true));
}).setEditAction(button -> {
final int selectedRow = myFilesTable.getSelectedRow();
//noinspection ConstantConditions
showEditorDialog(myFilesTable.getSelectedObject());
myModel.fireTableDataChanged();
myFilesTable.setRowSelectionInterval(selectedRow, selectedRow);
}).setRemoveActionUpdater(e -> myFilesTable.getSelectedRowCount() >= 1 &&
!myLog2Predefined.containsKey(myFilesTable.getSelectedObject())).setEditActionUpdater(
e -> myFilesTable.getSelectedRowCount() >= 1 &&
!myLog2Predefined.containsKey(myFilesTable.getSelectedObject()) &&
myFilesTable.getSelectedObject() != null).disableUpDownActions().createPanel(), BorderLayout.CENTER);
myWholePanel.setPreferredSize(new Dimension(-1, 150));
myOutputFile.addBrowseFolderListener(ExecutionBundle.message("choose.file.to.save.console.output"),
ExecutionBundle.message("console.output.would.be.saved.to.the.specified.file"), null,
FileChooserDescriptorFactory.createSingleFileOrFolderDescriptor(),
TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT);
myRedirectOutputCb.addActionListener(e -> myOutputFile.setEnabled(myRedirectOutputCb.isSelected()));
}
private void setUpColumnWidth(final JTableHeader tableHeader, final int preferredWidth, int columnIdx) {
myFilesTable.getColumnModel().getColumn(columnIdx).setCellRenderer(new BooleanTableCellRenderer());
final TableColumn tableColumn = tableHeader.getColumnModel().getColumn(columnIdx);
tableColumn.setWidth(preferredWidth);
tableColumn.setPreferredWidth(preferredWidth);
tableColumn.setMinWidth(preferredWidth);
tableColumn.setMaxWidth(preferredWidth);
}
public void refreshPredefinedLogFiles(RunConfigurationBase configurationBase) {
List<LogFileOptions> items = myModel.getItems();
List<LogFileOptions> newItems = new ArrayList<>();
boolean changed = false;
for (LogFileOptions item : items) {
final PredefinedLogFile predefined = myLog2Predefined.get(item);
if (predefined != null) {
final LogFileOptions options = configurationBase.getOptionsForPredefinedLogFile(predefined);
if (LogFileOptions.areEqual(item, options)) {
newItems.add(item);
}
else {
changed = true;
myLog2Predefined.remove(item);
if (options == null) {
myUnresolvedPredefined.add(predefined);
}
else {
newItems.add(options);
myLog2Predefined.put(options, predefined);
}
}
}
else {
newItems.add(item);
}
}
final PredefinedLogFile[] unresolved = myUnresolvedPredefined.toArray(new PredefinedLogFile[0]);
for (PredefinedLogFile logFile : unresolved) {
final LogFileOptions options = configurationBase.getOptionsForPredefinedLogFile(logFile);
if (options != null) {
changed = true;
myUnresolvedPredefined.remove(logFile);
myLog2Predefined.put(options, logFile);
newItems.add(options);
}
}
if (changed) {
myModel.setItems(newItems);
}
}
@Override
protected void resetEditorFrom(@NotNull final RunConfigurationBase configuration) {
ArrayList<LogFileOptions> list = new ArrayList<>();
final List<LogFileOptions> logFiles = configuration.getLogFiles();
for (LogFileOptions setting : logFiles) {
list.add(
new LogFileOptions(setting.getName(), setting.getPathPattern(), setting.isEnabled(), setting.isSkipContent(), setting.isShowAll()));
}
myLog2Predefined.clear();
myUnresolvedPredefined.clear();
final List<PredefinedLogFile> predefinedLogFiles = configuration.getPredefinedLogFiles();
for (PredefinedLogFile predefinedLogFile : predefinedLogFiles) {
PredefinedLogFile logFile = new PredefinedLogFile();
logFile.copyFrom(predefinedLogFile);
final LogFileOptions options = configuration.getOptionsForPredefinedLogFile(logFile);
if (options != null) {
myLog2Predefined.put(options, logFile);
list.add(options);
}
else {
myUnresolvedPredefined.add(logFile);
}
}
myModel.setItems(list);
final boolean redirectOutputToFile = configuration.isSaveOutputToFile();
myRedirectOutputCb.setSelected(redirectOutputToFile);
final String fileOutputPath = configuration.getOutputFilePath();
myOutputFile.setText(fileOutputPath != null ? FileUtil.toSystemDependentName(fileOutputPath) : "");
myOutputFile.setEnabled(redirectOutputToFile);
myShowConsoleOnStdOutCb.setSelected(configuration.isShowConsoleOnStdOut());
myShowConsoleOnStdErrCb.setSelected(configuration.isShowConsoleOnStdErr());
}
@Override
protected void applyEditorTo(@NotNull final RunConfigurationBase configuration) throws ConfigurationException {
myFilesTable.stopEditing();
configuration.removeAllLogFiles();
configuration.removeAllPredefinedLogFiles();
for (int i = 0; i < myModel.getRowCount(); i++) {
LogFileOptions options = (LogFileOptions)myModel.getValueAt(i, 1);
if (Comparing.equal(options.getPathPattern(), "")) {
continue;
}
final Boolean checked = (Boolean)myModel.getValueAt(i, 0);
final Boolean skipped = (Boolean)myModel.getValueAt(i, 2);
final PredefinedLogFile predefined = myLog2Predefined.get(options);
if (predefined != null) {
PredefinedLogFile file = new PredefinedLogFile();
file.setId(predefined.getId());
file.setEnabled(options.isEnabled());
configuration.addPredefinedLogFile(file);
}
else {
configuration
.addLogFile(options.getPathPattern(), options.getName(), checked.booleanValue(), skipped.booleanValue(), options.isShowAll());
}
}
for (PredefinedLogFile logFile : myUnresolvedPredefined) {
configuration.addPredefinedLogFile(logFile);
}
final String text = myOutputFile.getText();
configuration.setFileOutputPath(StringUtil.isEmpty(text) ? null : FileUtil.toSystemIndependentName(text));
configuration.setSaveOutputToFile(myRedirectOutputCb.isSelected());
configuration.setShowConsoleOnStdOut(myShowConsoleOnStdOutCb.isSelected());
configuration.setShowConsoleOnStdErr(myShowConsoleOnStdErrCb.isSelected());
}
@Override
@NotNull
protected JComponent createEditor() {
return myWholePanel;
}
private static boolean showEditorDialog(@NotNull LogFileOptions options) {
EditLogPatternDialog dialog = new EditLogPatternDialog();
dialog.init(options.getName(), options.getPathPattern(), options.isShowAll());
if (dialog.showAndGet()) {
options.setName(dialog.getName());
options.setPathPattern(dialog.getLogPattern());
options.setShowAll(dialog.isShowAllFiles());
return true;
}
return false;
}
private class MyLogFileColumnInfo extends ColumnInfo<LogFileOptions, LogFileOptions> {
MyLogFileColumnInfo() {
super(DiagnosticBundle.message("log.monitor.log.file.column"));
}
@Override
public TableCellRenderer getRenderer(final LogFileOptions p0) {
return new DefaultTableCellRenderer() {
@NotNull
@Override
public Component getTableCellRendererComponent(@NotNull JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
final Component renderer = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
setText(((LogFileOptions)value).getName());
setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
setBorder(null);
return renderer;
}
};
}
@Override
public LogFileOptions valueOf(final LogFileOptions object) {
return object;
}
@Override
public TableCellEditor getEditor(final LogFileOptions item) {
return new LogFileCellEditor(item);
}
@Override
public void setValue(final LogFileOptions o, final LogFileOptions aValue) {
if (aValue != null) {
if (!o.getName().equals(aValue.getName()) || !o.getPathPattern().equals(aValue.getPathPattern())
|| o.isShowAll() != aValue.isShowAll()) {
myLog2Predefined.remove(o);
}
o.setName(aValue.getName());
o.setShowAll(aValue.isShowAll());
o.setPathPattern(aValue.getPathPattern());
}
}
@Override
public boolean isCellEditable(final LogFileOptions o) {
return !myLog2Predefined.containsKey(o);
}
}
private class MyIsActiveColumnInfo extends ColumnInfo<LogFileOptions, Boolean> {
protected MyIsActiveColumnInfo() {
super(DiagnosticBundle.message("log.monitor.is.active.column"));
}
@Override
public Class getColumnClass() {
return Boolean.class;
}
@Override
public Boolean valueOf(final LogFileOptions object) {
return object.isEnabled();
}
@Override
public boolean isCellEditable(LogFileOptions element) {
return true;
}
@Override
public void setValue(LogFileOptions element, Boolean checked) {
final PredefinedLogFile predefinedLogFile = myLog2Predefined.get(element);
if (predefinedLogFile != null) {
predefinedLogFile.setEnabled(checked.booleanValue());
}
element.setEnabled(checked.booleanValue());
}
}
private class MyIsSkipColumnInfo extends ColumnInfo<LogFileOptions, Boolean> {
protected MyIsSkipColumnInfo() {
super(DiagnosticBundle.message("log.monitor.is.skipped.column"));
}
@Override
public Class getColumnClass() {
return Boolean.class;
}
@Override
public Boolean valueOf(final LogFileOptions element) {
return element.isSkipContent();
}
@Override
public boolean isCellEditable(LogFileOptions element) {
return !myLog2Predefined.containsKey(element);
}
@Override
public void setValue(LogFileOptions element, Boolean skipped) {
element.setSkipContent(skipped.booleanValue());
}
}
private class LogFileCellEditor extends AbstractTableCellEditor {
private final CellEditorComponentWithBrowseButton<JTextField> myComponent;
private final LogFileOptions myLogFileOptions;
LogFileCellEditor(LogFileOptions options) {
myLogFileOptions = options;
myComponent = new CellEditorComponentWithBrowseButton<>(new TextFieldWithBrowseButton(), this);
getChildComponent().setEditable(false);
getChildComponent().setBorder(null);
myComponent.getComponentWithButton().getButton().addActionListener(e -> {
showEditorDialog(myLogFileOptions);
JTextField textField = getChildComponent();
textField.setText(myLogFileOptions.getName());
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> IdeFocusManager.getGlobalInstance().requestFocus(textField, true));
myModel.fireTableDataChanged();
});
}
@Override
public Object getCellEditorValue() {
return myLogFileOptions;
}
private JTextField getChildComponent() {
return myComponent.getChildComponent();
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
getChildComponent().setText(((LogFileOptions)value).getName());
return myComponent;
}
}
}
| apache-2.0 |
isharak/product-is | modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/identity/integration/test/scim/SCIMUserProviderTestCase.java | 3153 | /**
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) 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 org.wso2.identity.integration.test.scim;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.identity.integration.common.clients.scim.SCIMConfigAdminClient;
import org.wso2.identity.integration.common.utils.ISIntegrationTest;
public class SCIMUserProviderTestCase extends ISIntegrationTest {
private static final Log log = LogFactory.getLog(SCIMUserProviderTestCase.class);
private SCIMConfigAdminClient scimConfigAdminClient;
public static final String providerId = "testProvider";
public static final int providerUserId = 2;
private String scim_Provider_url;
// @BeforeClass(alwaysRun = true)
// public void testInit() throws Exception {
// super.init();
// userInfo = UserListCsvReader.getUserInfo(providerUserId);
// scimConfigAdminClient =
// new SCIMConfigAdminClient(backendURL, sessionCookie);
// scim_Provider_url = "https://" + backendURL + "/wso2/scim/";
//
// }
//
// @Test(description = "Add user service provider", priority = 1)
// public void testAddUserProvider() throws Exception {
// boolean providerAvailable = false;
// scimConfigAdminClient.addUserProvider(userInfo.getUserName() + "@carbon.super", providerId,
// userInfo.getUserName(), userInfo.getPassword(),
// scim_Provider_url + "Users", scim_Provider_url + "Groups");
// Thread.sleep(5000);
// SCIMProviderDTO[] scimProviders = scimConfigAdminClient.listUserProviders(userInfo.getUserName() +
// "@carbon.super", providerId);
// for (SCIMProviderDTO scimProvider : scimProviders) {
// if (scimProvider.getProviderId().equals(providerId)) {
// providerAvailable = true;
// }
// }
// Assert.assertTrue(providerAvailable, "Provider adding failed");
// }
//
// @Test(description = "delete user service provider", dependsOnMethods = {"testAddUserProvider"}, priority = 2)
// public void testDeleteUserProvider() {
// boolean providerDeleted = false;
// try {
// scimConfigAdminClient.deleteUserProvider(userInfo.getUserName() + "@carbon.super", providerId);
// providerDeleted = true;
// } catch (Exception e) {
// log.error("Provider [" + providerId + "] delete failed.", e);
// }
// Assert.assertTrue(providerDeleted, "Provider [" + providerId + "] delete failed");
// }
}
| apache-2.0 |
jcamachor/calcite | core/src/main/java/org/apache/calcite/rel/rules/AggregateFilterTransposeRule.java | 7952 | /*
* 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.rel.rules;
import org.apache.calcite.plan.RelOptRuleCall;
import org.apache.calcite.plan.RelOptRuleOperand;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.plan.RelRule;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.Aggregate;
import org.apache.calcite.rel.core.Aggregate.Group;
import org.apache.calcite.rel.core.AggregateCall;
import org.apache.calcite.rel.core.Filter;
import org.apache.calcite.rel.metadata.RelMetadataQuery;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexUtil;
import org.apache.calcite.sql.SqlAggFunction;
import org.apache.calcite.tools.RelBuilderFactory;
import org.apache.calcite.util.ImmutableBitSet;
import org.apache.calcite.util.mapping.Mappings;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;
/**
* Planner rule that matches an {@link org.apache.calcite.rel.core.Aggregate}
* on a {@link org.apache.calcite.rel.core.Filter} and transposes them,
* pushing the aggregate below the filter.
*
* <p>In some cases, it is necessary to split the aggregate.
*
* <p>This rule does not directly improve performance. The aggregate will
* have to process more rows, to produce aggregated rows that will be thrown
* away. The rule might be beneficial if the predicate is very expensive to
* evaluate. The main use of the rule is to match a query that has a filter
* under an aggregate to an existing aggregate table.
*
* @see org.apache.calcite.rel.rules.FilterAggregateTransposeRule
* @see CoreRules#AGGREGATE_FILTER_TRANSPOSE
*/
public class AggregateFilterTransposeRule
extends RelRule<AggregateFilterTransposeRule.Config>
implements TransformationRule {
/** Creates an AggregateFilterTransposeRule. */
protected AggregateFilterTransposeRule(Config config) {
super(config);
}
@Deprecated // to be removed before 2.0
public AggregateFilterTransposeRule(RelOptRuleOperand operand,
RelBuilderFactory relBuilderFactory) {
this(Config.DEFAULT
.withRelBuilderFactory(relBuilderFactory)
.withOperandSupplier(b -> b.exactly(operand))
.as(Config.class));
}
@Override public void onMatch(RelOptRuleCall call) {
final Aggregate aggregate = call.rel(0);
final Filter filter = call.rel(1);
// Do the columns used by the filter appear in the output of the aggregate?
final ImmutableBitSet filterColumns =
RelOptUtil.InputFinder.bits(filter.getCondition());
final ImmutableBitSet newGroupSet =
aggregate.getGroupSet().union(filterColumns);
final RelNode input = filter.getInput();
final RelMetadataQuery mq = call.getMetadataQuery();
final Boolean unique = mq.areColumnsUnique(input, newGroupSet);
if (unique != null && unique) {
// The input is already unique on the grouping columns, so there's little
// advantage of aggregating again. More important, without this check,
// the rule fires forever: A-F => A-F-A => A-A-F-A => A-A-A-F-A => ...
return;
}
final boolean allColumnsInAggregate =
aggregate.getGroupSet().contains(filterColumns);
final Aggregate newAggregate =
aggregate.copy(aggregate.getTraitSet(), input,
newGroupSet, null, aggregate.getAggCallList());
final Mappings.TargetMapping mapping = Mappings.target(
newGroupSet::indexOf,
input.getRowType().getFieldCount(),
newGroupSet.cardinality());
final RexNode newCondition =
RexUtil.apply(mapping, filter.getCondition());
final Filter newFilter = filter.copy(filter.getTraitSet(),
newAggregate, newCondition);
if (allColumnsInAggregate && aggregate.getGroupType() == Group.SIMPLE) {
// Everything needed by the filter is returned by the aggregate.
assert newGroupSet.equals(aggregate.getGroupSet());
call.transformTo(newFilter);
} else {
// If aggregate uses grouping sets, we always need to split it.
// Otherwise, it means that grouping sets are not used, but the
// filter needs at least one extra column, and now aggregate it away.
final ImmutableBitSet.Builder topGroupSet = ImmutableBitSet.builder();
for (int c : aggregate.getGroupSet()) {
topGroupSet.set(newGroupSet.indexOf(c));
}
ImmutableList<ImmutableBitSet> newGroupingSets = null;
if (aggregate.getGroupType() != Group.SIMPLE) {
ImmutableList.Builder<ImmutableBitSet> newGroupingSetsBuilder =
ImmutableList.builder();
for (ImmutableBitSet groupingSet : aggregate.getGroupSets()) {
final ImmutableBitSet.Builder newGroupingSet =
ImmutableBitSet.builder();
for (int c : groupingSet) {
newGroupingSet.set(newGroupSet.indexOf(c));
}
newGroupingSetsBuilder.add(newGroupingSet.build());
}
newGroupingSets = newGroupingSetsBuilder.build();
}
final List<AggregateCall> topAggCallList = new ArrayList<>();
int i = newGroupSet.cardinality();
for (AggregateCall aggregateCall : aggregate.getAggCallList()) {
final SqlAggFunction rollup = aggregateCall.getAggregation().getRollup();
if (rollup == null) {
// This aggregate cannot be rolled up.
return;
}
if (aggregateCall.isDistinct()) {
// Cannot roll up distinct.
return;
}
topAggCallList.add(
AggregateCall.create(rollup, aggregateCall.isDistinct(),
aggregateCall.isApproximate(), aggregateCall.ignoreNulls(),
ImmutableList.of(i++), -1,
aggregateCall.distinctKeys, aggregateCall.collation,
aggregateCall.type, aggregateCall.name));
}
final Aggregate topAggregate =
aggregate.copy(aggregate.getTraitSet(), newFilter,
topGroupSet.build(), newGroupingSets, topAggCallList);
call.transformTo(topAggregate);
}
}
/** Rule configuration. */
public interface Config extends RelRule.Config {
Config DEFAULT = EMPTY.as(Config.class)
.withOperandFor(Aggregate.class, Filter.class);
@Override default AggregateFilterTransposeRule toRule() {
return new AggregateFilterTransposeRule(this);
}
/** Defines an operand tree for the given 2 classes. */
default Config withOperandFor(Class<? extends Aggregate> aggregateClass,
Class<? extends Filter> filterClass) {
return withOperandSupplier(b0 ->
b0.operand(aggregateClass).oneInput(b1 ->
b1.operand(filterClass).anyInputs()))
.as(Config.class);
}
/** Defines an operand tree for the given 3 classes. */
default Config withOperandFor(Class<? extends Aggregate> aggregateClass,
Class<? extends Filter> filterClass,
Class<? extends RelNode> relClass) {
return withOperandSupplier(b0 ->
b0.operand(aggregateClass).oneInput(b1 ->
b1.operand(filterClass).oneInput(b2 ->
b2.operand(relClass).anyInputs())))
.as(Config.class);
}
}
}
| apache-2.0 |
desruisseaux/sis | core/sis-utility/src/main/java/org/apache/sis/math/StatisticsFormat.java | 18179 | /*
* 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.math;
import java.util.List;
import java.util.ArrayList;
import java.io.IOException;
import java.util.Locale;
import java.util.TimeZone;
import java.text.Format;
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.ParseException;
import org.opengis.util.InternationalString;
import org.apache.sis.io.TableAppender;
import org.apache.sis.io.TabularFormat;
import org.apache.sis.util.ArgumentChecks;
import org.apache.sis.util.resources.Vocabulary;
import org.apache.sis.util.collection.BackingStoreException;
import static java.lang.Math.*;
/**
* Formats a {@link Statistics} object.
* By default, newly created {@code StatisticsFormat} instances will format statistical values
* in a tabular format using spaces as the column separator. This default configuration matches
* the {@link Statistics#toString()} format.
*
* <div class="section">Limitations</div>
* The current implementation can only format statistics - parsing is not yet implemented.
*
* @author Martin Desruisseaux (MPO, IRD, Geomatys)
* @since 0.3
* @version 0.3
* @module
*/
public class StatisticsFormat extends TabularFormat<Statistics> {
/**
* For cross-version compatibility.
*/
private static final long serialVersionUID = 6914760410359494163L;
/**
* Number of additional digits, to be added to the number of digits computed from the
* range and the number of sample values. This is an arbitrary parameter.
*/
private static final int ADDITIONAL_DIGITS = 2;
/**
* The locale for row and column headers.
* This is usually the same than the format locale, but not necessarily.
*/
private final Locale headerLocale;
/**
* The "width" of the border to drawn around the table, in number of lines.
*
* @see #getBorderWidth()
* @see #setBorderWidth(int)
*/
private byte borderWidth;
/**
* {@code true} if the sample values given to {@code Statistics.accept(…)} methods were the
* totality of the population under study, or {@code false} if they were only a sampling.
*
* @see #isForAllPopulation()
* @see #setForAllPopulation(boolean)
* @see Statistics#standardDeviation(boolean)
*/
private boolean allPopulation;
/**
* Returns an instance for the current system default locale.
*
* @return A statistics format instance for the current default locale.
*/
public static StatisticsFormat getInstance() {
return new StatisticsFormat(
Locale.getDefault(Locale.Category.FORMAT),
Locale.getDefault(Locale.Category.DISPLAY), null);
}
/**
* Returns an instance for the given locale.
*
* @param locale The locale for which to get a {@code StatisticsFormat} instance.
* @return A statistics format instance for the given locale.
*/
public static StatisticsFormat getInstance(final Locale locale) {
return new StatisticsFormat(locale, locale, null);
}
/**
* Constructs a new format for the given numeric and header locales.
* The timezone is used only if the values added to the {@link Statistics} are dates.
*
* @param locale The locale to use for numbers, dates and angles formatting,
* or {@code null} for the {@linkplain Locale#ROOT root locale}.
* @param headerLocale The locale for row and column headers. Usually same as {@code locale}.
* @param timezone The timezone, or {@code null} for UTC.
*/
public StatisticsFormat(final Locale locale, final Locale headerLocale, final TimeZone timezone) {
super(locale, timezone);
this.headerLocale = (headerLocale != null) ? headerLocale : Locale.ROOT;
}
/**
* Returns the locale for the given category. This method implements the following mapping:
*
* <ul>
* <li>{@link java.util.Locale.Category#DISPLAY} — the {@code headerLocale} given at construction time.</li>
* <li>{@link java.util.Locale.Category#FORMAT} — the {@code locale} given at construction time,
* used for all values below the header row.</li>
* </ul>
*
* @param category The category for which a locale is desired.
* @return The locale for the given category (never {@code null}).
*
* @since 0.4
*/
@Override
public Locale getLocale(final Locale.Category category) {
if (category == Locale.Category.DISPLAY) {
return headerLocale;
}
return super.getLocale(category);
}
/**
* Returns the type of objects formatted by this class.
*
* @return {@code Statistics.class}
*/
@Override
public final Class<Statistics> getValueType() {
return Statistics.class;
}
/**
* Returns {@code true} if this formatter shall consider that the statistics where computed
* using the totality of the populations under study. This information impacts the standard
* deviation values to be formatted.
*
* @return {@code true} if the statistics to format where computed using the totality of
* the populations under study.
*
* @see Statistics#standardDeviation(boolean)
*/
public boolean isForAllPopulation() {
return allPopulation;
}
/**
* Sets whether this formatter shall consider that the statistics where computed using
* the totality of the populations under study. The default value is {@code false}.
*
* @param allPopulation {@code true} if the statistics to format where computed
* using the totality of the populations under study.
*
* @see Statistics#standardDeviation(boolean)
*/
public void setForAllPopulation(final boolean allPopulation) {
this.allPopulation = allPopulation;
}
/**
* Returns the "width" of the border to drawn around the table, in number of lines.
* The default width is 0, which stands for no border.
*
* @return The border "width" in number of lines.
*/
public int getBorderWidth() {
return borderWidth;
}
/**
* Sets the "width" of the border to drawn around the table, in number of lines.
* The value can be any of the following:
*
* <ul>
* <li>0 (the default) for no border</li>
* <li>1 for single line ({@code │},{@code ─})</li>
* <li>2 for double lines ({@code ║},{@code ═})</li>
* </ul>
*
* @param borderWidth The border width, in number of lines.
*/
public void setBorderWidth(final int borderWidth) {
ArgumentChecks.ensureBetween("borderWidth", 0, 2, borderWidth);
this.borderWidth = (byte) borderWidth;
}
/**
* Not yet implemented.
*
* @return Currently never return.
* @throws ParseException Currently never thrown.
*/
@Override
public Statistics parse(CharSequence text, ParsePosition pos) throws ParseException {
throw new UnsupportedOperationException();
}
/**
* Formats the given statistics. This method will delegates to one of the following methods,
* depending on the type of the given object:
*
* <ul>
* <li>{@link #format(Statistics, Appendable)}</li>
* <li>{@link #format(Statistics[], Appendable)}</li>
* </ul>
*
* @param object The object to format.
* @param toAppendTo Where to format the object.
* @param pos Ignored in current implementation.
* @return The given buffer, returned for convenience.
*/
@Override
public StringBuffer format(final Object object, final StringBuffer toAppendTo, final FieldPosition pos) {
if (object instanceof Statistics[]) try {
format((Statistics[]) object, toAppendTo);
return toAppendTo;
} catch (IOException e) {
// Same exception handling than in the super-class.
throw new BackingStoreException(e);
} else {
return super.format(object, toAppendTo, pos);
}
}
/**
* Formats a localized string representation of the given statistics.
* If statistics on {@linkplain Statistics#differences() differences}
* are associated to the given object, they will be formatted too.
*
* @param stats The statistics to format.
* @param toAppendTo Where to format the statistics.
* @throws IOException If an error occurred while writing to the given appendable.
*/
@Override
public void format(Statistics stats, final Appendable toAppendTo) throws IOException {
final List<Statistics> list = new ArrayList<>(3);
while (stats != null) {
list.add(stats);
stats = stats.differences();
}
format(list.toArray(new Statistics[list.size()]), toAppendTo);
}
/**
* Formats the given statistics in a tabular format. This method does not check
* for the statistics on {@linkplain Statistics#differences() differences} - if
* such statistics are wanted, they must be included in the given array.
*
* @param stats The statistics to format.
* @param toAppendTo Where to format the statistics.
* @throws IOException If an error occurred while writing to the given appendable.
*/
public void format(final Statistics[] stats, final Appendable toAppendTo) throws IOException {
/*
* Inspect the given statistics in order to determine if we shall omit the headers,
* and if we shall omit the count of NaN values.
*/
final String[] headers = new String[stats.length];
boolean showHeaders = false;
boolean showNaNCount = false;
for (int i=0; i<stats.length; i++) {
final Statistics s = stats[i];
showNaNCount |= (s.countNaN() != 0);
final InternationalString header = s.name();
if (header != null) {
headers[i] = header.toString(headerLocale);
showHeaders |= (headers[i] != null);
}
}
char horizontalLine = 0;
String separator = columnSeparator;
switch (borderWidth) {
case 1: horizontalLine = '─'; separator += "│ "; break;
case 2: horizontalLine = '═'; separator += "║ "; break;
}
final TableAppender table = new TableAppender(toAppendTo, separator);
final Vocabulary resources = Vocabulary.getResources(headerLocale);
/*
* If there is a header for at least one statistics, write the full headers row.
*/
if (horizontalLine != 0) {
table.nextLine(horizontalLine);
}
if (showHeaders) {
table.nextColumn();
for (final String header : headers) {
if (header != null) {
table.append(header);
table.setCellAlignment(TableAppender.ALIGN_CENTER);
}
table.nextColumn();
}
table.append(lineSeparator);
if (horizontalLine != 0) {
table.nextLine(horizontalLine);
}
}
/*
* Initialize the NumberFormat for formatting integers without scientific notation.
* This is necessary since the format may have been modified by a previous execution
* of this method.
*/
final Format format = getFormat(Double.class);
if (format instanceof DecimalFormat) {
((DecimalFormat) format).applyPattern("#0"); // Also disable scientific notation.
} else if (format instanceof NumberFormat) {
setFractionDigits((NumberFormat) format, 0);
}
/*
* Iterates over the rows to format (count, minimum, maximum, mean, RMS, standard deviation),
* then iterate over columns (statistics on sample values, on the first derivatives, etc.)
* The NumberFormat configuration may be different for each column, but we can skip many
* reconfiguration in the common case where there is only one column.
*/
boolean needsConfigure = false;
for (int i=0; i<KEYS.length; i++) {
switch (i) {
case 1: if (!showNaNCount) continue; else break;
// Case 0 and 1 use the above configuration for integers.
// Case 2 unconditionally needs a reconfiguration for floating point values.
// Case 3 and others need reconfiguration only if there is more than one column.
case 2: needsConfigure = true; break;
case 3: needsConfigure = (stats[0].differences() != null); break;
}
table.setCellAlignment(TableAppender.ALIGN_LEFT);
table.append(resources.getString(KEYS[i])).append(':');
for (final Statistics s : stats) {
final Number value;
switch (i) {
case 0: value = s.count(); break;
case 1: value = s.countNaN(); break;
case 2: value = s.minimum(); break;
case 3: value = s.maximum(); break;
case 4: value = s.mean(); break;
case 5: value = s.rms(); break;
case 6: value = s.standardDeviation(allPopulation); break;
default: throw new AssertionError(i);
}
if (needsConfigure) {
configure(format, s);
}
table.append(beforeFill);
table.nextColumn(fillCharacter);
table.append(format.format(value));
table.setCellAlignment(TableAppender.ALIGN_RIGHT);
}
table.append(lineSeparator);
}
if (horizontalLine != 0) {
table.nextLine(horizontalLine);
}
/*
* TableAppender needs to be explicitly flushed in order to format the values.
*/
table.flush();
}
/**
* The resource keys of the rows to formats. Array index must be consistent with the
* switch statements inside the {@link #format(Statistics[], Appendable)} method
* (we define this static field close to the format methods for this purpose).
*/
private static final short[] KEYS = {
Vocabulary.Keys.NumberOfValues,
Vocabulary.Keys.NumberOfNaN,
Vocabulary.Keys.MinimumValue,
Vocabulary.Keys.MaximumValue,
Vocabulary.Keys.MeanValue,
Vocabulary.Keys.RootMeanSquare,
Vocabulary.Keys.StandardDeviation
};
/**
* Configures the given formatter for writing a set of data described by the given statistics.
* This method configures the formatter using heuristic rules based on the range of values and
* their standard deviation. It can be used for reasonable default formatting when the user
* didn't specify an explicit one.
*
* @param format The formatter to configure.
* @param stats The statistics for which to configure the formatter.
*/
private void configure(final Format format, final Statistics stats) {
final double minimum = stats.minimum();
final double maximum = stats.maximum();
final double extremum = max(abs(minimum), abs(maximum));
if ((extremum >= 1E+10 || extremum <= 1E-4) && format instanceof DecimalFormat) {
/*
* The above threshold is high so that geocentric and projected coordinates in metres
* are not formatted with scientific notation (a threshold of 1E+7 is not enough).
* The number of decimal digits in the pattern is arbitrary.
*/
((DecimalFormat) format).applyPattern("0.00000E00");
} else {
/*
* Computes a representative range of values. We take 2 standard deviations away
* from the mean. Assuming that data have a gaussian distribution, this is 97.7%
* of data. If the data have a uniform distribution, then this is 100% of data.
*/
double delta;
final double mean = stats.mean();
delta = 2 * stats.standardDeviation(true); // 'true' is for avoiding NaN when count == 1.
delta = min(maximum, mean+delta) - max(minimum, mean-delta); // Range of 97.7% of values.
delta = max(delta/stats.count(), ulp(extremum)); // Mean delta for uniform distribution, not finer than 'double' accuracy.
if (format instanceof NumberFormat) {
setFractionDigits((NumberFormat) format, max(0, ADDITIONAL_DIGITS
+ DecimalFunctions.fractionDigitsForDelta(delta, false)));
} else {
// A future version could configure DateFormat here.
}
}
}
/**
* Convenience method for setting the minimum and maximum fraction digits of the given format.
*/
private static void setFractionDigits(final NumberFormat format, final int digits) {
format.setMinimumFractionDigits(digits);
format.setMaximumFractionDigits(digits);
}
}
| apache-2.0 |
lucasvschenatto/eventex | src/main/routes/ReadActivityRoute.java | 949 | package main.routes;
import com.google.gson.Gson;
import main.domain.activity.reading.ReadActivityRequest;
import main.domain.activity.reading.ActivitySummary;
import main.domain.activity.reading.ReadActivityUseCase;
import spark.Request;
import spark.Response;
import spark.Route;
public class ReadActivityRoute implements Route {
private Dependencies dependencies;
private Gson converter = new Gson();
public ReadActivityRoute(Dependencies dependencies){
this.dependencies = dependencies;
}
public Object handle(Request request, Response response) throws Exception {
ReadActivityRequest input = new ReadActivityRequest();
input.id = request.params(":id");
ActivitySummary output = new ActivitySummary();
new ReadActivityUseCase(dependencies.getActivityRepository(),input,output).execute();
if(output.id == null || output.id.isEmpty()) response.status(404);
return converter.toJson(output);
}
}
| apache-2.0 |
covito/legend-shop | src/main/java/com/legendshop/event/processor/Processor.java | 177 | package com.legendshop.event.processor;
public abstract interface Processor<T> {
public abstract boolean isSupport(T paramT);
public abstract void onEvent(T paramT);
} | apache-2.0 |
SensorSink/pond | bootstrap/src/main/java/org/sensorsink/pond/bootstrap/domain/SinksModule.java | 1340 | /*
* Copyright 2015 Niclas Hedhman, niclas@hedhman.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.sensorsink.pond.bootstrap.domain;
import org.apache.zest.api.common.Visibility;
import org.apache.zest.bootstrap.AssemblyException;
import org.apache.zest.bootstrap.LayerAssembly;
import org.apache.zest.bootstrap.ModuleAssembly;
import org.apache.zest.bootstrap.layered.ModuleAssembler;
import org.sensorsink.pond.model.sink.Sink;
import org.sensorsink.pond.sink.elasticsearch.ElasticSearchSink;
public class SinksModule
implements ModuleAssembler
{
@Override
public ModuleAssembly assemble( LayerAssembly layer, ModuleAssembly module )
throws AssemblyException
{
module.services( ElasticSearchSink.class ).visibleIn( Visibility.application );
return module;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-athena/src/main/java/com/amazonaws/services/athena/model/transform/CreateDataCatalogRequestMarshaller.java | 3290 | /*
* 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.athena.model.transform;
import java.util.Map;
import java.util.List;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.athena.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* CreateDataCatalogRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class CreateDataCatalogRequestMarshaller {
private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Name").build();
private static final MarshallingInfo<String> TYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Type").build();
private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Description").build();
private static final MarshallingInfo<Map> PARAMETERS_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Parameters").build();
private static final MarshallingInfo<List> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Tags").build();
private static final CreateDataCatalogRequestMarshaller instance = new CreateDataCatalogRequestMarshaller();
public static CreateDataCatalogRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(CreateDataCatalogRequest createDataCatalogRequest, ProtocolMarshaller protocolMarshaller) {
if (createDataCatalogRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(createDataCatalogRequest.getName(), NAME_BINDING);
protocolMarshaller.marshall(createDataCatalogRequest.getType(), TYPE_BINDING);
protocolMarshaller.marshall(createDataCatalogRequest.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(createDataCatalogRequest.getParameters(), PARAMETERS_BINDING);
protocolMarshaller.marshall(createDataCatalogRequest.getTags(), TAGS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
joarder/oltpdbsim | oltpdbsim/src/main/java/entry/Global.java | 5352 | /*******************************************************************************
* Copyright [2014] [Joarder Kamal]
*
* 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 main.java.entry;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import main.java.dsm.DataStreamMining;
import org.apache.commons.math3.random.RandomDataGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class Global {
// Global variables
public static int global_index = 0;
public static Map<Integer, Integer> global_index_map = new HashMap<Integer, Integer>();
public static int global_trSeq = 0;
public static int global_trCount = 0;
public static int total_transactions = 0;
public static int remove_count = 0;
public static int global_tupleSeq = 0;
public static int global_dataCount = 0;
// Hyperedge and compressed hyperedge sequence number
public static int hEdgeSeq = 0;
public static int cHEdgeSeq = 0;
// Random variable
public static Random rand;
// Random number generator
public static RandomDataGenerator rdg;
// Input arugments from console
public static String wrl;
public static double scaleFactor;
public static int repeatedRuns;
// Cluster related parameters
public static String setup;
public static int servers;
public static int serverSSD;
public static int serverSSDCapacity;
public static int partitions;
public static long partitionCapacity;
public static int replicas;
// OS name
public static String OS = System.getProperty("os.name").toLowerCase();
// Directory and extension names
public static String dir_sep = "";
public static String wrl_dir = "";
public static String part_dir = "";
public static String mining_dir = "";
public static String metis_dir = "";
public static String metric_dir = "";
public static String metis_hgr_exec = "";
public static String metis_gr_exec = "";
public static String ext = "";
public static String wrl_file_name = "workload.tr";
public static String wrl_fixfile_name = "fixfile.tr";
// Usage and abort message
public static String run_usage = "Example usage: \"java -jar oltpdbsim-4.3.5 tpcc 0.01 1\" or \"java -jar oltpdbsim-4.3.5 twitter 10 1\" to run the simulation";
public static String abort = "Aborting ...";
// Workload execution
public static double simulationPeriod;
public static double warmupPeriod;
public static double meanInterArrivalTime;
public static double meanServiceTime;
public static double percentageChangeInWorkload;
//public static double adjustment;
public static double expAvgWt; // Defines how far we need to look back while repeating transactions
public static int observationWindow;
public static int uniqueMaxFixed;
public static boolean uniqueEnabled;
// Workload mining
public static int mining_serial = 0;
public static DataStreamMining dsm;
public static boolean streamCollection;
public static int streamCollectorSizeFactor = 1;
// ARHC and A-ARHC specific
public static boolean adaptive; // A-ARHC
public static boolean associative; // ARHC
public static boolean isFrequentClustersFound = true; // A-ARHC/ARHC
// Simulation specific
public static String simulation; // none/static/(gr/cgr/hgr/chg-basic/fd/fdfnd-random/mc/msm/sword)
public static boolean workloadAware; // true/false
public static boolean incrementalRepartitioning; // true/false
public static boolean graphcutBasedRepartitioning; // true/false
public static boolean enableTrClassification; // true/false
public static boolean repartStatic;
public static boolean repartHourly;
public static boolean repartThreshold;
public static String workloadRepresentation; // gr/cgr/hgr/chg
public static String trClassificationStrategy; // basic/fd/fdfnd
public static String dataMigrationStrategy; // random/mc/msm/sword
public static boolean compressionEnabled; // true/false
public static boolean compressionBeforeSetup;
public static double compressionRatio;
public static int repartitioningCycle = 0;
public static double userDefinedIDtThreshold;
// Logger
public static Logger LOGGER = LoggerFactory.getLogger(Global.class);
public static boolean spanReduction;
public static int spanReduce;
public static double lambda;
// For Sword
public static int compressedVertices;
public static boolean swordInitial = true;
// For Analysis
public static boolean analysis;
// For dynamic partitioning
public static boolean dynamicPartitioning;
public static int dynamicPartitions;
public static String getRunDir() {
return ("run"+Global.repeatedRuns+Global.dir_sep);
}
} | apache-2.0 |
zhangxin23/widgets | core/src/main/java/net/coderland/server/core/model/pojo/StockFollows.java | 975 | package net.coderland.server.core.model.pojo;
import java.util.Date;
public class StockFollows {
private Integer id;
private String user;
private String stockCode;
private Date ctime;
private Byte status;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user == null ? null : user.trim();
}
public String getStockCode() {
return stockCode;
}
public void setStockCode(String stockCode) {
this.stockCode = stockCode == null ? null : stockCode.trim();
}
public Date getCtime() {
return ctime;
}
public void setCtime(Date ctime) {
this.ctime = ctime;
}
public Byte getStatus() {
return status;
}
public void setStatus(Byte status) {
this.status = status;
}
} | apache-2.0 |
watson-developer-cloud/java-sdk | speech-to-text/src/main/java/com/ibm/watson/speech_to_text/v1/util/MediaTypeUtils.java | 2500 | /*
* (C) Copyright IBM Corp. 2019, 2020.
*
* 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.ibm.watson.speech_to_text.v1.util;
import com.ibm.cloud.sdk.core.http.HttpMediaType;
import com.ibm.watson.speech_to_text.v1.SpeechToText;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* The utilities required for processing audio files using the {@link SpeechToText} service.
*
* @see SpeechToText
*/
public final class MediaTypeUtils {
private static final Map<String, String> MEDIA_TYPES;
static {
MEDIA_TYPES = new HashMap<String, String>();
MEDIA_TYPES.put(".wav", HttpMediaType.AUDIO_WAV);
MEDIA_TYPES.put(".ogg", HttpMediaType.AUDIO_OGG);
MEDIA_TYPES.put(".oga", HttpMediaType.AUDIO_OGG);
MEDIA_TYPES.put(".flac", HttpMediaType.AUDIO_FLAC);
MEDIA_TYPES.put(".raw", HttpMediaType.AUDIO_RAW);
MEDIA_TYPES.put(".mp3", HttpMediaType.AUDIO_MP3);
MEDIA_TYPES.put(".mpeg", HttpMediaType.AUDIO_MPEG);
MEDIA_TYPES.put(".webm", HttpMediaType.AUDIO_WEBM);
}
private MediaTypeUtils() {
// This is a utility class - no instantiation allowed.
}
/**
* Returns the media type for a given file.
*
* @param file the file object for which media type needs to be provided
* @return Internet media type for the file, or null if none found
*/
public static String getMediaTypeFromFile(final File file) {
if (file == null) {
return null;
}
final String fileName = file.getName();
final int i = fileName.lastIndexOf('.');
if (i == -1) {
return null;
}
return MEDIA_TYPES.get(fileName.substring(i).toLowerCase());
}
/**
* Checks if the media type is supported by the service.
*
* @param mediaType Internet media type for the file
* @return true if it is supported, false if not.
*/
public static boolean isValidMediaType(final String mediaType) {
return (mediaType != null) && MEDIA_TYPES.values().contains(mediaType.toLowerCase());
}
}
| apache-2.0 |
dagnir/aws-sdk-java | aws-java-sdk-cognitoidp/src/main/java/com/amazonaws/services/cognitoidp/model/DeviceRememberedStatusType.java | 1733 | /*
* 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.cognitoidp.model;
import javax.annotation.Generated;
/**
*
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum DeviceRememberedStatusType {
Remembered("remembered"),
Not_remembered("not_remembered");
private String value;
private DeviceRememberedStatusType(String value) {
this.value = value;
}
@Override
public String toString() {
return this.value;
}
/**
* Use this in place of valueOf.
*
* @param value
* real value
* @return DeviceRememberedStatusType corresponding to the value
*/
public static DeviceRememberedStatusType fromValue(String value) {
if (value == null || "".equals(value)) {
throw new IllegalArgumentException("Value cannot be null or empty!");
}
for (DeviceRememberedStatusType enumEntry : DeviceRememberedStatusType.values()) {
if (enumEntry.toString().equals(value)) {
return enumEntry;
}
}
throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
}
}
| apache-2.0 |
IBM-Bluemix/talent-manager | src/com/ibm/personafusion/InitDB.java | 337 | package com.ibm.personafusion;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import com.ibm.personafusion.db.CloudantClient;
public class InitDB extends HttpServlet {
public void init() throws ServletException {
System.out.println("Initalizing DB");
CloudantClient cc = new CloudantClient();
}
} | apache-2.0 |
SergiusIW/ton | src/main/java/com/matthewmichelotti/ton/internal/parser/nodes/ObjectNode.java | 1462 | /*
* Copyright 2015-2016 Matthew D. Michelotti
*
* 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.matthewmichelotti.ton.internal.parser.nodes;
import java.util.HashSet;
import java.util.LinkedHashMap;
import com.matthewmichelotti.ton.FileLoc;
import com.matthewmichelotti.ton.internal.NodeType;
public class ObjectNode extends ParentNode {
public String className;
public final LinkedHashMap<Object, Node> map = new LinkedHashMap<>();
public final HashSet<Object> checkedKeys = new HashSet<>();
private int index;
public ObjectNode(String className, FileLoc loc) {
super(NodeType.OBJECT, loc);
this.className = className;
}
public int getIndex() {
if(!hasIndex()) throw new IllegalStateException();
return index;
}
public void incIndex() {
if(!hasIndex()) throw new IllegalStateException();
index++;
}
public boolean hasIndex() {
return index >= 0;
}
public void destroyIndex() {
index = -1;
}
}
| apache-2.0 |
wangqi/gameserver | server/src/main/java/com/xinqihd/sns/gameserver/guild/GuildCraftType.java | 366 | package com.xinqihd.sns.gameserver.guild;
/**
* 公会铁匠铺的加成类型
*
* @author wangqi
*
*/
public enum GuildCraftType {
//装备合成
COMPOSE_EQUIP,
//石头升级
COMPOSE_STONE,
//颜色熔炼
COMPOSE_COLOR,
//装备强化
COMPOSE_STRENGTH,
//将石头合成到装备上
COMPOSE_EQUIP_WITH_STONE,
//装备转移
COMPOSE_TRANSFER,
}
| apache-2.0 |
jexp/idea2 | platform/platform-api/src/com/intellij/openapi/ui/ComboBoxWithWidePopup.java | 1510 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.ui;
import javax.swing.*;
import java.util.Vector;
import java.awt.*;
public class ComboBoxWithWidePopup extends JComboBox {
private boolean myLayingOut = false;
public ComboBoxWithWidePopup(final ComboBoxModel aModel) {
super(aModel);
}
public ComboBoxWithWidePopup(final Object items[]) {
super(items);
}
public ComboBoxWithWidePopup(final Vector<?> items) {
super(items);
}
public ComboBoxWithWidePopup() {
}
public void doLayout() {
try {
myLayingOut = true;
super.doLayout();
}
finally {
myLayingOut = false;
}
}
public Dimension getSize() {
Dimension size = super.getSize();
if (!myLayingOut) {
size.width = Math.max(size.width, getOriginalPreferredSize().width);
}
return size;
}
protected Dimension getOriginalPreferredSize() {
return getPreferredSize();
}
}
| apache-2.0 |
openpreserve/plato | minimee/src/main/java/at/tuwien/minimee/migration/parser/HPROF_Parser.java | 4372 | /*******************************************************************************
* Copyright 2006 - 2012 Vienna University of Technology,
* Department of Software Technology and Interactive Systems, IFS
*
* 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 at.tuwien.minimee.migration.parser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HPROF_Parser {
private Logger log = LoggerFactory.getLogger(this.getClass());
long total_virtual = 0;
long total_allocated = 0;
public HPROF_Parser() {
super();
}
public static void main(String args[]) {
HPROF_Parser hp_parser = new HPROF_Parser();
hp_parser
.parse("/home/riccardo/profilers/hprof/hprof_1_Image_0_2Mb.hprof");
System.out.println("Virtual:" + hp_parser.getTotal_virtual()
+ "MB Allocated: " + hp_parser.getTotal_allocated() + "MB");
}
/**
* Returns the Total Allocated Memory in MB
*
* @return
*/
public double getTotal_allocated() {
return (((double) total_allocated) / (1024 * 1024));
}
/**
* Returns the Total Virtual Memory in MB
*
* @return
*/
public double getTotal_virtual() {
return (((double) total_virtual) / (1024 * 1024));
}
public void parse(String fileToRead) {
try {
total_virtual = 0;
total_allocated = 0;
/*
* Sets up a file reader to read the file passed on the command line
* one character at a time
*/
FileReader input = new FileReader(fileToRead);
/*
* Filter FileReader through a Buffered read to read a line at a
* time
*/
try {
BufferedReader bufRead = new BufferedReader(input);
String line; // String that holds current file line
// Read first line
line = bufRead.readLine();
// Read through file one line at time. Print line # and line
while (line != null) {
if (line.contains(" rank self"))
break;
line = bufRead.readLine();
}
// read next line containing the first info
line = bufRead.readLine();
// begin parsing
while (line != null && line.compareTo("SITES END") != 0) {
interpretline(line);
line = bufRead.readLine();
}
} finally {
input.close();
}
} catch (IOException e) {
// If another exception is generated, print a stack trace
log.error("Failed to parse HPROF output " + fileToRead, e);
}
}// end main
private void interpretline(String line) {
char[] chars = new char[line.length()];
line.getChars(0, line.length() - 1, chars, 0);
String live_mem = "";
String alloc_mem = "";
int countWord = 0;
int wordEntered = 0;
for (char c : chars) {
if (c == ' ') {
wordEntered = 0;
continue;
}
if (wordEntered == 0)
countWord++;
wordEntered = 1;
if (countWord == 4)
live_mem += c;
else if (countWord == 6)
alloc_mem += c;
}
total_virtual = total_virtual + Long.parseLong(live_mem);
total_allocated = total_allocated + Long.parseLong(alloc_mem);
}
}
| apache-2.0 |
fabric8io/kubernetes-client | openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/BuildConfigOperationContext.java | 5111 | /**
* Copyright (C) 2015 Red Hat, 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.fabric8.openshift.client.dsl.internal;
import java.util.concurrent.TimeUnit;
public class BuildConfigOperationContext {
private String secret;
private String triggerType;
private String authorName;
private String authorEmail;
private String committerName;
private String committerEmail;
private String commit;
private String message;
private String asFile;
private long timeout;
private TimeUnit timeoutUnit = TimeUnit.MILLISECONDS;
public BuildConfigOperationContext() {
}
public BuildConfigOperationContext(String secret, String triggerType, String authorName, String authorEmail, String committerName, String committerEmail, String commit, String message, String asFile, Long timeout, TimeUnit timeUnit) {
this.secret = secret;
this.triggerType = triggerType;
this.authorName = authorName;
this.authorEmail = authorEmail;
this.committerName = committerName;
this.committerEmail = committerEmail;
this.commit = commit;
this.message = message;
this.asFile = asFile;
this.timeout = timeout;
this.timeoutUnit = timeUnit != null ? timeUnit : TimeUnit.MILLISECONDS;
}
public String getSecret() {
return secret;
}
public String getTriggerType() {
return triggerType;
}
public String getAuthorName() {
return authorName;
}
public String getAuthorEmail() {
return authorEmail;
}
public String getCommitterName() {
return committerName;
}
public String getCommitterEmail() {
return committerEmail;
}
public String getCommit() {
return commit;
}
public String getMessage() {
return message;
}
public String getAsFile() {
return asFile;
}
public long getTimeout() {
return timeout;
}
public TimeUnit getTimeoutUnit() {
return timeoutUnit;
}
public BuildConfigOperationContext withSecret(String secret) {
return new BuildConfigOperationContext(secret, triggerType, authorName, authorEmail, committerName, committerEmail, commit, message,asFile, timeout, timeoutUnit);
}
public BuildConfigOperationContext withTriggerType(String triggerType) {
return new BuildConfigOperationContext(secret, triggerType, authorName, authorEmail, committerName, committerEmail, commit, message,asFile, timeout, timeoutUnit);
}
public BuildConfigOperationContext withAuthorName(String authorName) {
return new BuildConfigOperationContext(secret, triggerType, authorName, authorEmail, committerName, committerEmail, commit, message,asFile, timeout, timeoutUnit);
}
public BuildConfigOperationContext withAuthorEmail(String authorEmail) {
return new BuildConfigOperationContext(secret, triggerType, authorName, authorEmail, committerName, committerEmail, commit, message,asFile, timeout, timeoutUnit);
}
public BuildConfigOperationContext withCommitterName(String committerName) {
return new BuildConfigOperationContext(secret, triggerType, authorName, authorEmail, committerName, committerEmail, commit, message,asFile, timeout, timeoutUnit);
}
public BuildConfigOperationContext withCommitterEmail(String committerEmail) {
return new BuildConfigOperationContext(secret, triggerType, authorName, authorEmail, committerName, committerEmail, commit, message,asFile, timeout, timeoutUnit);
}
public BuildConfigOperationContext withCommit(String commit) {
return new BuildConfigOperationContext(secret, triggerType, authorName, authorEmail, committerName, committerEmail, commit, message,asFile, timeout, timeoutUnit);
}
public BuildConfigOperationContext withMessage(String message) {
return new BuildConfigOperationContext(secret, triggerType, authorName, authorEmail, committerName, committerEmail, commit, message,asFile, timeout, timeoutUnit);
}
public BuildConfigOperationContext withAsFile(String asFile) {
return new BuildConfigOperationContext(secret, triggerType, authorName, authorEmail, committerName, committerEmail, commit, message,asFile, timeout, timeoutUnit);
}
public BuildConfigOperationContext withTimeout(long timeout) {
return new BuildConfigOperationContext(secret, triggerType, authorName, authorEmail, committerName, committerEmail, commit, message,asFile, timeout, timeoutUnit);
}
public BuildConfigOperationContext withTimeoutUnit(TimeUnit timeoutUnit) {
return new BuildConfigOperationContext(secret, triggerType, authorName, authorEmail, committerName, committerEmail, commit, message,asFile, timeout, timeoutUnit);
}
}
| apache-2.0 |
wanliwang/cayman | cm-idea/src/main/java/com/bjorktech/cayman/idea/datastructure/dynamic/ItemType.java | 700 | package com.bjorktech.cayman.idea.datastructure.dynamic;
import java.math.BigDecimal;
class ItemType {
public ItemType(BigDecimal amount, Integer count) {
super();
this.amount = amount;
this.count = count;
}
private BigDecimal amount;
private Integer count;
/**
* @return the amount
*/
public BigDecimal getAmount() {
return amount;
}
/**
* @param amount
* the amount to set
*/
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
/**
* @return the count
*/
public Integer getCount() {
return count;
}
/**
* @param count
* the count to set
*/
public void setCount(Integer count) {
this.count = count;
}
}
| apache-2.0 |
MyRobotLab/myrobotlab | src/main/java/org/myrobotlab/jme3/Search.java | 1088 | package org.myrobotlab.jme3;
import java.util.ArrayList;
import java.util.List;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.SceneGraphVisitor;
import com.jme3.scene.Spatial;
public class Search implements SceneGraphVisitor {
List<Spatial> results = new ArrayList<Spatial>();
String searchText;
boolean exactMatch;
boolean includeGeometries;
public Search(String searchText, boolean exactMatch, boolean includeGeometries) {
this.searchText = searchText;
this.exactMatch = exactMatch;
this.includeGeometries = includeGeometries;
}
@Override
public void visit(Spatial spatial) {
String name = spatial.getName();
if (name == null) {
return;
}
if (!exactMatch) {
if (name.toLowerCase().contains(searchText.toLowerCase())) {
if (spatial instanceof Node) {
results.add(spatial);
} else if (spatial instanceof Geometry && includeGeometries) {
results.add(spatial);
}
}
}
}
public List<Spatial> getResults() {
return results;
}
}
| apache-2.0 |
campa/tinvention-training-j2ee | parent-web-ejb/ejb/src/main/java/net/tinvention/training/ejb/mdb/ProducerBean.java | 1067 | /**
* Copyright Tinvention -Ingegneria Informatica- http://tinvention.net/ Licensed under the Apache
* License, Version 2.0 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package net.tinvention.training.ejb.mdb;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.jms.JMSContext;
import javax.jms.Queue;
@Stateless
public class ProducerBean {
@Resource(lookup = "jms/test")
private Queue queue;
@Inject
private JMSContext jmsContext;
public void send(ValueObject vo) {
jmsContext.createProducer().send(queue, vo);
}
}
| apache-2.0 |
xiaojinzi123/Component | Demo/Module1/src/main/java/com/xiaojinzi/component1/view/Test2Fragment.java | 552 | package com.xiaojinzi.component1.view;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import com.xiaojinzi.component.anno.FragmentAnno;
public class Test2Fragment extends Fragment {
@FragmentAnno(value = "test2Fragment")
public static Test2Fragment newInstance(@NonNull Bundle bundle) {
Bundle args = new Bundle();
args.putAll(bundle);
Test2Fragment fragment = new Test2Fragment();
fragment.setArguments(args);
return fragment;
}
}
| apache-2.0 |
codechix/CodeChix-Public-Repo | pytheas-helloworld/src/main/java/com/netflix/explorers/helloworld/resources/HelloWorldAppResource.java | 1292 | /**
* Copyright 2013 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 com.netflix.explorers.helloworld.resources;
import com.sun.jersey.api.view.Viewable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.HashMap;
import java.util.Map;
@Path("/")
public class HelloWorldAppResource {
private Logger LOG = LoggerFactory.getLogger(HelloWorldAppResource.class);
@GET
@Produces( MediaType.TEXT_HTML )
public Viewable showIndex()
{
LOG.info("home page");
Map<String, Object> model = new HashMap<String, Object>();
return new Viewable( "/helloworld/home.ftl", model );
}
} | apache-2.0 |
sjsucmpe275/fluffy | src/client/MultiClientRunner.java | 966 | /**
*
*/
package client;
import java.io.FileNotFoundException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* @author saurabh
*/
public class MultiClientRunner {
public static void main(String[] args) throws InterruptedException {
String[] params = new String[3];
params[0] = "get";
params[1] = "abcdeasdasd";
params[2] = "src/util/dump2.jpg";
Client client = new Client();
ExecutorService threadPool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
threadPool.execute(new Runnable() {
@Override
public void run() {
try {
client.handleCommand(params);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
}
threadPool.shutdown();
try {
threadPool.awaitTermination(100, TimeUnit.SECONDS);
client.releaseClient();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| apache-2.0 |
kaazing/java.client | ws/ws/src/test/java/org/kaazing/net/auth/ChallengeRequestTest.java | 3475 | /**
* Copyright 2007-2015, Kaazing Corporation. 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 org.kaazing.net.auth;
import org.kaazing.net.auth.ChallengeRequest;
import org.kaazing.net.impl.auth.RealmUtils;
import org.junit.Assert;
import org.junit.Test;
public class ChallengeRequestTest {
private static final String DEFAULT_LOCATION = "http://host.example.com/foo";
@Test(expected = NullPointerException.class)
public void testNullLocation() throws Exception {
new ChallengeRequest(null, null);
}
@Test
public void testNullChallenge() throws Exception {
ChallengeRequest challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, null);
Assert.assertNull(challengeRequest.getAuthenticationScheme());
Assert.assertNull(challengeRequest.getAuthenticationParameters());
}
@Test
public void testEmptyChallenge() throws Exception {
ChallengeRequest challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "");
Assert.assertEquals("", challengeRequest.getAuthenticationScheme());
Assert.assertNull(challengeRequest.getAuthenticationParameters());
}
@Test
public void testBasicChallenge() throws Exception {
ChallengeRequest challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "Basic");
Assert.assertEquals("Basic", challengeRequest.getAuthenticationScheme());
Assert.assertNull(challengeRequest.getAuthenticationParameters());
challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "Basic ");
Assert.assertEquals("Basic", challengeRequest.getAuthenticationScheme());
Assert.assertNull(challengeRequest.getAuthenticationParameters());
challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "Basic AuthData");
Assert.assertEquals("Basic", challengeRequest.getAuthenticationScheme());
Assert.assertEquals("AuthData", challengeRequest.getAuthenticationParameters());
}
@Test
public void testRealmParameter() throws Exception {
ChallengeRequest challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "Basic");
Assert.assertNull(RealmUtils.getRealm(challengeRequest));
challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "Basic realm=missingQuotes");
Assert.assertNull(RealmUtils.getRealm(challengeRequest));
challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "Basic realm=");
Assert.assertNull(RealmUtils.getRealm(challengeRequest));
challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "Basic realm=\"\"");
Assert.assertEquals("", RealmUtils.getRealm(challengeRequest));
challengeRequest = new ChallengeRequest(DEFAULT_LOCATION, "Basic realm=\"realmValue\"");
Assert.assertEquals("realmValue", RealmUtils.getRealm(challengeRequest));
}
}
| apache-2.0 |
ptahchiev/spring-boot | spring-boot-project/spring-boot-test/src/test/java/org/springframework/boot/test/context/runner/AbstractApplicationContextRunnerTests.java | 7362 | /*
* Copyright 2012-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 org.springframework.boot.test.context.runner;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import com.google.gson.Gson;
import org.junit.Test;
import org.springframework.boot.context.annotation.UserConfigurations;
import org.springframework.boot.test.context.FilteredClassLoader;
import org.springframework.boot.test.context.assertj.ApplicationContextAssertProvider;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.ClassUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIOException;
import static org.junit.Assert.fail;
/**
* Abstract tests for {@link AbstractApplicationContextRunner} implementations.
*
* @param <T> The runner type
* @param <C> the context type
* @param <A> the assertable context type
* @author Stephane Nicoll
* @author Phillip Webb
*/
public abstract class AbstractApplicationContextRunnerTests<T extends AbstractApplicationContextRunner<T, C, A>, C extends ConfigurableApplicationContext, A extends ApplicationContextAssertProvider<C>> {
@Test
public void runWithInitializerShouldInitialize() {
AtomicBoolean called = new AtomicBoolean();
get().withInitializer((context) -> called.set(true)).run((context) -> {
});
assertThat(called).isTrue();
}
@Test
public void runWithSystemPropertiesShouldSetAndRemoveProperties() {
String key = "test." + UUID.randomUUID();
assertThat(System.getProperties().containsKey(key)).isFalse();
get().withSystemProperties(key + "=value")
.run((context) -> assertThat(System.getProperties()).containsEntry(key,
"value"));
assertThat(System.getProperties().containsKey(key)).isFalse();
}
@Test
public void runWithSystemPropertiesWhenContextFailsShouldRemoveProperties() {
String key = "test." + UUID.randomUUID();
assertThat(System.getProperties().containsKey(key)).isFalse();
get().withSystemProperties(key + "=value")
.withUserConfiguration(FailingConfig.class)
.run((context) -> assertThat(context).hasFailed());
assertThat(System.getProperties().containsKey(key)).isFalse();
}
@Test
public void runWithSystemPropertiesShouldRestoreOriginalProperties() {
String key = "test." + UUID.randomUUID();
System.setProperty(key, "value");
try {
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
get().withSystemProperties(key + "=newValue")
.run((context) -> assertThat(System.getProperties())
.containsEntry(key, "newValue"));
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
}
finally {
System.clearProperty(key);
}
}
@Test
public void runWithSystemPropertiesWhenValueIsNullShouldRemoveProperty() {
String key = "test." + UUID.randomUUID();
System.setProperty(key, "value");
try {
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
get().withSystemProperties(key + "=")
.run((context) -> assertThat(System.getProperties())
.doesNotContainKey(key));
assertThat(System.getProperties().getProperty(key)).isEqualTo("value");
}
finally {
System.clearProperty(key);
}
}
@Test
public void runWithMultiplePropertyValuesShouldAllAllValues() {
get().withPropertyValues("test.foo=1").withPropertyValues("test.bar=2")
.run((context) -> {
Environment environment = context.getEnvironment();
assertThat(environment.getProperty("test.foo")).isEqualTo("1");
assertThat(environment.getProperty("test.bar")).isEqualTo("2");
});
}
@Test
public void runWithPropertyValuesWhenHasExistingShouldReplaceValue() {
get().withPropertyValues("test.foo=1").withPropertyValues("test.foo=2")
.run((context) -> {
Environment environment = context.getEnvironment();
assertThat(environment.getProperty("test.foo")).isEqualTo("2");
});
}
@Test
public void runWithConfigurationsShouldRegisterConfigurations() {
get().withUserConfiguration(FooConfig.class)
.run((context) -> assertThat(context).hasBean("foo"));
}
@Test
public void runWithMultipleConfigurationsShouldRegisterAllConfigurations() {
get().withUserConfiguration(FooConfig.class)
.withConfiguration(UserConfigurations.of(BarConfig.class))
.run((context) -> assertThat(context).hasBean("foo").hasBean("bar"));
}
@Test
public void runWithFailedContextShouldReturnFailedAssertableContext() {
get().withUserConfiguration(FailingConfig.class)
.run((context) -> assertThat(context).hasFailed());
}
@Test
public void runWithClassLoaderShouldSetClassLoaderOnContext() {
get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName()))
.run((context) -> {
try {
ClassUtils.forName(Gson.class.getName(),
context.getClassLoader());
fail("Should have thrown a ClassNotFoundException");
}
catch (ClassNotFoundException ex) {
// expected
}
});
}
@Test
public void runWithClassLoaderShouldSetClassLoaderOnConditionContext() {
get().withClassLoader(new FilteredClassLoader(Gson.class.getPackage().getName()))
.withUserConfiguration(ConditionalConfig.class)
.run((context) -> assertThat(context)
.hasSingleBean(ConditionalConfig.class));
}
@Test
public void thrownRuleWorksWithCheckedException() {
get().run((context) -> assertThatIOException()
.isThrownBy(() -> throwCheckedException("Expected message"))
.withMessageContaining("Expected message"));
}
protected abstract T get();
private static void throwCheckedException(String message) throws IOException {
throw new IOException(message);
}
@Configuration
static class FailingConfig {
@Bean
public String foo() {
throw new IllegalStateException("Failed");
}
}
@Configuration
static class FooConfig {
@Bean
public String foo() {
return "foo";
}
}
@Configuration
static class BarConfig {
@Bean
public String bar() {
return "bar";
}
}
@Configuration
@Conditional(FilteredClassLoaderCondition.class)
static class ConditionalConfig {
}
static class FilteredClassLoaderCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return context.getClassLoader() instanceof FilteredClassLoader;
}
}
}
| apache-2.0 |
is-m/simba | simba-common/src/main/java/cn/ism/fw/simba/base/dao/IBaseDao.java | 1364 | package cn.ism.fw.simba.base.dao;
import java.util.List;
import cn.ism.fw.simba.base.PageVO;
import cn.ism.fw.simba.base.PagedResult;
/**
* 通用dao
* @since 2017年12月24日
* @author Administrator
*/
public interface IBaseDao<T,K> {
/**
* 创建对象
* @param t
* @return
* @since 2017年12月24日
* @author Administrator
*/
public T create(T t);
/**
* 删除对象
* @param t
* @return
* @since 2017年12月24日
* @author Administrator
*/
public int delete(K k);
/**
* 更新对象
* @param t
* @return
* @since 2017年12月24日
* @author Administrator
*/
public T update(T t);
/**
* 保存对象,不存在创建,存在更新
* @param t
* @return
* @since 2017年12月24日
* @author Administrator
*/
public T save(T t);
/**
* 根据主键获取
* @param k
* @since 2017年12月24日
* @author Administrator
*/
public T getOne(K k);
/**
* 按条件分页查询
* @param page
* @param condition
* @return
* @since 2017年12月24日
* @author Administrator
*/
public PagedResult<T> getPageData(PageVO page,T condition);
/**
* 按条件查询所有
* @param condition
* @return
* @since 2017年12月24日
* @author Administrator
*/
public List<T> getAll(T condition);
}
| apache-2.0 |