repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
googleapis/java-bigquerystorage | google-cloud-bigquerystorage/src/test/java/com/google/cloud/bigquery/storage/v1beta2/StreamWriterV2Test.java | 19575 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.bigquery.storage.v1beta2;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import com.google.api.core.ApiFuture;
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.testing.MockGrpcService;
import com.google.api.gax.grpc.testing.MockServiceHelper;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.StatusCode.Code;
import com.google.cloud.bigquery.storage.test.Test.FooType;
import com.google.common.base.Strings;
import com.google.protobuf.DescriptorProtos;
import com.google.protobuf.Int64Value;
import io.grpc.Status;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.function.ThrowingRunnable;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.threeten.bp.Duration;
@RunWith(JUnit4.class)
public class StreamWriterV2Test {
private static final Logger log = Logger.getLogger(StreamWriterV2Test.class.getName());
private static final String TEST_STREAM = "projects/p/datasets/d/tables/t/streams/s";
private static final String TEST_TRACE_ID = "DATAFLOW:job_id";
private FakeScheduledExecutorService fakeExecutor;
private FakeBigQueryWrite testBigQueryWrite;
private static MockServiceHelper serviceHelper;
private BigQueryWriteClient client;
@Before
public void setUp() throws Exception {
testBigQueryWrite = new FakeBigQueryWrite();
serviceHelper =
new MockServiceHelper(
UUID.randomUUID().toString(), Arrays.<MockGrpcService>asList(testBigQueryWrite));
serviceHelper.start();
fakeExecutor = new FakeScheduledExecutorService();
testBigQueryWrite.setExecutor(fakeExecutor);
client =
BigQueryWriteClient.create(
BigQueryWriteSettings.newBuilder()
.setCredentialsProvider(NoCredentialsProvider.create())
.setTransportChannelProvider(serviceHelper.createChannelProvider())
.build());
}
@After
public void tearDown() throws Exception {
log.info("tearDown called");
client.close();
serviceHelper.stop();
}
private StreamWriterV2 getTestStreamWriterV2() throws IOException {
return StreamWriterV2.newBuilder(TEST_STREAM, client)
.setWriterSchema(createProtoSchema())
.setTraceId(TEST_TRACE_ID)
.build();
}
private ProtoSchema createProtoSchema() {
return ProtoSchema.newBuilder()
.setProtoDescriptor(
DescriptorProtos.DescriptorProto.newBuilder()
.setName("Message")
.addField(
DescriptorProtos.FieldDescriptorProto.newBuilder()
.setName("foo")
.setType(DescriptorProtos.FieldDescriptorProto.Type.TYPE_STRING)
.setNumber(1)
.build())
.build())
.build();
}
private ProtoRows createProtoRows(String[] messages) {
ProtoRows.Builder rowsBuilder = ProtoRows.newBuilder();
for (String message : messages) {
FooType foo = FooType.newBuilder().setFoo(message).build();
rowsBuilder.addSerializedRows(foo.toByteString());
}
return rowsBuilder.build();
}
private AppendRowsResponse createAppendResponse(long offset) {
return AppendRowsResponse.newBuilder()
.setAppendResult(
AppendRowsResponse.AppendResult.newBuilder().setOffset(Int64Value.of(offset)).build())
.build();
}
private AppendRowsResponse createAppendResponseWithError(Status.Code code, String message) {
return AppendRowsResponse.newBuilder()
.setError(com.google.rpc.Status.newBuilder().setCode(code.value()).setMessage(message))
.build();
}
private ApiFuture<AppendRowsResponse> sendTestMessage(StreamWriterV2 writer, String[] messages) {
return writer.append(createProtoRows(messages), -1);
}
private static <T extends Throwable> T assertFutureException(
Class<T> expectedThrowable, final Future<?> future) {
return assertThrows(
expectedThrowable,
new ThrowingRunnable() {
@Override
public void run() throws Throwable {
try {
future.get();
} catch (ExecutionException ex) {
// Future wraps exception with ExecutionException. So unwrapper it here.
throw ex.getCause();
}
}
});
}
private void verifyAppendIsBlocked(final StreamWriterV2 writer) throws Exception {
Thread appendThread =
new Thread(
new Runnable() {
@Override
public void run() {
sendTestMessage(writer, new String[] {"A"});
}
});
// Start a separate thread to append and verify that it is still alive after 2 seoncds.
appendThread.start();
TimeUnit.SECONDS.sleep(2);
assertTrue(appendThread.isAlive());
appendThread.interrupt();
}
private void verifyAppendRequests(long appendCount) {
assertEquals(appendCount, testBigQueryWrite.getAppendRequests().size());
for (int i = 0; i < appendCount; i++) {
AppendRowsRequest serverRequest = testBigQueryWrite.getAppendRequests().get(i);
assertTrue(serverRequest.getProtoRows().getRows().getSerializedRowsCount() > 0);
assertEquals(i, serverRequest.getOffset().getValue());
if (i == 0) {
// First request received by server should have schema and stream name.
assertTrue(serverRequest.getProtoRows().hasWriterSchema());
assertEquals(serverRequest.getWriteStream(), TEST_STREAM);
assertEquals(serverRequest.getTraceId(), TEST_TRACE_ID);
} else {
// Following request should not have schema and stream name.
assertFalse(serverRequest.getProtoRows().hasWriterSchema());
assertEquals(serverRequest.getWriteStream(), "");
assertEquals(serverRequest.getTraceId(), "");
}
}
}
@Test
public void testBuildBigQueryWriteClientInWriter() throws Exception {
StreamWriterV2 writer =
StreamWriterV2.newBuilder(TEST_STREAM)
.setCredentialsProvider(NoCredentialsProvider.create())
.setChannelProvider(serviceHelper.createChannelProvider())
.setWriterSchema(createProtoSchema())
.build();
testBigQueryWrite.addResponse(createAppendResponse(0));
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
assertEquals(0, appendFuture1.get().getAppendResult().getOffset().getValue());
writer.close();
}
@Test
public void testAppendSuccess() throws Exception {
StreamWriterV2 writer = getTestStreamWriterV2();
long appendCount = 100;
for (int i = 0; i < appendCount; i++) {
testBigQueryWrite.addResponse(createAppendResponse(i));
}
List<ApiFuture<AppendRowsResponse>> futures = new ArrayList<>();
for (int i = 0; i < appendCount; i++) {
futures.add(writer.append(createProtoRows(new String[] {String.valueOf(i)}), i));
}
for (int i = 0; i < appendCount; i++) {
assertEquals(i, futures.get(i).get().getAppendResult().getOffset().getValue());
}
verifyAppendRequests(appendCount);
writer.close();
}
@Test
public void testNoSchema() throws Exception {
StatusRuntimeException ex =
assertThrows(
StatusRuntimeException.class,
new ThrowingRunnable() {
@Override
public void run() throws Throwable {
StreamWriterV2.newBuilder(TEST_STREAM, client).build();
}
});
assertEquals(ex.getStatus().getCode(), Status.INVALID_ARGUMENT.getCode());
assertTrue(ex.getStatus().getDescription().contains("Writer schema must be provided"));
}
@Test
public void testInvalidTraceId() throws Exception {
assertThrows(
IllegalArgumentException.class,
new ThrowingRunnable() {
@Override
public void run() throws Throwable {
StreamWriterV2.newBuilder(TEST_STREAM).setTraceId("abc");
}
});
assertThrows(
IllegalArgumentException.class,
new ThrowingRunnable() {
@Override
public void run() throws Throwable {
StreamWriterV2.newBuilder(TEST_STREAM).setTraceId("abc:");
}
});
assertThrows(
IllegalArgumentException.class,
new ThrowingRunnable() {
@Override
public void run() throws Throwable {
StreamWriterV2.newBuilder(TEST_STREAM).setTraceId(":abc");
}
});
}
@Test
public void testAppendSuccessAndConnectionError() throws Exception {
StreamWriterV2 writer = getTestStreamWriterV2();
testBigQueryWrite.addResponse(createAppendResponse(0));
testBigQueryWrite.addException(Status.INTERNAL.asException());
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
ApiFuture<AppendRowsResponse> appendFuture2 = sendTestMessage(writer, new String[] {"B"});
assertEquals(0, appendFuture1.get().getAppendResult().getOffset().getValue());
ApiException actualError = assertFutureException(ApiException.class, appendFuture2);
assertEquals(Code.INTERNAL, actualError.getStatusCode().getCode());
writer.close();
}
@Test
public void testAppendSuccessAndInStreamError() throws Exception {
StreamWriterV2 writer = getTestStreamWriterV2();
testBigQueryWrite.addResponse(createAppendResponse(0));
testBigQueryWrite.addResponse(
createAppendResponseWithError(Status.INVALID_ARGUMENT.getCode(), "test message"));
testBigQueryWrite.addResponse(createAppendResponse(1));
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
ApiFuture<AppendRowsResponse> appendFuture2 = sendTestMessage(writer, new String[] {"B"});
ApiFuture<AppendRowsResponse> appendFuture3 = sendTestMessage(writer, new String[] {"C"});
assertEquals(0, appendFuture1.get().getAppendResult().getOffset().getValue());
StatusRuntimeException actualError =
assertFutureException(StatusRuntimeException.class, appendFuture2);
assertEquals(Status.Code.INVALID_ARGUMENT, actualError.getStatus().getCode());
assertEquals("test message", actualError.getStatus().getDescription());
assertEquals(1, appendFuture3.get().getAppendResult().getOffset().getValue());
writer.close();
}
@Test
public void longIdleBetweenAppends() throws Exception {
StreamWriterV2 writer = getTestStreamWriterV2();
testBigQueryWrite.addResponse(createAppendResponse(0));
testBigQueryWrite.addResponse(createAppendResponse(1));
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
assertEquals(0, appendFuture1.get().getAppendResult().getOffset().getValue());
// Sleep to create a long idle between appends.
TimeUnit.SECONDS.sleep(3);
ApiFuture<AppendRowsResponse> appendFuture2 = sendTestMessage(writer, new String[] {"B"});
assertEquals(1, appendFuture2.get().getAppendResult().getOffset().getValue());
writer.close();
}
@Test
public void testAppendAfterUserClose() throws Exception {
StreamWriterV2 writer = getTestStreamWriterV2();
testBigQueryWrite.addResponse(createAppendResponse(0));
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
writer.close();
ApiFuture<AppendRowsResponse> appendFuture2 = sendTestMessage(writer, new String[] {"B"});
assertEquals(0, appendFuture1.get().getAppendResult().getOffset().getValue());
assertTrue(appendFuture2.isDone());
StatusRuntimeException actualError =
assertFutureException(StatusRuntimeException.class, appendFuture2);
assertEquals(Status.Code.FAILED_PRECONDITION, actualError.getStatus().getCode());
}
@Test
public void testAppendAfterServerClose() throws Exception {
StreamWriterV2 writer = getTestStreamWriterV2();
testBigQueryWrite.addException(Status.INTERNAL.asException());
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
ApiException error1 = assertFutureException(ApiException.class, appendFuture1);
assertEquals(Code.INTERNAL, error1.getStatusCode().getCode());
ApiFuture<AppendRowsResponse> appendFuture2 = sendTestMessage(writer, new String[] {"B"});
assertTrue(appendFuture2.isDone());
StatusRuntimeException error2 =
assertFutureException(StatusRuntimeException.class, appendFuture2);
assertEquals(Status.Code.FAILED_PRECONDITION, error2.getStatus().getCode());
writer.close();
}
@Test
public void userCloseWhileRequestInflight() throws Exception {
final StreamWriterV2 writer = getTestStreamWriterV2();
// Server will sleep 2 seconds before sending back the response.
testBigQueryWrite.setResponseSleep(Duration.ofSeconds(2));
testBigQueryWrite.addResponse(createAppendResponse(0));
// Send a request and close the stream in separate thread while the request is inflight.
final ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
Thread closeThread =
new Thread(
new Runnable() {
@Override
public void run() {
writer.close();
}
});
closeThread.start();
// Due to the sleep on server, the append won't finish within 1 second even though stream
// is being closed.
assertThrows(
TimeoutException.class,
new ThrowingRunnable() {
@Override
public void run() throws Throwable {
appendFuture1.get(1, TimeUnit.SECONDS);
}
});
// Within 2 seconds, the request should be done and stream should be closed.
closeThread.join(2000);
assertTrue(appendFuture1.isDone());
assertEquals(0, appendFuture1.get().getAppendResult().getOffset().getValue());
}
@Test
public void serverCloseWhileRequestsInflight() throws Exception {
StreamWriterV2 writer = getTestStreamWriterV2();
// Server will sleep 2 seconds before closing the connection.
testBigQueryWrite.setResponseSleep(Duration.ofSeconds(2));
testBigQueryWrite.addException(Status.INTERNAL.asException());
// Send 10 requests, so that there are 10 inflight requests.
int appendCount = 10;
List<ApiFuture<AppendRowsResponse>> futures = new ArrayList<>();
for (int i = 0; i < appendCount; i++) {
futures.add(sendTestMessage(writer, new String[] {String.valueOf(i)}));
}
// Server close should properly handle all inflight requests.
for (int i = 0; i < appendCount; i++) {
ApiException actualError = assertFutureException(ApiException.class, futures.get(i));
assertEquals(Code.INTERNAL, actualError.getStatusCode().getCode());
}
writer.close();
}
@Test
public void testZeroMaxInflightRequests() throws Exception {
StreamWriterV2 writer =
StreamWriterV2.newBuilder(TEST_STREAM, client)
.setWriterSchema(createProtoSchema())
.setMaxInflightRequests(0)
.build();
testBigQueryWrite.addResponse(createAppendResponse(0));
verifyAppendIsBlocked(writer);
writer.close();
}
@Test
public void testZeroMaxInflightBytes() throws Exception {
StreamWriterV2 writer =
StreamWriterV2.newBuilder(TEST_STREAM, client)
.setWriterSchema(createProtoSchema())
.setMaxInflightBytes(0)
.build();
testBigQueryWrite.addResponse(createAppendResponse(0));
verifyAppendIsBlocked(writer);
writer.close();
}
@Test
public void testOneMaxInflightRequests() throws Exception {
StreamWriterV2 writer =
StreamWriterV2.newBuilder(TEST_STREAM, client)
.setWriterSchema(createProtoSchema())
.setMaxInflightRequests(1)
.build();
// Server will sleep 1 second before every response.
testBigQueryWrite.setResponseSleep(Duration.ofSeconds(1));
testBigQueryWrite.addResponse(createAppendResponse(0));
long appendStartTimeMs = System.currentTimeMillis();
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {"A"});
long appendElapsedMs = System.currentTimeMillis() - appendStartTimeMs;
assertTrue(appendElapsedMs >= 1000);
assertEquals(0, appendFuture1.get().getAppendResult().getOffset().getValue());
writer.close();
}
@Test
public void testAppendsWithTinyMaxInflightBytes() throws Exception {
StreamWriterV2 writer =
StreamWriterV2.newBuilder(TEST_STREAM, client)
.setWriterSchema(createProtoSchema())
.setMaxInflightBytes(1)
.build();
// Server will sleep 100ms before every response.
testBigQueryWrite.setResponseSleep(Duration.ofMillis(100));
long appendCount = 10;
for (int i = 0; i < appendCount; i++) {
testBigQueryWrite.addResponse(createAppendResponse(i));
}
List<ApiFuture<AppendRowsResponse>> futures = new ArrayList<>();
long appendStartTimeMs = System.currentTimeMillis();
for (int i = 0; i < appendCount; i++) {
futures.add(writer.append(createProtoRows(new String[] {String.valueOf(i)}), i));
}
long appendElapsedMs = System.currentTimeMillis() - appendStartTimeMs;
assertTrue(appendElapsedMs >= 1000);
for (int i = 0; i < appendCount; i++) {
assertEquals(i, futures.get(i).get().getAppendResult().getOffset().getValue());
}
assertEquals(appendCount, testBigQueryWrite.getAppendRequests().size());
for (int i = 0; i < appendCount; i++) {
assertEquals(i, testBigQueryWrite.getAppendRequests().get(i).getOffset().getValue());
}
writer.close();
}
@Test
public void testMessageTooLarge() throws Exception {
StreamWriterV2 writer = getTestStreamWriterV2();
String oversized = Strings.repeat("a", (int) (StreamWriterV2.getApiMaxRequestBytes() + 1));
ApiFuture<AppendRowsResponse> appendFuture1 = sendTestMessage(writer, new String[] {oversized});
assertTrue(appendFuture1.isDone());
StatusRuntimeException actualError =
assertFutureException(StatusRuntimeException.class, appendFuture1);
assertEquals(Status.Code.INVALID_ARGUMENT, actualError.getStatus().getCode());
assertTrue(actualError.getStatus().getDescription().contains("MessageSize is too large"));
writer.close();
}
}
| apache-2.0 |
cash1981/civilization-boardgame-rest | src/main/java/no/asgari/civilization/server/resource/AdminResource.java | 5169 | /*
* Copyright (c) 2015 Shervin Asgari
* 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 no.asgari.civilization.server.resource;
import com.mongodb.DB;
import io.dropwizard.auth.Auth;
import lombok.extern.log4j.Log4j;
import no.asgari.civilization.server.action.AdminAction;
import no.asgari.civilization.server.action.GameAction;
import no.asgari.civilization.server.model.Player;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
/**
* Resource for admin stuff
*/
@Path("admin")
@Log4j
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class AdminResource {
private final GameAction gameAction;
private final AdminAction adminAction;
@Context
private UriInfo uriInfo;
public AdminResource(DB db) {
gameAction = new GameAction(db);
adminAction = new AdminAction(db);
}
/**
* Since this will go in production, for now only I am allowed to change this
*
* @param admin
* @param gameid
*/
@Path("/changeuser")
@POST
//public Response changeUserForGame(@Auth Player admin, @QueryParam("gameid") String gameid,
public Response changeUserForGame(@QueryParam("gameid") String gameid,
@QueryParam("fromUsername") String fromUsername,
@QueryParam("toUsername") String toUsername) {
/* if (!admin.getUsername().equals("admin")) {
return Response.status(Response.Status.FORBIDDEN).build();
}
*/
gameAction.changeUserFromExistingGame(gameid, fromUsername, toUsername);
return Response.ok().build();
}
/**
* Since this will go in production, for now only I am allowed to change this
*
* @param admin
* @param gameid
*/
@Path("/deletegame")
@POST
public Response deleteGame(@Auth Player admin, @QueryParam("gameid") String gameid) {
if (!"admin".equals(admin.getUsername())) {
return Response.status(Response.Status.FORBIDDEN).build();
}
boolean deleted = gameAction.deleteGame(gameid);
if (deleted) return Response.ok().build();
return Response.status(Response.Status.NOT_MODIFIED).build();
}
@Path("/email/notification/{playerId}/stop")
@GET
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.TEXT_PLAIN)
public Response stopEmail(@PathParam("playerId") String playerId) {
boolean yes = gameAction.disableEmailForPlayer(playerId);
if (yes) {
String startEmailUrl = uriInfo.getAbsolutePath().toString().replaceAll("stop", "start");
return Response.ok().entity(
"<html><body>" +
"<h1>You will no longer get anymore emails. Don't forget to check in once in a while</h1> " +
"If you reconsider and want to get emails again, then push <a href=\""
+ startEmailUrl + "\">here</a>" +
"</body></html>")
.build();
} else {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
@Path("/email/notification/{playerId}/start")
@GET
@Produces(MediaType.TEXT_HTML)
@Consumes(MediaType.TEXT_PLAIN)
public Response startEmail(@PathParam("playerId") String playerId) {
boolean yes = gameAction.startEmailForPlayer(playerId);
if (yes) {
return Response.ok().entity(
"<h1>Your email has started again</h1>")
.build();
} else {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
@Path("/cleanup")
@POST
public void deleteUnusedLogs() {
adminAction.cleanup();
}
@PUT
@Path("/mail")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response sendMail(@QueryParam("msg") String msg) {
//gameAction.sendMailToAll(msg);
return Response.noContent().build();
}
@POST
@Path("/taketurn")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public void takeTurn(@QueryParam("gameid") String gameid,
@QueryParam("username") String fromUsername) {
gameAction.takeTurn(gameid, fromUsername);
}
}
| apache-2.0 |
DimensionDataCBUSydney/dimensiondata-cloud-java-client | src/main/java/com/dimensiondata/cloud/client/http/NotFoundException.java | 262 | package com.dimensiondata.cloud.client.http;
import com.dimensiondata.cloud.client.ClientRuntimeException;
public class NotFoundException extends ClientRuntimeException
{
public NotFoundException()
{
super("Unknown resource");
}
} | apache-2.0 |
cpollet/jixture | core/src/test/java/net/cpollet/jixture/fixtures/transformers/TestFileFixtureTransformer.java | 5299 | /*
* Copyright 2014 Christophe Pollet
*
* 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.cpollet.jixture.fixtures.transformers;
import net.cpollet.jixture.fixtures.FileFixture;
import net.cpollet.jixture.fixtures.Fixture;
import net.cpollet.jixture.fixtures.ObjectFixture;
import net.cpollet.jixture.fixtures.capacities.filtering.FilterableFixtureProxy;
import net.cpollet.jixture.helper.MappingBuilder;
import net.cpollet.jixture.helper.MappingBuilderFactory;
import net.cpollet.jixture.helper.MappingDefinitionHolder;
import net.cpollet.jixture.helper.MappingField;
import net.cpollet.jixture.tests.mappings.CartEntry;
import net.cpollet.jixture.tests.mappings.PersistentObject;
import net.cpollet.jixture.tests.mappings.Product;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.util.NumberUtils;
import static org.fest.assertions.Assertions.assertThat;
/**
* @author Christophe Pollet
*/
@RunWith(MockitoJUnitRunner.class)
public abstract class TestFileFixtureTransformer {
@Mock
private ConversionServiceFactoryBean conversionServiceFactoryBean;
@Mock
private MappingDefinitionHolder mappingDefinitionHolder;
@Mock
private MappingBuilderFactory mappingBuilderFactory;
@Before
public void setUp() throws NoSuchFieldException {
GenericConversionService genericConversionService = new GenericConversionService();
genericConversionService.addConverter(new Converter<String, Integer>() {
@Override
public Integer convert(String source) {
if (0 == source.length()) {
return null;
}
return NumberUtils.parseNumber(source, Integer.class);
}
});
Mockito.when(conversionServiceFactoryBean.getObject()).thenReturn(genericConversionService);
mockCartEntry();
mockProduct();
}
private void mockCartEntry() throws NoSuchFieldException {
Mockito.when(mappingDefinitionHolder.getMappingClassByTableName("cart_entry")).thenReturn(CartEntry.class);
Mockito.when(mappingDefinitionHolder.getMappingFieldByTableAndColumnNames("cart_entry", "client_id"))//
.thenReturn(new MappingField(CartEntry.class.getDeclaredField("pk"), CartEntry.CartEntryPk.class.getDeclaredField("clientId")));
Mockito.when(mappingDefinitionHolder.getMappingFieldByTableAndColumnNames("cart_entry", "product_id"))//
.thenReturn(new MappingField(CartEntry.class.getDeclaredField("pk"), CartEntry.CartEntryPk.class.getDeclaredField("productId")));
Mockito.when(mappingDefinitionHolder.getMappingFieldByTableAndColumnNames("cart_entry", "count"))//
.thenReturn(new MappingField(CartEntry.class.getDeclaredField("count")));
MappingBuilder cartEntryMappingBuilder = MappingBuilder.createMapping("CART_ENTRY", mappingDefinitionHolder, conversionServiceFactoryBean.getObject());
Mockito.when(mappingBuilderFactory.create("CART_ENTRY"))//
.thenReturn(cartEntryMappingBuilder);
}
private void mockProduct() throws NoSuchFieldException {
Mockito.when(mappingDefinitionHolder.getMappingClassByTableName("product")).thenReturn(Product.class);
Mockito.when(mappingDefinitionHolder.getMappingFieldByTableAndColumnNames("product", "id"))//
.thenReturn(new MappingField(PersistentObject.class.getDeclaredField("id")));
Mockito.when(mappingDefinitionHolder.getMappingFieldByTableAndColumnNames("product", "name"))//
.thenReturn(new MappingField(Product.class.getDeclaredField("name")));
MappingBuilder productMappingBuilder = MappingBuilder.createMapping("product", mappingDefinitionHolder, conversionServiceFactoryBean.getObject());
Mockito.when(mappingBuilderFactory.create("product"))//
.thenReturn(productMappingBuilder);
}
protected void assertCorrectCartEntry(FileFixture fileFixture, ObjectFixture transformedFixture) {
assertThat(transformedFixture).isInstanceOf(Fixture.class);
assertThat(transformedFixture.getObjects()).hasSize(1);
assertThat(transformedFixture.getObjects().get(0)).isInstanceOf(CartEntry.class);
CartEntry actualCartEntry = (CartEntry) transformedFixture.getObjects().get(0);
CartEntry expectedCartEntry = new CartEntry();
expectedCartEntry.setPk(new CartEntry.CartEntryPk());
expectedCartEntry.getPk().setClientId(1);
expectedCartEntry.getPk().setProductId(2);
expectedCartEntry.setCount(10);
assertThat(actualCartEntry).isEqualTo(expectedCartEntry);
assertThat(fileFixture.getExtractionResult().getEntities()).hasSize(1);
assertThat(FilterableFixtureProxy.get(transformedFixture).filter("")).isFalse();
}
}
| apache-2.0 |
zoozooll/MyExercise | meep/MeepMovie/src/com/oregonscientific/meep/movie/SdCardOnchangeReceiver.java | 784 | package com.oregonscientific.meep.movie;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* @author aaronli
*
*/
public class SdCardOnchangeReceiver extends BroadcastReceiver {
private static DataSourceManager DataSourceManager;
/* (non-Javadoc)
* @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
*/
@Override
public void onReceive(Context context, Intent intent) {
//Log.d(this.getClass().getSimpleName(), context+" broadcast receive "+intent.getAction());
if (DataSourceManager == null) {
DataSourceManager = new DataSourceManager(context);
}
Log.e("cdf","video is changed");
DataSourceManager.getAllItems(true);
}
}
| apache-2.0 |
mano-mykingdom/titanium_mobile | android/modules/ui/src/java/ti/modules/titanium/ui/widget/listview/ListSectionProxy.java | 23756 | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
package ti.modules.titanium.ui.widget.listview;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.proxy.TiViewProxy;
import org.appcelerator.titanium.util.TiConvert;
import org.appcelerator.titanium.view.TiCompositeLayout;
import org.appcelerator.titanium.view.TiUIView;
import ti.modules.titanium.ui.UIModule;
import ti.modules.titanium.ui.ViewProxy;
import ti.modules.titanium.ui.widget.listview.TiListView.TiBaseAdapter;
import ti.modules.titanium.ui.widget.listview.TiListViewTemplate.DataItem;
import android.app.Activity;
import android.view.View;
@Kroll.proxy(creatableInModule = UIModule.class, propertyAccessors = {})
public class ListSectionProxy extends ViewProxy
{
private static final String TAG = "ListSectionProxy";
private ArrayList<ListItemData> listItemData;
private int itemCount;
private TiBaseAdapter adapter;
private ArrayList<Object> itemProperties;
private ArrayList<Integer> filterIndices;
private boolean preload;
private String headerTitle;
private String footerTitle;
private TiViewProxy headerView;
private TiViewProxy footerView;
private WeakReference<TiListView> listView;
public TiDefaultListViewTemplate builtInTemplate;
public class ListItemData
{
private KrollDict properties;
private TiListViewTemplate template;
private String searchableText = "";
public ListItemData(KrollDict properties, TiListViewTemplate template)
{
this.properties = properties;
this.template = template;
//set searchableText
if (properties.containsKey(TiC.PROPERTY_PROPERTIES)) {
Object props = properties.get(TiC.PROPERTY_PROPERTIES);
if (props instanceof HashMap) {
HashMap<String, Object> propsHash = (HashMap<String, Object>) props;
Object searchText = propsHash.get(TiC.PROPERTY_SEARCHABLE_TEXT);
if (propsHash.containsKey(TiC.PROPERTY_SEARCHABLE_TEXT) && searchText != null) {
searchableText = TiConvert.toString(searchText);
}
}
}
}
public KrollDict getProperties()
{
return properties;
}
public String getSearchableText()
{
return searchableText;
}
public TiListViewTemplate getTemplate()
{
return template;
}
}
public ListSectionProxy()
{
//initialize variables
listItemData = new ArrayList<ListItemData>();
filterIndices = new ArrayList<Integer>();
itemCount = 0;
preload = false;
}
public void handleCreationDict(KrollDict dict)
{
//getting header/footer titles from creation dictionary
if (dict.containsKey(TiC.PROPERTY_HEADER_TITLE)) {
headerTitle = TiConvert.toString(dict, TiC.PROPERTY_HEADER_TITLE);
}
if (dict.containsKey(TiC.PROPERTY_FOOTER_TITLE)) {
footerTitle = TiConvert.toString(dict, TiC.PROPERTY_FOOTER_TITLE);
}
if (dict.containsKey(TiC.PROPERTY_HEADER_VIEW)) {
Object obj = dict.get(TiC.PROPERTY_HEADER_VIEW);
if (obj instanceof TiViewProxy) {
headerView = (TiViewProxy) obj;
}
}
if (dict.containsKey(TiC.PROPERTY_FOOTER_VIEW)) {
Object obj = dict.get(TiC.PROPERTY_FOOTER_VIEW);
if (obj instanceof TiViewProxy) {
footerView = (TiViewProxy) obj;
}
}
if (dict.containsKey(TiC.PROPERTY_ITEMS)) {
handleSetItems(dict.get(TiC.PROPERTY_ITEMS));
}
}
public void setAdapter(TiBaseAdapter a)
{
adapter = a;
}
// clang-format off
@Kroll.method
@Kroll.setProperty
public void setHeaderView(TiViewProxy headerView)
// clang-format on
{
this.headerView = headerView;
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
// clang-format off
@Kroll.method
@Kroll.getProperty
public TiViewProxy getHeaderView()
// clang-format on
{
return headerView;
}
// clang-format off
@Kroll.method
@Kroll.setProperty
public void setFooterView(TiViewProxy footerView)
// clang-format on
{
handleSetFooterView(footerView);
}
// clang-format off
@Kroll.method
@Kroll.getProperty
public TiViewProxy getFooterView()
// clang-format on
{
return footerView;
}
// clang-format off
@Kroll.method
@Kroll.setProperty
public void setHeaderTitle(String headerTitle)
// clang-format on
{
handleSetHeaderTitle(headerTitle);
}
// clang-format off
@Kroll.method
@Kroll.getProperty
public String getHeaderTitle()
// clang-format on
{
return headerTitle;
}
// clang-format off
@Kroll.method
@Kroll.setProperty
public void setFooterTitle(String footerTitle)
// clang-format on
{
handleSetFooterTitle(footerTitle);
}
// clang-format off
@Kroll.method
@Kroll.getProperty
public String getFooterTitle()
// clang-format on
{
return footerTitle;
}
public String getHeaderOrFooterTitle(int index)
{
if (isHeaderTitle(index)) {
return headerTitle;
} else if (isFooterTitle(index)) {
return footerTitle;
}
return "";
}
public View getHeaderOrFooterView(int index)
{
if (isHeaderView(index)) {
return getListView().layoutHeaderOrFooterView(headerView);
} else if (isFooterView(index)) {
return getListView().layoutHeaderOrFooterView(footerView);
}
return null;
}
@Kroll.method
public KrollDict getItemAt(int index)
{
if (itemProperties != null && index >= 0 && index < itemProperties.size()) {
return new KrollDict((HashMap) itemProperties.get(index));
}
return null;
}
// clang-format off
@Kroll.method
@Kroll.setProperty
public void setItems(Object data)
// clang-format on
{
handleSetItems(data);
}
// clang-format off
@Kroll.method
@Kroll.getProperty
public Object[] getItems()
// clang-format on
{
if (itemProperties == null) {
return new Object[0];
}
return itemProperties.toArray();
}
@Kroll.method
public void appendItems(Object data)
{
if (data instanceof Object[]) {
Object[] views = (Object[]) data;
if (itemProperties == null) {
itemProperties = new ArrayList<Object>(Arrays.asList(views));
} else {
for (Object view : views) {
itemProperties.add(view);
}
}
//only process items when listview's properties is processed.
if (getListView() == null) {
preload = true;
return;
}
//we must update the itemCount before notify data change. If we don't, it will crash
int count = itemCount;
itemCount += views.length;
processData(views, count);
} else {
Log.e(TAG, "Invalid argument type to setData", Log.DEBUG_MODE);
}
}
public boolean isIndexValid(int index)
{
return (index >= 0) ? true : false;
}
@Kroll.method
public void insertItemsAt(int index, Object data)
{
if (!isIndexValid(index)) {
return;
}
handleInsertItemsAt(index, data);
}
@Kroll.method
public void deleteItemsAt(int index, int count)
{
if (!isIndexValid(index)) {
return;
}
deleteItems(index, count);
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
@Kroll.method
public void replaceItemsAt(int index, int count, Object data)
{
if (!isIndexValid(index)) {
return;
}
handleReplaceItemsAt(index, count, data);
}
@Kroll.method
public void updateItemAt(int index, Object data)
{
if (!isIndexValid(index) || !(data instanceof HashMap)) {
return;
}
handleReplaceItemsAt(index, 1, new Object[] { data });
setProperty(TiC.PROPERTY_ITEMS, itemProperties.toArray());
}
public void processPreloadData()
{
if (itemProperties != null && preload) {
handleSetItems(itemProperties.toArray());
preload = false;
}
}
public void refreshItems()
{
handleSetItems(itemProperties.toArray());
}
private void processData(Object[] items, int offset)
{
if (listItemData == null) {
return;
}
TiListViewTemplate[] temps = new TiListViewTemplate[items.length];
//First pass through data, we process template and update
//default properties based data given
for (int i = 0; i < items.length; i++) {
Object itemData = items[i];
if (itemData instanceof HashMap) {
KrollDict d = new KrollDict((HashMap) itemData);
TiListViewTemplate template = processTemplate(d, i + offset);
template.updateOrMergeWithDefaultProperties(d, true);
temps[i] = template;
}
}
//Second pass we would merge properties
for (int i = 0; i < items.length; i++) {
Object itemData = items[i];
if (itemData instanceof HashMap) {
KrollDict d = new KrollDict((HashMap) itemData);
TiListViewTemplate template = temps[i];
if (template != null) {
template.updateOrMergeWithDefaultProperties(d, false);
}
ListItemData itemD = new ListItemData(d, template);
d.remove(TiC.PROPERTY_TEMPLATE);
listItemData.add(i + offset, itemD);
}
}
//reapply filter if necessary
if (isFilterOn()) {
applyFilter(getListView().getSearchText());
}
//Notify adapter that data has changed.
adapter.notifyDataSetChanged();
}
private void handleSetItems(Object data)
{
if (data instanceof Object[]) {
Object[] items = (Object[]) data;
itemProperties = new ArrayList<Object>(Arrays.asList(items));
listItemData.clear();
//only process items when listview's properties is processed.
if (getListView() == null) {
preload = true;
return;
}
itemCount = items.length;
processData(items, 0);
} else {
Log.e(TAG, "Invalid argument type to setData", Log.DEBUG_MODE);
}
}
private void handleSetHeaderTitle(String headerTitle)
{
this.headerTitle = headerTitle;
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
private void handleSetFooterTitle(String footerTitle)
{
this.footerTitle = footerTitle;
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
private void handleSetFooterView(TiViewProxy footerView)
{
this.footerView = footerView;
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
private void handleInsertItemsAt(int index, Object data)
{
if (data instanceof Object[]) {
Object[] views = (Object[]) data;
if (itemProperties == null) {
itemProperties = new ArrayList<Object>(Arrays.asList(views));
} else {
if (index < 0 || index > itemProperties.size()) {
Log.e(TAG, "Invalid index to handleInsertItem", Log.DEBUG_MODE);
return;
}
int counter = index;
for (Object view : views) {
itemProperties.add(counter, view);
counter++;
}
}
//only process items when listview's properties is processed.
if (getListView() == null) {
preload = true;
return;
}
itemCount += views.length;
processData(views, index);
} else {
Log.e(TAG, "Invalid argument type to insertItemsAt", Log.DEBUG_MODE);
}
}
private boolean deleteItems(int index, int count)
{
boolean delete = false;
while (count > 0) {
if (index < itemProperties.size()) {
itemProperties.remove(index);
itemCount--;
delete = true;
}
if (index < listItemData.size()) {
listItemData.remove(index);
}
count--;
}
//reapply filter if necessary
if (isFilterOn()) {
applyFilter(getListView().getSearchText());
}
return delete;
}
private void handleReplaceItemsAt(int index, int count, Object data)
{
if (count == 0) {
handleInsertItemsAt(index, data);
} else if (deleteItems(index, count)) {
handleInsertItemsAt(index, data);
}
}
private TiListViewTemplate processTemplate(KrollDict itemData, int index)
{
TiListView listView = getListView();
String defaultTemplateBinding = null;
if (listView != null) {
defaultTemplateBinding = listView.getDefaultTemplateBinding();
}
//if template is specified in data, we look it up and if one exists, we use it.
//Otherwise we check if a default template is specified in ListView. If not, we use builtInTemplate.
String binding = TiConvert.toString(itemData.get(TiC.PROPERTY_TEMPLATE));
if (binding != null) {
//check if template is default
if (binding.equals(UIModule.LIST_ITEM_TEMPLATE_DEFAULT)) {
return processDefaultTemplate(itemData, index);
}
TiListViewTemplate template = listView.getTemplateByBinding(binding);
//if template is successfully retrieved, bind it to the index. This is b/c
//each row can have a different template.
if (template == null) {
Log.e(TAG, "Template undefined");
}
return template;
} else {
//if a valid default template is specify, use that one
if (defaultTemplateBinding != null && !defaultTemplateBinding.equals(UIModule.LIST_ITEM_TEMPLATE_DEFAULT)) {
TiListViewTemplate defTemplate = listView.getTemplateByBinding(defaultTemplateBinding);
if (defTemplate != null) {
return defTemplate;
}
}
return processDefaultTemplate(itemData, index);
}
}
private TiListViewTemplate processDefaultTemplate(KrollDict data, int index)
{
if (builtInTemplate == null) {
//Create template and generate default properties
builtInTemplate = new TiDefaultListViewTemplate(UIModule.LIST_ITEM_TEMPLATE_DEFAULT, null, getActivity());
//Each template is treated as an item type, so we can reuse views efficiently.
//Section templates are given a type in TiListView.processSections(). Here we
//give default template a type if possible.
TiListView listView = getListView();
if (listView != null) {
builtInTemplate.setType(TiListView.BUILT_IN_TEMPLATE_ITEM_TYPE);
builtInTemplate.setRootParent(listView.getProxy());
}
}
return builtInTemplate;
}
/**
* This method creates a new cell and fill it with content. getView() calls this method
* when a view needs to be created.
* @param index Entry's index relative to its section
* @return
*/
public void generateCellContent(int sectionIndex, KrollDict data, TiListViewTemplate template,
TiBaseListViewItem itemContent, int itemPosition, View item_layout)
{
//Here we create an item content and populate it with data
//Get item proxy
TiViewProxy itemProxy = template.getRootItem().getViewProxy();
//Create corresponding TiUIView for item proxy
TiListItem item = new TiListItem(itemProxy, (TiCompositeLayout.LayoutParams) itemContent.getLayoutParams(),
itemContent, item_layout);
//Connect native view with TiUIView so we can get it from recycled view.
itemContent.setTag(item);
if (data != null && template != null) {
generateChildContentViews(template.getRootItem(), null, itemContent, true);
populateViews(data, itemContent, template, itemPosition, sectionIndex, item_layout);
}
}
public void generateChildContentViews(DataItem item, TiUIView parentContent, TiBaseListViewItem rootItem,
boolean root)
{
Activity activity = getActivity();
if (activity == null) {
return;
}
ArrayList<DataItem> childrenItem = item.getChildren();
for (int i = 0; i < childrenItem.size(); i++) {
DataItem child = childrenItem.get(i);
TiViewProxy proxy = child.getViewProxy();
proxy.setActivity(activity);
TiUIView view = proxy.createView(proxy.getActivity());
view.registerForTouch();
proxy.setView(view);
generateChildContentViews(child, view, rootItem, false);
//Bind view to root.
ViewItem viewItem = new ViewItem(view, new KrollDict());
rootItem.bindView(child.getBindingId(), viewItem);
//Add it to view hierarchy
if (root) {
rootItem.addView(view.getNativeView(), view.getLayoutParams());
} else {
parentContent.add(view);
}
}
}
public void appendExtraEventData(TiUIView view, int itemIndex, int sectionIndex, String bindId, String itemId)
{
KrollDict existingData = view.getAdditionalEventData();
if (existingData == null) {
existingData = new KrollDict();
view.setAdditionalEventData(existingData);
}
//itemIndex = realItemIndex + header (if exists). We want the real item index.
if (headerTitle != null || headerView != null) {
itemIndex -= 1;
}
existingData.put(TiC.PROPERTY_SECTION, this);
existingData.put(TiC.PROPERTY_SECTION_INDEX, sectionIndex);
int realItemIndex = itemIndex;
if (isFilterOn()) {
realItemIndex = filterIndices.get(itemIndex);
}
existingData.put(TiC.PROPERTY_ITEM_INDEX, realItemIndex);
if (!bindId.startsWith(TiListViewTemplate.GENERATED_BINDING) && !bindId.equals(TiC.PROPERTY_PROPERTIES)) {
existingData.put(TiC.PROPERTY_BIND_ID, bindId);
} else if (existingData.containsKey(TiC.PROPERTY_BIND_ID)) {
existingData.remove(TiC.PROPERTY_BIND_ID);
}
if (itemId != null) {
existingData.put(TiC.PROPERTY_ITEM_ID, itemId);
} else if (existingData.containsKey(TiC.PROPERTY_ITEM_ID)) {
existingData.remove(TiC.PROPERTY_ITEM_ID);
}
}
public void populateViews(KrollDict data, TiBaseListViewItem cellContent, TiListViewTemplate template,
int itemIndex, int sectionIndex, View item_layout)
{
Object cell = cellContent.getTag();
//Handling root item, since that is not in the views map.
if (!(cell instanceof TiListItem)) {
Log.e(TAG, "Cell is not TiListItem. Something is wrong..", Log.DEBUG_MODE);
return;
}
TiListItem listItem = (TiListItem) cell;
KrollDict listItemProperties;
String itemId = null;
if (data.containsKey(TiC.PROPERTY_PROPERTIES)) {
listItemProperties = new KrollDict((HashMap) data.get(TiC.PROPERTY_PROPERTIES));
} else {
listItemProperties = template.getRootItem().getDefaultProperties();
}
//find out if we need to update itemId
if (listItemProperties.containsKey(TiC.PROPERTY_ITEM_ID)) {
itemId = TiConvert.toString(listItemProperties.get(TiC.PROPERTY_ITEM_ID));
}
//update extra event data for list item
appendExtraEventData(listItem, itemIndex, sectionIndex, TiC.PROPERTY_PROPERTIES, itemId);
HashMap<String, ViewItem> views = (HashMap<String, ViewItem>) cellContent.getViewsMap();
//Loop through all our views and apply default properties
for (String binding : views.keySet()) {
DataItem dataItem = template.getDataItem(binding);
ViewItem viewItem = views.get(binding);
TiUIView view = viewItem.getView();
KrollProxy viewProxy = null;
//update extra event data for views
if (view != null) {
viewProxy = view.getProxy();
appendExtraEventData(view, itemIndex, sectionIndex, binding, itemId);
}
//if binding is contain in data given to us, process that data, otherwise
//apply default properties.
if (data.containsKey(binding) && view != null) {
KrollDict properties = new KrollDict((HashMap) data.get(binding));
KrollDict diffProperties = viewItem.generateDiffProperties(properties);
if (!diffProperties.isEmpty()) {
if (viewProxy != null && viewProxy.getProperties() != null) {
viewProxy.getProperties().putAll(diffProperties);
}
view.processProperties(diffProperties);
}
} else if (dataItem != null && view != null) {
KrollDict diffProperties = viewItem.generateDiffProperties(dataItem.getDefaultProperties());
if (!diffProperties.isEmpty()) {
if (viewProxy != null && viewProxy.getProperties() != null) {
viewProxy.getProperties().putAll(diffProperties);
}
view.processProperties(diffProperties);
}
} else {
Log.w(TAG, "Sorry, " + binding + " isn't a valid binding. Perhaps you made a typo?", Log.DEBUG_MODE);
}
}
//process listItem properties
if (cellContent.getViewItem() != null) {
KrollDict listItemDiff = cellContent.getViewItem().generateDiffProperties(listItemProperties);
if (!listItemDiff.isEmpty()) {
listItem.processProperties(listItemDiff);
}
}
}
public TiListViewTemplate getTemplateByIndex(int index)
{
if (headerTitle != null || headerView != null) {
index -= 1;
}
if (isFilterOn()) {
return listItemData.get(filterIndices.get(index)).getTemplate();
} else {
return listItemData.get(index).getTemplate();
}
}
public int getContentCount()
{
if (isFilterOn()) {
return filterIndices.size();
} else {
return itemCount;
}
}
/**
* @return number of entries within section
*/
public int getItemCount()
{
int totalCount = 0;
if (isFilterOn()) {
totalCount = filterIndices.size();
} else {
totalCount = itemCount;
}
if (!hideHeaderOrFooter()) {
if (headerTitle != null || headerView != null) {
totalCount += 1;
}
if (footerTitle != null || footerView != null) {
totalCount += 1;
}
}
return totalCount;
}
private boolean hideHeaderOrFooter()
{
TiListView listview = getListView();
return (listview.getSearchText() != null && filterIndices.isEmpty());
}
public boolean hasHeader()
{
return (headerTitle != null || headerView != null);
}
public boolean isHeaderView(int pos)
{
return (headerView != null && pos == 0);
}
public boolean isFooterView(int pos)
{
return (footerView != null && pos == getItemCount() - 1);
}
public boolean isHeaderTitle(int pos)
{
return (headerTitle != null && pos == 0);
}
public boolean isFooterTitle(int pos)
{
return (footerTitle != null && pos == getItemCount() - 1);
}
public void setListView(TiListView listView)
{
// Store a weak reference to the given ListView.
this.listView = new WeakReference<TiListView>(listView);
// Updates this proxy to use the given ListView's activity. Will end up using its theme.
// Note: Odds are this proxy was initialized with the previous activity upon creation.
if (listView != null) {
TiViewProxy listViewProxy = listView.getProxy();
if ((listViewProxy != null) && (listViewProxy.getActivity() != null)) {
setActivity(listViewProxy.getActivity());
}
}
}
public TiListView getListView()
{
if (listView != null) {
return listView.get();
}
return null;
}
/**
* Attempt to give each existing template a type, if possible
*/
public void setTemplateType()
{
for (int i = 0; i < listItemData.size(); i++) {
TiListViewTemplate temp = listItemData.get(i).getTemplate();
TiListView listView = getListView();
if (temp.getType() == -1) {
temp.setType(listView.getItemType());
}
}
}
public KrollDict getListItemData(int position)
{
if (headerTitle != null || headerView != null) {
position -= 1;
}
if (isFilterOn()) {
return listItemData.get(filterIndices.get(position)).getProperties();
} else if (position >= 0 && position < listItemData.size()) {
return listItemData.get(position).getProperties();
}
return null;
}
public boolean isFilterOn()
{
TiListView lv = getListView();
if (lv != null && lv.getSearchText() != null) {
return true;
}
return false;
}
public int applyFilter(String searchText)
{
//Clear previous result
filterIndices.clear();
boolean caseInsensitive = getListView().getCaseInsensitive();
//Add new results
for (int i = 0; i < listItemData.size(); ++i) {
String searchableText = listItemData.get(i).getSearchableText();
//Handle case sensitivity
if (caseInsensitive) {
searchText = searchText.toLowerCase();
searchableText = searchableText.toLowerCase();
}
//String comparison
if (searchableText.contains(searchText)) {
filterIndices.add(i);
}
}
return filterIndices.size();
}
public void release()
{
if (listItemData != null) {
listItemData.clear();
listItemData = null;
}
if (itemProperties != null) {
itemProperties.clear();
itemProperties = null;
}
if (builtInTemplate != null) {
builtInTemplate.release();
builtInTemplate = null;
}
super.release();
}
public void releaseViews()
{
listView = null;
}
@Override
public String getApiName()
{
return "Ti.UI.ListSection";
}
}
| apache-2.0 |
mmmsplay10/QuizUpWinner | quizup/com/fasterxml/jackson/databind/deser/Deserializers.java | 5094 | package com.fasterxml.jackson.databind.deser;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.jsontype.TypeDeserializer;
import com.fasterxml.jackson.databind.type.ArrayType;
import com.fasterxml.jackson.databind.type.CollectionLikeType;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.type.MapLikeType;
import com.fasterxml.jackson.databind.type.MapType;
public abstract interface Deserializers
{
public abstract JsonDeserializer<?> findArrayDeserializer(ArrayType paramArrayType, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription, TypeDeserializer paramTypeDeserializer, JsonDeserializer<?> paramJsonDeserializer);
public abstract JsonDeserializer<?> findBeanDeserializer(JavaType paramJavaType, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription);
public abstract JsonDeserializer<?> findCollectionDeserializer(CollectionType paramCollectionType, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription, TypeDeserializer paramTypeDeserializer, JsonDeserializer<?> paramJsonDeserializer);
public abstract JsonDeserializer<?> findCollectionLikeDeserializer(CollectionLikeType paramCollectionLikeType, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription, TypeDeserializer paramTypeDeserializer, JsonDeserializer<?> paramJsonDeserializer);
public abstract JsonDeserializer<?> findEnumDeserializer(Class<?> paramClass, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription);
public abstract JsonDeserializer<?> findMapDeserializer(MapType paramMapType, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription, KeyDeserializer paramKeyDeserializer, TypeDeserializer paramTypeDeserializer, JsonDeserializer<?> paramJsonDeserializer);
public abstract JsonDeserializer<?> findMapLikeDeserializer(MapLikeType paramMapLikeType, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription, KeyDeserializer paramKeyDeserializer, TypeDeserializer paramTypeDeserializer, JsonDeserializer<?> paramJsonDeserializer);
public abstract JsonDeserializer<?> findTreeNodeDeserializer(Class<? extends JsonNode> paramClass, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription);
public static class Base
implements Deserializers
{
public JsonDeserializer<?> findArrayDeserializer(ArrayType paramArrayType, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription, TypeDeserializer paramTypeDeserializer, JsonDeserializer<?> paramJsonDeserializer)
{
return null;
}
public JsonDeserializer<?> findBeanDeserializer(JavaType paramJavaType, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription)
{
return null;
}
public JsonDeserializer<?> findCollectionDeserializer(CollectionType paramCollectionType, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription, TypeDeserializer paramTypeDeserializer, JsonDeserializer<?> paramJsonDeserializer)
{
return null;
}
public JsonDeserializer<?> findCollectionLikeDeserializer(CollectionLikeType paramCollectionLikeType, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription, TypeDeserializer paramTypeDeserializer, JsonDeserializer<?> paramJsonDeserializer)
{
return null;
}
public JsonDeserializer<?> findEnumDeserializer(Class<?> paramClass, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription)
{
return null;
}
public JsonDeserializer<?> findMapDeserializer(MapType paramMapType, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription, KeyDeserializer paramKeyDeserializer, TypeDeserializer paramTypeDeserializer, JsonDeserializer<?> paramJsonDeserializer)
{
return null;
}
public JsonDeserializer<?> findMapLikeDeserializer(MapLikeType paramMapLikeType, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription, KeyDeserializer paramKeyDeserializer, TypeDeserializer paramTypeDeserializer, JsonDeserializer<?> paramJsonDeserializer)
{
return null;
}
public JsonDeserializer<?> findTreeNodeDeserializer(Class<? extends JsonNode> paramClass, DeserializationConfig paramDeserializationConfig, BeanDescription paramBeanDescription)
{
return null;
}
}
}
/* Location: /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
* Qualified Name: com.fasterxml.jackson.databind.deser.Deserializers
* JD-Core Version: 0.6.2
*/ | apache-2.0 |
zapr-oss/druidry | src/main/java/in/zapr/druid/druidry/filter/DruidFilter.java | 824 | /*
* Copyright 2018-present Red Brick Lane Marketing Solutions Pvt. 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 in.zapr.druid.druidry.filter;
import lombok.EqualsAndHashCode;
import lombok.Getter;
@Getter
@EqualsAndHashCode
public abstract class DruidFilter {
protected String type;
}
| apache-2.0 |
crnk-project/crnk-framework | crnk-data/crnk-data-jpa/src/test/java/io/crnk/data/jpa/repository/JpaModuleTest.java | 1439 | package io.crnk.data.jpa.repository;
import io.crnk.data.jpa.JpaModule;
import io.crnk.data.jpa.JpaModuleConfig;
import io.crnk.data.jpa.model.TestEntity;
import io.crnk.data.jpa.query.AbstractJpaTest;
import io.crnk.data.jpa.query.JpaQueryFactory;
import io.crnk.data.jpa.query.querydsl.QuerydslQueryFactory;
import io.crnk.test.mock.ClassTestUtils;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.util.Set;
@Transactional
public class JpaModuleTest extends AbstractJpaTest {
@Test
public void hasProtectedConstructor() {
ClassTestUtils.assertProtectedConstructor(JpaModule.class);
}
@Override
protected void setupModule(JpaModuleConfig module) {
Set<Class<?>> resourceClasses = module.getResourceClasses();
int n = resourceClasses.size();
Assert.assertNotEquals(0, n);
module.removeRepository(TestEntity.class);
Assert.assertEquals(n - 1, module.getResourceClasses().size());
module.removeRepositories();
}
@Test
public void test() {
Assert.assertEquals(0, module.getConfig().getResourceClasses().size());
Assert.assertEquals("jpa", module.getModuleName());
}
@Override
protected JpaQueryFactory createQueryFactory(EntityManager em) {
return QuerydslQueryFactory.newInstance();
}
}
| apache-2.0 |
yorkchow/yirui | yirui-paginator/src/test/java/com/yirui/paginator/test/pagesize/PageSizeZeroTest.java | 2444 | package com.yirui.paginator.test.pagesize;
import com.yirui.paginator.PageHelper;
import com.yirui.paginator.PageInfo;
import com.yirui.paginator.mapper.CountryMapper;
import com.yirui.paginator.model.Country;
import com.yirui.paginator.util.MybatisPageSizeZeroHelper;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class PageSizeZeroTest {
/**
* 使用Mapper接口调用时,使用PageHelper.startPage效果更好,不需要添加Mapper接口参数
*/
@Test
public void testWithStartPage() {
SqlSession sqlSession = MybatisPageSizeZeroHelper.getSqlSession();
CountryMapper countryMapper = sqlSession.getMapper(CountryMapper.class);
try {
//pageSize=0的时候查询全部结果
PageHelper.startPage(1, 0);
List<Country> list = countryMapper.selectAll();
PageInfo page = new PageInfo(list);
assertEquals(183, list.size());
assertEquals(183, page.getTotal());
//pageSize=0的时候查询全部结果
PageHelper.startPage(10, 0);
list = countryMapper.selectAll();
page = new PageInfo(list);
assertEquals(183, list.size());
assertEquals(183, page.getTotal());
} finally {
sqlSession.close();
}
}
/**
* 使用Mapper接口调用时,使用PageHelper.startPage效果更好,不需要添加Mapper接口参数
*/
@Test
public void testWithRowbounds() {
SqlSession sqlSession = MybatisPageSizeZeroHelper.getSqlSession();
CountryMapper countryMapper = sqlSession.getMapper(CountryMapper.class);
try {
//pageSize=0的时候查询全部结果
List<Country> list = countryMapper.selectAll(new RowBounds(1, 0));
PageInfo page = new PageInfo(list);
assertEquals(183, list.size());
assertEquals(183, page.getTotal());
//pageSize=0的时候查询全部结果
PageHelper.startPage(10, 0);
list = countryMapper.selectAll(new RowBounds(1000, 0));
page = new PageInfo(list);
assertEquals(183, list.size());
assertEquals(183, page.getTotal());
} finally {
sqlSession.close();
}
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/transform/HlsBasicPutSettingsJsonUnmarshaller.java | 3578 | /*
* 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.medialive.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.medialive.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* HlsBasicPutSettings JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class HlsBasicPutSettingsJsonUnmarshaller implements Unmarshaller<HlsBasicPutSettings, JsonUnmarshallerContext> {
public HlsBasicPutSettings unmarshall(JsonUnmarshallerContext context) throws Exception {
HlsBasicPutSettings hlsBasicPutSettings = new HlsBasicPutSettings();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("connectionRetryInterval", targetDepth)) {
context.nextToken();
hlsBasicPutSettings.setConnectionRetryInterval(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("filecacheDuration", targetDepth)) {
context.nextToken();
hlsBasicPutSettings.setFilecacheDuration(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("numRetries", targetDepth)) {
context.nextToken();
hlsBasicPutSettings.setNumRetries(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("restartDelay", targetDepth)) {
context.nextToken();
hlsBasicPutSettings.setRestartDelay(context.getUnmarshaller(Integer.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return hlsBasicPutSettings;
}
private static HlsBasicPutSettingsJsonUnmarshaller instance;
public static HlsBasicPutSettingsJsonUnmarshaller getInstance() {
if (instance == null)
instance = new HlsBasicPutSettingsJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-codestarconnections/src/main/java/com/amazonaws/services/codestarconnections/model/ListTagsForResourceResult.java | 4969 | /*
* 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.codestarconnections.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codestar-connections-2019-12-01/ListTagsForResource"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListTagsForResourceResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* A list of tag key and value pairs associated with the specified resource.
* </p>
*/
private java.util.List<Tag> tags;
/**
* <p>
* A list of tag key and value pairs associated with the specified resource.
* </p>
*
* @return A list of tag key and value pairs associated with the specified resource.
*/
public java.util.List<Tag> getTags() {
return tags;
}
/**
* <p>
* A list of tag key and value pairs associated with the specified resource.
* </p>
*
* @param tags
* A list of tag key and value pairs associated with the specified resource.
*/
public void setTags(java.util.Collection<Tag> tags) {
if (tags == null) {
this.tags = null;
return;
}
this.tags = new java.util.ArrayList<Tag>(tags);
}
/**
* <p>
* A list of tag key and value pairs associated with the specified resource.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setTags(java.util.Collection)} or {@link #withTags(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param tags
* A list of tag key and value pairs associated with the specified resource.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListTagsForResourceResult withTags(Tag... tags) {
if (this.tags == null) {
setTags(new java.util.ArrayList<Tag>(tags.length));
}
for (Tag ele : tags) {
this.tags.add(ele);
}
return this;
}
/**
* <p>
* A list of tag key and value pairs associated with the specified resource.
* </p>
*
* @param tags
* A list of tag key and value pairs associated with the specified resource.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListTagsForResourceResult withTags(java.util.Collection<Tag> tags) {
setTags(tags);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getTags() != null)
sb.append("Tags: ").append(getTags());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListTagsForResourceResult == false)
return false;
ListTagsForResourceResult other = (ListTagsForResourceResult) obj;
if (other.getTags() == null ^ this.getTags() == null)
return false;
if (other.getTags() != null && other.getTags().equals(this.getTags()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode());
return hashCode;
}
@Override
public ListTagsForResourceResult clone() {
try {
return (ListTagsForResourceResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_2303.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_2303 {
}
| apache-2.0 |
SmallBadFish/demo | src/main/java/com/yin/myproject/demo/concurrent/base/restaurant/Restaurant.java | 487 | package com.yin.myproject.demo.concurrent.base.restaurant;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Restaurant {
Meal meal;
ExecutorService service = Executors.newCachedThreadPool();
public Chef chef = new Chef(this);
public WaitPerson wp = new WaitPerson(this);
public Restaurant() {
service.execute(chef);
service.execute(wp);
}
public static void main(String[] args) {
new Restaurant();
}
}
| apache-2.0 |
zhangyongfu/image | src/main/java/org/image/model/ImageMetadata.java | 2597 | package org.image.model;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import org.image.DAO.ImageDao;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ImageMetadata {
public ImageMetadata(){
}
public Map<String,String> getAllMetadata(long imgId) throws ImageProcessingException, IOException{
Map<String,String> imgMetadata = new HashMap<String, String>();
UploadPubImages uploadPubImages = new UploadPubImages();
String imgName = uploadPubImages.getPubImgFileName(imgId);
String imagePath = "/root/webdata/imagedata/";
// String imagePath = "/home/zyj/IdeaProjects/image/i/imagedata/";
try {
File imgFile = new File(imagePath + "pub_img/" + imgName);
try {
Metadata metadata = ImageMetadataReader.readMetadata(imgFile);
for (Directory directory : metadata.getDirectories()) {
for (Tag tag : directory.getTags()) {
imgMetadata.put(tag.getTagName(),tag.getDescription());
// System.out.println(tag);
}
}
} catch (ImageProcessingException e) {
e.printStackTrace();
}
}
catch (IOException e) {
e.printStackTrace();
}
return imgMetadata;
}
/**
* 图片数据元提取
*/
public static void metadataExtractor(){
File jpegFile = new File("11.jpg");
try {
Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
for (Directory directory : metadata.getDirectories()) {
for (Tag tag : directory.getTags()) {
System.out.println(tag);
}
}
} catch (ImageProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
// metadataExtractor();
// ImageMetadata i = new ImageMetadata();
//
// i.getAllMetadata(216);
Map<String,String> data = new ImageMetadata().getAllMetadata(206);
for(Map.Entry<String,String> entry:data.entrySet()){
System.out.println(entry.getKey() + ";;;;" + entry.getValue());
}
}
}
| apache-2.0 |
grapecity/DebugRank | java-lib/src/main/java/com/grapecity/debugrank/javalib/entities/Puzzle.java | 740 | package com.grapecity.debugrank.javalib.entities;
import java.io.Serializable;
/**
* Created by chrisr on 1/26/2016.
*/
public class Puzzle implements Serializable
{
public final String key;
public final String name;
public final int points;
public final int time;
public final int bugs;
public final String[] testcases;
public final String[] answers;
public Puzzle(String key, String name, int points, int time, int bugs, String[] testcases, String[] answers)
{
this.key = key;
this.name = name;
this.points = points;
this.time = time;
this.bugs = bugs;
this.testcases = testcases;
this.answers = answers;
}
}
| apache-2.0 |
multiscripter/job4j | junior/pack1_trainee/p2_oop/ch2_inheritance/src/main/java/ru/job4j/profession/Person.java | 1793 | package ru.job4j.profession;
import java.util.Date;
/**
* Class Person.
*
* @author Goureev Ilya (mailto:ill-jah@yandex.ru)
* @version 1
* @since 2017-04-18
*/
abstract class Person {
/**
* Фамилия.
*/
private String nameLast;
/**
* Имя.
*/
private final String nameFirst;
/**
* Пол.
*/
private Gender gender;
/**
* Дата рождения.
*/
private final Date birthDay;
/**
* Конструктор.
* @param nameLast фамилия.
* @param nameFirst имя.
* @param gender пол.
* @param birthDay дата рождения.
*/
Person(String nameLast, String nameFirst, Gender gender, Date birthDay) {
this.nameLast = nameLast;
this.nameFirst = nameFirst;
this.gender = gender;
this.birthDay = birthDay;
}
/**
* Возвращает фамилию.
* @return фамилия.
*/
public String getNameLast() {
return this.nameLast;
}
/**
* Устанавливает фамилию.
* @param nameLast новая фамилия.
*/
public void setNameLast(String nameLast) {
this.nameLast = nameLast;
}
/**
* Возвращает имя.
* @return имя.
*/
public String getNameFirst() {
return this.nameFirst;
}
/**
* Возвращает пол.
* @return пол.
*/
public Gender getGender() {
return this.gender;
}
/**
* Возвращает дату рождения.
* @return дата рождения.
*/
public Date getBirthDay() {
return this.birthDay;
}
} | apache-2.0 |
facebook/litho | litho-it/src/test/java/com/facebook/litho/widget/ProgressSpecTest.java | 2118 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho.widget;
import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import android.view.View;
import com.facebook.litho.ComponentContext;
import com.facebook.litho.LithoView;
import com.facebook.litho.testing.helper.ComponentTestHelper;
import com.facebook.litho.testing.testrunner.LithoTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/** Tests {@link ProgressSpec} */
@RunWith(LithoTestRunner.class)
public class ProgressSpecTest {
private ComponentContext mContext;
@Before
public void setup() {
mContext = new ComponentContext(getApplicationContext());
}
@Test
public void testDefault() {
LithoView view = getMountedView();
assertThat(view.getMeasuredWidth()).isGreaterThan(0);
assertThat(view.getMeasuredHeight()).isGreaterThan(0);
}
@Test
public void testUnsetSize() {
LithoView view = getMountedView();
view.measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
assertThat(view.getMeasuredWidth()).isEqualTo(ProgressSpec.DEFAULT_SIZE);
assertThat(view.getMeasuredHeight()).isEqualTo(ProgressSpec.DEFAULT_SIZE);
}
private LithoView getMountedView() {
Progress.Builder progress = Progress.create(mContext);
return ComponentTestHelper.mountComponent(progress);
}
}
| apache-2.0 |
intrack/BoofCV-master | main/geo/src/boofcv/factory/feature/tracker/FactoryPointTracker.java | 23771 | /*
* Copyright (c) 2011-2013, 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.feature.tracker;
import boofcv.abst.feature.associate.*;
import boofcv.abst.feature.describe.ConfigSurfDescribe;
import boofcv.abst.feature.describe.DescribeRegionPoint;
import boofcv.abst.feature.describe.WrapDescribeBrief;
import boofcv.abst.feature.describe.WrapDescribePixelRegionNCC;
import boofcv.abst.feature.detdesc.DetectDescribeFusion;
import boofcv.abst.feature.detdesc.DetectDescribePoint;
import boofcv.abst.feature.detect.interest.ConfigFast;
import boofcv.abst.feature.detect.interest.ConfigFastHessian;
import boofcv.abst.feature.detect.interest.ConfigGeneralDetector;
import boofcv.abst.feature.detect.interest.InterestPointDetector;
import boofcv.abst.feature.orientation.ConfigAverageIntegral;
import boofcv.abst.feature.orientation.ConfigSlidingIntegral;
import boofcv.abst.feature.orientation.OrientationImage;
import boofcv.abst.feature.orientation.OrientationIntegral;
import boofcv.abst.feature.tracker.*;
import boofcv.abst.filter.derivative.ImageGradient;
import boofcv.alg.feature.associate.AssociateSurfBasic;
import boofcv.alg.feature.describe.DescribePointBrief;
import boofcv.alg.feature.describe.DescribePointPixelRegionNCC;
import boofcv.alg.feature.describe.DescribePointSurf;
import boofcv.alg.feature.describe.brief.FactoryBriefDefinition;
import boofcv.alg.feature.detect.intensity.GradientCornerIntensity;
import boofcv.alg.feature.detect.interest.EasyGeneralFeatureDetector;
import boofcv.alg.feature.detect.interest.GeneralFeatureDetector;
import boofcv.alg.filter.derivative.GImageDerivativeOps;
import boofcv.alg.interpolate.InterpolateRectangle;
import boofcv.alg.tracker.combined.CombinedTrackerScalePoint;
import boofcv.alg.transform.ii.GIntegralImageOps;
import boofcv.factory.feature.associate.FactoryAssociation;
import boofcv.factory.feature.describe.FactoryDescribePointAlgs;
import boofcv.factory.feature.describe.FactoryDescribeRegionPoint;
import boofcv.factory.feature.detdesc.FactoryDetectDescribe;
import boofcv.factory.feature.detect.intensity.FactoryIntensityPointAlg;
import boofcv.factory.feature.detect.interest.FactoryDetectPoint;
import boofcv.factory.feature.detect.interest.FactoryInterestPoint;
import boofcv.factory.feature.orientation.FactoryOrientation;
import boofcv.factory.feature.orientation.FactoryOrientationAlgs;
import boofcv.factory.filter.blur.FactoryBlurFilter;
import boofcv.factory.filter.derivative.FactoryDerivative;
import boofcv.factory.interpolate.FactoryInterpolation;
import boofcv.factory.tracker.FactoryTrackerAlg;
import boofcv.factory.transform.pyramid.FactoryPyramid;
import boofcv.struct.feature.*;
import boofcv.struct.image.ImageDataType;
import boofcv.struct.image.ImageSingleBand;
import boofcv.struct.pyramid.PyramidDiscrete;
import java.util.Random;
/**
* Factory for creating trackers which implement {@link boofcv.abst.feature.tracker.PointTracker}. These trackers
* are intended for use in SFM applications. Some features which individual trackers can provide are lost when
* using the high level interface {@link PointTracker}. To create low level tracking algorithms see
* {@link FactoryTrackerAlg}
*
* @see FactoryTrackerAlg
*
* @author Peter Abeles
*/
public class FactoryPointTracker {
/**
* Pyramid KLT feature tracker.
*
* @see boofcv.alg.tracker.klt.PyramidKltTracker
*
* @param scaling Scales in the image pyramid. Recommend [1,2,4] or [2,4]
* @param configExtract Configuration for extracting features
* @param featureRadius Size of the tracked feature. Try 3 or 5
* @param imageType Input image type.
* @param derivType Image derivative type.
* @return KLT based tracker.
*/
public static <I extends ImageSingleBand, D extends ImageSingleBand>
PointTracker<I> klt(int scaling[], ConfigGeneralDetector configExtract, int featureRadius,
Class<I> imageType, Class<D> derivType) {
PkltConfig<I, D> config =
PkltConfig.createDefault(imageType, derivType);
config.pyramidScaling = scaling;
config.templateRadius = featureRadius;
return klt(config, configExtract);
}
/**
* Pyramid KLT feature tracker.
*
* @see boofcv.alg.tracker.klt.PyramidKltTracker
*
* @param config Config for the tracker. Try PkltConfig.createDefault().
* @param configExtract Configuration for extracting features
* @return KLT based tracker.
*/
public static <I extends ImageSingleBand, D extends ImageSingleBand>
PointTracker<I> klt(PkltConfig<I, D> config, ConfigGeneralDetector configExtract) {
GeneralFeatureDetector<I, D> detector = createShiTomasi(configExtract, config.typeDeriv);
InterpolateRectangle<I> interpInput = FactoryInterpolation.<I>bilinearRectangle(config.typeInput);
InterpolateRectangle<D> interpDeriv = FactoryInterpolation.<D>bilinearRectangle(config.typeDeriv);
ImageGradient<I,D> gradient = FactoryDerivative.sobel(config.typeInput, config.typeDeriv);
PyramidDiscrete<I> pyramid = FactoryPyramid.discreteGaussian(config.pyramidScaling,-1,2,true,config.typeInput);
return new PointTrackerKltPyramid<I, D>(config.config,config.templateRadius,pyramid,detector,
gradient,interpInput,interpDeriv,config.typeDeriv);
}
/**
* Creates a tracker which detects Fast-Hessian features and describes them with SURF using the faster variant
* of SURF.
*
* @see DescribePointSurf
* @see boofcv.abst.feature.tracker.DdaManagerDetectDescribePoint
*
* @param configDetector Configuration for SURF detector
* @param configDescribe Configuration for SURF descriptor
* @param configOrientation Configuration for orientation
* @param imageType Type of image the input is.
* @return SURF based tracker.
*/
// TODO remove maxTracks? Use number of detected instead
public static <I extends ImageSingleBand>
PointTracker<I> dda_FH_SURF_Fast(
ConfigFastHessian configDetector ,
ConfigSurfDescribe.Speed configDescribe ,
ConfigAverageIntegral configOrientation ,
Class<I> imageType)
{
ScoreAssociation<TupleDesc_F64> score = FactoryAssociation.scoreEuclidean(TupleDesc_F64.class, true);
AssociateSurfBasic assoc = new AssociateSurfBasic(FactoryAssociation.greedy(score, 5, true));
AssociateDescription2D<SurfFeature> generalAssoc =
new AssociateDescTo2D<SurfFeature>(new WrapAssociateSurfBasic(assoc));
DetectDescribePoint<I,SurfFeature> fused =
FactoryDetectDescribe.surfFast(configDetector, configDescribe, configOrientation,
ImageDataType.single(imageType));
DdaManagerDetectDescribePoint<I,SurfFeature> manager = new DdaManagerDetectDescribePoint<I,SurfFeature>(fused);
return new DetectDescribeAssociate<I,SurfFeature>(manager, generalAssoc,false);
}
/**
* Creates a tracker which detects Fast-Hessian features and describes them with SURF using the faster variant
* of SURF.
*
* @see DescribePointSurf
* @see boofcv.abst.feature.tracker.DdaManagerDetectDescribePoint
*
* @param configDetector Configuration for SURF detector
* @param configDescribe Configuration for SURF descriptor
* @param configOrientation Configuration for orientation
* @param imageType Type of image the input is.
* @return SURF based tracker.
*/
// TODO remove maxTracks? Use number of detected instead
public static <I extends ImageSingleBand>
PointTracker<I> dda_FH_SURF_Stable(
ConfigFastHessian configDetector ,
ConfigSurfDescribe.Stablility configDescribe ,
ConfigSlidingIntegral configOrientation ,
Class<I> imageType)
{
ScoreAssociation<TupleDesc_F64> score = FactoryAssociation.scoreEuclidean(TupleDesc_F64.class, true);
AssociateSurfBasic assoc = new AssociateSurfBasic(FactoryAssociation.greedy(score, 5, true));
AssociateDescription2D<SurfFeature> generalAssoc =
new AssociateDescTo2D<SurfFeature>(new WrapAssociateSurfBasic(assoc));
DetectDescribePoint<I,SurfFeature> fused =
FactoryDetectDescribe.surfStable(configDetector,configDescribe,configOrientation,
ImageDataType.single(imageType));
DdaManagerDetectDescribePoint<I,SurfFeature> manager = new DdaManagerDetectDescribePoint<I,SurfFeature>(fused);
return new DetectDescribeAssociate<I,SurfFeature>(manager, generalAssoc,false);
}
/**
* Creates a tracker which detects Shi-Tomasi corner features and describes them with BRIEF.
*
* @see boofcv.alg.feature.detect.intensity.ShiTomasiCornerIntensity
* @see DescribePointBrief
* @see boofcv.abst.feature.tracker.DdaManagerDetectDescribePoint
*
* @param maxAssociationError Maximum allowed association error. Try 200.
* @param configExtract Configuration for extracting features
* @param imageType Type of image being processed.
* @param derivType Type of image used to store the image derivative. null == use default
*/
public static <I extends ImageSingleBand, D extends ImageSingleBand>
PointTracker<I> dda_ST_BRIEF(int maxAssociationError,
ConfigGeneralDetector configExtract,
Class<I> imageType, Class<D> derivType)
{
if( derivType == null )
derivType = GImageDerivativeOps.getDerivativeType(imageType);
DescribePointBrief<I> brief = FactoryDescribePointAlgs.brief(FactoryBriefDefinition.gaussian2(new Random(123), 16, 512),
FactoryBlurFilter.gaussian(imageType, 0, 4));
GeneralFeatureDetector<I, D> detectPoint = createShiTomasi(configExtract, derivType);
EasyGeneralFeatureDetector<I,D> easy = new EasyGeneralFeatureDetector<I, D>(detectPoint,imageType,derivType);
ScoreAssociateHamming_B score = new ScoreAssociateHamming_B();
AssociateDescription2D<TupleDesc_B> association =
new AssociateDescTo2D<TupleDesc_B>(FactoryAssociation.greedy(score, maxAssociationError, true));
DdaManagerGeneralPoint<I,D,TupleDesc_B> manager =
new DdaManagerGeneralPoint<I,D,TupleDesc_B>(easy,new WrapDescribeBrief<I>(brief,imageType),1.0);
return new DetectDescribeAssociate<I,TupleDesc_B>(manager, association,false);
}
/**
* Creates a tracker which detects FAST corner features and describes them with BRIEF.
*
* @see boofcv.alg.feature.detect.intensity.FastCornerIntensity
* @see DescribePointBrief
* @see boofcv.abst.feature.tracker.DdaManagerDetectDescribePoint
*
* @param configFast Configuration for FAST detector
* @param configExtract Configuration for extracting features
* @param maxAssociationError Maximum allowed association error. Try 200.
* @param imageType Type of image being processed.
*/
public static <I extends ImageSingleBand, D extends ImageSingleBand>
PointTracker<I> dda_FAST_BRIEF(ConfigFast configFast,
ConfigGeneralDetector configExtract,
int maxAssociationError,
Class<I> imageType )
{
DescribePointBrief<I> brief = FactoryDescribePointAlgs.brief(FactoryBriefDefinition.gaussian2(new Random(123), 16, 512),
FactoryBlurFilter.gaussian(imageType, 0, 4));
GeneralFeatureDetector<I,D> corner = FactoryDetectPoint.createFast(configFast, configExtract, imageType);
EasyGeneralFeatureDetector<I,D> easy = new EasyGeneralFeatureDetector<I, D>(corner,imageType,null);
ScoreAssociateHamming_B score = new ScoreAssociateHamming_B();
AssociateDescription2D<TupleDesc_B> association =
new AssociateDescTo2D<TupleDesc_B>(
FactoryAssociation.greedy(score, maxAssociationError, true));
DdaManagerGeneralPoint<I,D,TupleDesc_B> manager =
new DdaManagerGeneralPoint<I,D,TupleDesc_B>(easy,new WrapDescribeBrief<I>(brief,imageType),1.0);
return new DetectDescribeAssociate<I,TupleDesc_B>(manager, association,false);
}
/**
* Creates a tracker which detects Shi-Tomasi corner features and describes them with NCC.
*
* @see boofcv.alg.feature.detect.intensity.ShiTomasiCornerIntensity
* @see DescribePointPixelRegionNCC
* @see boofcv.abst.feature.tracker.DdaManagerDetectDescribePoint
*
* @param configExtract Configuration for extracting features
* @param describeRadius Radius of the region being described. Try 2.
* @param imageType Type of image being processed.
* @param derivType Type of image used to store the image derivative. null == use default */
public static <I extends ImageSingleBand, D extends ImageSingleBand>
PointTracker<I> dda_ST_NCC(ConfigGeneralDetector configExtract, int describeRadius,
Class<I> imageType, Class<D> derivType) {
if( derivType == null )
derivType = GImageDerivativeOps.getDerivativeType(imageType);
int w = 2*describeRadius+1;
DescribePointPixelRegionNCC<I> alg = FactoryDescribePointAlgs.pixelRegionNCC(w, w, imageType);
GeneralFeatureDetector<I, D> corner = createShiTomasi(configExtract, derivType);
EasyGeneralFeatureDetector<I,D> easy = new EasyGeneralFeatureDetector<I, D>(corner,imageType,derivType);
ScoreAssociateNccFeature score = new ScoreAssociateNccFeature();
AssociateDescription2D<NccFeature> association =
new AssociateDescTo2D<NccFeature>(
FactoryAssociation.greedy(score, Double.MAX_VALUE, true));
DdaManagerGeneralPoint<I,D,NccFeature> manager =
new DdaManagerGeneralPoint<I,D,NccFeature>(easy,new WrapDescribePixelRegionNCC<I>(alg,imageType),1.0);
return new DetectDescribeAssociate<I,NccFeature>(manager, association,false);
}
/**
* Creates a tracker which uses the detect, describe, associate architecture.
*
* @param detector Interest point detector.
* @param orientation Optional orientation estimation algorithm. Can be null.
* @param describe Region description.
* @param associate Description association.
* @param updateDescription After a track has been associated should the description be changed? Try false.
* @param <I> Type of input image.
* @param <Desc> Type of region description
* @return tracker
*/
public static <I extends ImageSingleBand, Desc extends TupleDesc>
DetectDescribeAssociate<I,Desc> dda(InterestPointDetector<I> detector,
OrientationImage<I> orientation ,
DescribeRegionPoint<I, Desc> describe,
AssociateDescription2D<Desc> associate ,
boolean updateDescription ) {
DetectDescribeFusion<I,Desc> fused =
new DetectDescribeFusion<I,Desc>(detector,orientation,describe);
DdaManagerDetectDescribePoint<I,Desc> manager =
new DdaManagerDetectDescribePoint<I,Desc>(fused);
DetectDescribeAssociate<I,Desc> dat =
new DetectDescribeAssociate<I,Desc>(manager, associate,updateDescription);
return dat;
}
public static <I extends ImageSingleBand, Desc extends TupleDesc>
DetectDescribeAssociate<I,Desc> dda( DetectDescribePoint<I, Desc> detDesc,
AssociateDescription2D<Desc> associate ,
boolean updateDescription ) {
DdaManagerDetectDescribePoint<I,Desc> manager =
new DdaManagerDetectDescribePoint<I,Desc>(detDesc);
DetectDescribeAssociate<I,Desc> dat =
new DetectDescribeAssociate<I,Desc>(manager, associate,updateDescription);
return dat;
}
/**
* Creates a tracker which detects Fast-Hessian features, describes them with SURF, nominally tracks them using KLT.
*
* @see DescribePointSurf
* @see boofcv.abst.feature.tracker.DdaManagerDetectDescribePoint
*
* @param trackRadius Size of feature being tracked by KLT
* @param pyramidScalingKlt Image pyramid used for KLT
* @param reactivateThreshold Tracks are reactivated after this many have been dropped. Try 10% of maxMatches
* @param configDetector Configuration for SURF detector
* @param configDescribe Configuration for SURF descriptor
* @param configOrientation Configuration for region orientation
* @param imageType Type of image the input is.
* @param <I> Input image type.
* @return SURF based tracker.
*/
public static <I extends ImageSingleBand>
PointTracker<I> combined_FH_SURF_KLT(int trackRadius,
int[] pyramidScalingKlt ,
int reactivateThreshold ,
ConfigFastHessian configDetector ,
ConfigSurfDescribe.Stablility configDescribe ,
ConfigSlidingIntegral configOrientation ,
Class<I> imageType) {
ScoreAssociation<TupleDesc_F64> score = FactoryAssociation.defaultScore(TupleDesc_F64.class);
AssociateSurfBasic assoc = new AssociateSurfBasic(FactoryAssociation.greedy(score, 100000, true));
AssociateDescription<SurfFeature> generalAssoc = new WrapAssociateSurfBasic(assoc);
DetectDescribePoint<I,SurfFeature> fused =
FactoryDetectDescribe.surfStable(configDetector, configDescribe, configOrientation,
ImageDataType.single(imageType));
return combined(fused,generalAssoc,trackRadius,pyramidScalingKlt,reactivateThreshold,
imageType);
}
/**
* Creates a tracker which detects Shi-Tomasi corner features, describes them with SURF, and
* nominally tracks them using KLT.
*
* @see boofcv.alg.feature.detect.intensity.ShiTomasiCornerIntensity
* @see DescribePointSurf
* @see boofcv.abst.feature.tracker.DdaManagerDetectDescribePoint
*
* @param configExtract Configuration for extracting features
* @param trackRadius Size of feature being tracked by KLT
* @param pyramidScalingKlt Image pyramid used for KLT
* @param reactivateThreshold Tracks are reactivated after this many have been dropped. Try 10% of maxMatches
* @param configDescribe Configuration for SURF descriptor
* @param configOrientation Configuration for region orientation. If null then orientation isn't estimated
* @param imageType Type of image the input is.
* @param derivType Image derivative type.
* @param <I> Input image type.
* @return SURF based tracker.
*/
public static <I extends ImageSingleBand, D extends ImageSingleBand>
PointTracker<I> combined_ST_SURF_KLT(ConfigGeneralDetector configExtract,
int trackRadius,
int[] pyramidScalingKlt ,
int reactivateThreshold ,
ConfigSurfDescribe.Stablility configDescribe,
ConfigSlidingIntegral configOrientation ,
Class<I> imageType,
Class<D> derivType ) {
if( derivType == null )
derivType = GImageDerivativeOps.getDerivativeType(imageType);
GeneralFeatureDetector<I, D> corner = createShiTomasi(configExtract, derivType);
InterestPointDetector<I> detector = FactoryInterestPoint.wrapPoint(corner, 1, imageType, derivType);
DescribeRegionPoint<I,SurfFeature> regionDesc
= FactoryDescribeRegionPoint.surfStable(configDescribe, ImageDataType.single(imageType));
ScoreAssociation<TupleDesc_F64> score = FactoryAssociation.scoreEuclidean(TupleDesc_F64.class, true);
AssociateSurfBasic assoc = new AssociateSurfBasic(FactoryAssociation.greedy(score, 100000, true));
AssociateDescription<SurfFeature> generalAssoc = new WrapAssociateSurfBasic(assoc);
OrientationImage<I> orientation = null;
if( configOrientation != null ) {
Class integralType = GIntegralImageOps.getIntegralType(imageType);
OrientationIntegral orientationII = FactoryOrientationAlgs.sliding_ii(configOrientation, integralType);
orientation = FactoryOrientation.convertImage(orientationII,imageType);
}
return combined(detector,orientation,regionDesc,generalAssoc,trackRadius,pyramidScalingKlt,reactivateThreshold,
imageType);
}
/**
* Creates a tracker that is a hybrid between KLT and Detect-Describe-Associate (DDA) trackers.
*
* @see CombinedTrackerScalePoint
*
* @param detector Feature detector.
* @param orientation Optional feature orientation. Can be null.
* @param describe Feature description
* @param associate Association algorithm.
* @param featureRadiusKlt KLT feature radius
* @param pyramidScalingKlt KLT pyramid configuration
* @param reactivateThreshold Tracks are reactivated after this many have been dropped. Try 10% of maxMatches
* @param imageType Input image type.
* @param <I> Input image type.
* @param <Desc> Feature description type.
* @return Feature tracker
*/
public static <I extends ImageSingleBand, Desc extends TupleDesc>
PointTracker<I> combined( InterestPointDetector<I> detector,
OrientationImage<I> orientation ,
DescribeRegionPoint<I, Desc> describe,
AssociateDescription<Desc> associate ,
int featureRadiusKlt,
int[] pyramidScalingKlt ,
int reactivateThreshold,
Class<I> imageType )
{
DetectDescribeFusion<I,Desc> fused = new DetectDescribeFusion<I,Desc>(detector,orientation,describe);
return combined(fused,associate,featureRadiusKlt,pyramidScalingKlt,reactivateThreshold,imageType);
}
/**
* Creates a tracker that is a hybrid between KLT and Detect-Describe-Associate (DDA) trackers.
*
* @see CombinedTrackerScalePoint
*
* @param detector Feature detector and describer.
* @param associate Association algorithm.
* @param featureRadiusKlt KLT feature radius
* @param pyramidScalingKlt KLT pyramid configuration
* @param reactivateThreshold Tracks are reactivated after this many have been dropped. Try 10% of maxMatches
* @param imageType Input image type.
* @param <I> Input image type.
* @param <D> Derivative image type.
* @param <Desc> Feature description type.
* @return Feature tracker
*/
public static <I extends ImageSingleBand, D extends ImageSingleBand, Desc extends TupleDesc>
PointTracker<I> combined( DetectDescribePoint<I,Desc> detector ,
AssociateDescription<Desc> associate ,
int featureRadiusKlt,
int[] pyramidScalingKlt ,
int reactivateThreshold,
Class<I> imageType )
{
Class<D> derivType = GImageDerivativeOps.getDerivativeType(imageType);
CombinedTrackerScalePoint<I, D,Desc> tracker =
FactoryTrackerAlg.combined(detector,associate,featureRadiusKlt,pyramidScalingKlt,
imageType,derivType);
return new PointTrackerCombined<I,D,Desc>(tracker,reactivateThreshold,imageType,derivType);
}
public static <I extends ImageSingleBand, D extends ImageSingleBand, Desc extends TupleDesc>
PointTracker<I> dda(GeneralFeatureDetector<I, D> detector,
DescribeRegionPoint<I, Desc> describe,
AssociateDescription2D<Desc> associate,
double scale,
Class<I> imageType) {
EasyGeneralFeatureDetector<I,D> easy = new EasyGeneralFeatureDetector<I, D>(detector,imageType,null);
DdaManagerGeneralPoint<I,D,Desc> manager =
new DdaManagerGeneralPoint<I,D,Desc>(easy,describe,scale);
return new DetectDescribeAssociate<I,Desc>(manager,associate,false);
}
/**
* Creates a Shi-Tomasi corner detector specifically designed for SFM. Smaller feature radius work better.
* Variable detectRadius to control the number of features. When larger features are used weighting should
* be set to true, but because this is so small, it is set to false
*/
public static <I extends ImageSingleBand, D extends ImageSingleBand>
GeneralFeatureDetector<I, D> createShiTomasi(ConfigGeneralDetector config ,
Class<D> derivType)
{
GradientCornerIntensity<D> cornerIntensity = FactoryIntensityPointAlg.shiTomasi(1, false, derivType);
return FactoryDetectPoint.createGeneral(cornerIntensity, config );
}
} | apache-2.0 |
evandor/skysail | skysail.server.queryfilter/test/io/skysail/server/queryfilter/parser/test/FilterParamUtilsTest.java | 10612 | package io.skysail.server.queryfilter.parser.test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.restlet.Request;
import org.restlet.data.Form;
import org.restlet.data.Parameter;
import org.restlet.data.Reference;
import io.skysail.server.domain.jvm.FieldFacet;
import io.skysail.server.domain.jvm.facets.MatcherFacet;
import io.skysail.server.domain.jvm.facets.NumberFacet;
import io.skysail.server.domain.jvm.facets.YearFacet;
import io.skysail.server.queryfilter.parser.LdapParser;
import io.skysail.server.utils.params.FilterParamUtils;
import lombok.SneakyThrows;
/**
* these tests use the real {@link LdapParser} implementation of the queryfilter bundle.
*
* see io.skysail.server.utils.params.test.FilterParamUtilsTest
*
*/
public class FilterParamUtilsTest {
private Reference originalRef;
private Form form;
private Request request = mock(Request.class);
private Map<String, String> numberFacetConfig;
private Map<String, String> yearFacetConfig;
@Before
public void setUp() {
form = new Form();
originalRef = Mockito.mock(org.restlet.data.Reference.class);
when(request.getOriginalRef()).thenReturn(originalRef);
when(originalRef.hasQuery()).thenReturn(true);
when(originalRef.getQuery()).thenReturn(form.getQueryString());
when(originalRef.getQueryAsForm()).thenReturn(form);
when(originalRef.getHierarchicalPart()).thenReturn("");
numberFacetConfig = new HashMap<>();
numberFacetConfig.put("BORDERS", "0,100");
yearFacetConfig = new HashMap<>();
yearFacetConfig.put("START", "2014");
yearFacetConfig.put("END", "2016");
}
// === NumberFacet Tests ====================================
@Test
@SneakyThrows
public void setMatch_with_valid_bucket_ids_on_numberFacet_without_existing_filterParam_yields_proper_filterParams() {
FieldFacet facet = new NumberFacet("a", numberFacetConfig);
FilterParamUtils filterParamUtils = new FilterParamUtils("a", request,new LdapParser());
assertThat(decode(filterParamUtils.setMatchFilter("0",facet)), is("?_f=(a<0.0)"));
assertThat(decode(filterParamUtils.setMatchFilter("1",facet)), is("?_f=(&(a>0.0)(a<100.0))"));
assertThat(decode(filterParamUtils.setMatchFilter("2",facet)), is("?_f=(a>100.0)"));
}
@Test
@SneakyThrows
public void setMatch_with_valid_bucket_ids_on_numberFacet_with_existing_filterParam_yields_proper_filterParams() {
form.add(new Parameter("_f", "(a<0.0)"));
FieldFacet facet = new NumberFacet("a", numberFacetConfig);
FilterParamUtils filterParamUtils = new FilterParamUtils("a", request,new LdapParser());
assertThat(decode(filterParamUtils.setMatchFilter("0",facet)), is("?_f=(a<0.0)"));
assertThat(decode(filterParamUtils.setMatchFilter("1",facet)), is("?_f=(|(a<0.0)(&(a>0.0)(a<100.0)))"));
assertThat(decode(filterParamUtils.setMatchFilter("2",facet)), is("?_f=(|(a<0.0)(a>100.0))"));
}
@Test
@SneakyThrows
public void setMatch_with_valid_bucket_ids_on_numberFacet_with_other_filterParam_yields_proper_filterParams() {
form.add(new Parameter("_f", "(b>0.0)"));
FieldFacet facet = new NumberFacet("a", numberFacetConfig);
FilterParamUtils filterParamUtils = new FilterParamUtils("a", request,new LdapParser());
assertThat(decode(filterParamUtils.setMatchFilter("0",facet)), is("?_f=(&(b>0.0)(a<0.0))"));
assertThat(decode(filterParamUtils.setMatchFilter("1",facet)), is("?_f=(&(b>0.0)(&(a>0.0)(a<100.0)))"));
assertThat(decode(filterParamUtils.setMatchFilter("2",facet)), is("?_f=(&(b>0.0)(a>100.0))"));
}
@Test
@SneakyThrows
public void reduceMatch_with_valid_bucket_ids_on_numberFacet_without_existing_filterParam_yields_proper_filterParams() {
FieldFacet facet = new NumberFacet("a", numberFacetConfig);
FilterParamUtils filterParamUtils = new FilterParamUtils("a", request,new LdapParser());
assertThat(decode(filterParamUtils.reduceMatchFilter("0",facet,null)), is("?_f=(a<0.0)"));
// assertThat(decode(filterParamUtils.reduceMatchFilter("1",facet,null)), is("?_f=(a<0.0)"));
// assertThat(decode(filterParamUtils.reduceMatchFilter("2",facet,null)), is("?_f=(a<0.0)"));
}
@Test
@SneakyThrows
public void reduceMatch_with_valid_bucket_ids_on_numberFacet_with_existing_filterParam_yields_proper_filterParams() {
form.add(new Parameter("_f", "(a<0.0)"));
FieldFacet facet = new NumberFacet("a", numberFacetConfig);
FilterParamUtils filterParamUtils = new FilterParamUtils("a", request,new LdapParser());
assertThat(decode(filterParamUtils.reduceMatchFilter("0",facet,null)), is(""));
assertThat(decode(filterParamUtils.reduceMatchFilter("1",facet,null)), is("?_f=(a<0.0)"));
assertThat(decode(filterParamUtils.reduceMatchFilter("2",facet,null)), is("?_f=(a<0.0)"));
}
@Test
@SneakyThrows
public void reduceMatch_with_valid_bucket_ids_on_numberFacet_with_other_filterParam_yields_proper_filterParams() {
form.add(new Parameter("_f", "(b>0.0)"));
FieldFacet facet = new NumberFacet("a", numberFacetConfig);
FilterParamUtils filterParamUtils = new FilterParamUtils("a", request,new LdapParser());
assertThat(decode(filterParamUtils.reduceMatchFilter("0",facet,null)), is("?_f=(b>0.0)"));
assertThat(decode(filterParamUtils.reduceMatchFilter("1",facet,null)), is("?_f=(b>0.0)"));
assertThat(decode(filterParamUtils.reduceMatchFilter("2",facet,null)), is("?_f=(b>0.0)"));
}
@Test
@SneakyThrows
public void reduceMatch_with_valid_bucket_ids_on_numberFacet_with_existing_partial_filterParam_yields_proper_filterParams() {
form.add(new Parameter("_f", "(|(a<0.0)(&(a>0.0)(a<100.0)))"));
FieldFacet facet = new NumberFacet("a", numberFacetConfig);
FilterParamUtils filterParamUtils = new FilterParamUtils("a", request,new LdapParser());
// assertThat(decode(filterParamUtils.reduceMatchFilter("0",facet,null)), is("?_f=(&(a>0.0)(a<100.0))"));
assertThat(decode(filterParamUtils.reduceMatchFilter("1",facet,null)), is("?_f=(a<0.0)"));
// assertThat(decode(filterParamUtils.reduceMatchFilter("2",facet,null)), is("?_f=(|(a<0.0)(&(a>0.0)(a<100.0)))"));
}
// === YearFacet Tests ====================================
@Test
@SneakyThrows
public void setMatch_with_valid_bucket_ids_on_yearFacet_without_existing_filterParam_yields_proper_filterParams2() {
YearFacet facet = new YearFacet("a", yearFacetConfig);
FilterParamUtils filterParamUtils = new FilterParamUtils("a", request, new LdapParser());
assertThat(decode(filterParamUtils.setMatchFilter("2014",facet)), is("?_f=(a=2014)"));
assertThat(decode(filterParamUtils.setMatchFilter("2015",facet)), is("?_f=(a=2015)"));
assertThat(decode(filterParamUtils.setMatchFilter("2016",facet)), is("?_f=(a=2016)"));
}
@Test
@SneakyThrows
public void setMatch_with_valid_bucket_ids_on_yearFacet_with_existing_filterParam_yields_proper_filterParams2() {
form.add(new Parameter("_f", "(a=2014)"));
YearFacet facet = new YearFacet("a", yearFacetConfig);
FilterParamUtils filterParamUtils = new FilterParamUtils("a", request, new LdapParser());
assertThat(decode(filterParamUtils.setMatchFilter("2014",facet)), is("?_f=(a=2014)"));
assertThat(decode(filterParamUtils.setMatchFilter("2015",facet)), is("?_f=(|(a=2014)(a=2015))"));
assertThat(decode(filterParamUtils.setMatchFilter("2016",facet)), is("?_f=(|(a=2014)(a=2016))"));
}
@Test
@SneakyThrows
public void setMatch_with_valid_bucket_ids_on_yearFacet_with_other_filterParam_yields_proper_filterParams2() {
form.add(new Parameter("_f", "(b=2012)"));
YearFacet facet = new YearFacet("a", yearFacetConfig);
FilterParamUtils filterParamUtils = new FilterParamUtils("a", request, new LdapParser());
assertThat(decode(filterParamUtils.setMatchFilter("2014",facet)), is("?_f=(&(b=2012)(a=2014))"));
assertThat(decode(filterParamUtils.setMatchFilter("2015",facet)), is("?_f=(&(b=2012)(a=2015))"));
assertThat(decode(filterParamUtils.setMatchFilter("2016",facet)), is("?_f=(&(b=2012)(a=2016))"));
}
// === MatcherFacet Tests ====================================
@Test
@SneakyThrows
public void setMatch_with_valid_bucket_ids_on_matcherFacet_without_existing_filterParam_yields_proper_filterParams2() {
MatcherFacet facet = new MatcherFacet("a",Collections.emptyMap());
FilterParamUtils filterParamUtils = new FilterParamUtils("a", request, new LdapParser());
assertThat(decode(filterParamUtils.setMatchFilter("xxx",facet,"YYYY")), is("?_f=(a;YYYY=xxx)"));
}
@Test
@SneakyThrows
public void setMatch_with_valid_bucket_ids_on_matcherFacet_with_existing_filterParam_yields_proper_filterParams2() {
form.add(new Parameter("_f", "(a;YYYY=xxx)"));
MatcherFacet facet = new MatcherFacet("a",Collections.emptyMap());
FilterParamUtils filterParamUtils = new FilterParamUtils("a", request, new LdapParser());
assertThat(decode(filterParamUtils.setMatchFilter("xxx",facet,"YYYY")), is("?_f=(a;YYYY=xxx)"));
assertThat(decode(filterParamUtils.setMatchFilter("yyy",facet,"YYYY")), is("?_f=(|(a;YYYY=xxx)(a;YYYY=yyy))"));
}
@Test
@SneakyThrows
public void setMatch_with_valid_bucket_ids_on_matcherFacet_with_other_filterParam_yields_proper_filterParams2() {
form.add(new Parameter("_f", "(b=xxx)"));
MatcherFacet facet = new MatcherFacet("a",Collections.emptyMap());
FilterParamUtils filterParamUtils = new FilterParamUtils("a", request, new LdapParser());
assertThat(decode(filterParamUtils.setMatchFilter("xxx",facet,"YYYY")), is("?_f=(&(b=xxx)(a;YYYY=xxx))"));
assertThat(decode(filterParamUtils.setMatchFilter("yyy",facet,"YYYY")), is("?_f=(&(b=xxx)(a;YYYY=yyy))"));
}
private String decode(String string) throws UnsupportedEncodingException {
return java.net.URLDecoder.decode(string, "UTF-8");
}
}
| apache-2.0 |
bazi/ninja | ninja-servlet-integration-test/src/test/java/conf/RoutesTest.java | 5600 | /**
* Copyright (C) 2012-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 conf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.util.Map;
import ninja.NinjaRouterTest;
import org.junit.Test;
import com.google.common.collect.Maps;
import controllers.ApplicationController;
/**
*
* Remove me once NinjaRouterTest has been put to rest.
*
* @author ra
* @deprecated
*/
@Deprecated
public class RoutesTest extends NinjaRouterTest {
@Test
public void testTestRoutesAreHiddenFromProduction() {
startServerInProdMode();
//test that test route is not available in production mode.
aRequestLike("GET", "/_test/testPage").isNotHandledByRoutesInRouter();
}
@Test
public void testRoutes() {
startServer();
//some tests that routes are there:
aRequestLike("GET", "/").isHandledBy(ApplicationController.class, "index");
}
@Test
public void testReverseRoutingWithoutMap() {
startServer();
// TEST 1: a simple route without replacements:
String generatedReverseRoute = router.getReverseRoute(ApplicationController.class, "index");
assertEquals("/", generatedReverseRoute);
// TEST 2: a more complex route with replacements:
//router.GET().route("/user/{id}/{email}/userDashboard").with(ApplicationController.class, "userDashboard");
generatedReverseRoute = router.getReverseRoute(ApplicationController.class, "userDashboard");
// this looks strange, but is expected:
assertEquals(null, generatedReverseRoute);
}
@Test
public void testReverseRoutingWithMap() {
startServer();
// TEST 1: a simple route without replacements:
Map<String, Object> map = Maps.newHashMap();
String generatedReverseRoute = router.getReverseRoute(ApplicationController.class, "index", map);
assertEquals("/", generatedReverseRoute);
// TEST 2: a more complex route with replacements:
//router.GET().route("/user/{id}/{email}/userDashboard").with(ApplicationController.class, "userDashboard");
map = Maps.newHashMap();
map.put("id","myId");
map.put("email","myEmail");
generatedReverseRoute = router.getReverseRoute(ApplicationController.class, "userDashboard", map);
assertEquals("/user/myId/myEmail/userDashboard", generatedReverseRoute);
}
@Test
public void testReverseRoutingWithMapAndQueryParameter() {
startServer();
// TEST 2: a more complex route with replacements and query parameters
//router.GET().route("/user/{id}/{email}/userDashboard").with(ApplicationController.class, "userDashboard");
Map<String, Object> map = Maps.newHashMap();
map.put("id","myId");
map.put("email","myEmail");
map.put("paging_size","100");
map.put("page","1");
String generatedReverseRoute = router.getReverseRoute(ApplicationController.class, "userDashboard", map);
assertThat(generatedReverseRoute, containsString("page=1"));
assertThat(generatedReverseRoute, containsString("paging_size=100"));
assertThat(generatedReverseRoute, containsString("/user/myId/myEmail/userDashboard?"));
}
@Test
public void testReverseRoutingWithArrayAndQueryParameters() {
startServer();
String generatedReverseRoute = router.getReverseRoute(
ApplicationController.class,
"userDashboard",
"id","myId",
"email","myEmail",
"paging_size","100",
"page","1");
assertThat(generatedReverseRoute, containsString("page=1"));
assertThat(generatedReverseRoute, containsString("paging_size=100"));
assertThat(generatedReverseRoute, containsString("/user/myId/myEmail/userDashboard?"));
}
@Test
public void testReverseRoutingWithArrayAndWrongAmountOfQueryParameters() {
startServer();
// TEST 2: a more complex route with replacements and query parameters
//router.GET().route("/user/{id}/{email}/userDashboard").with(ApplicationController.class, "userDashboard");
Map<String, Object> map = Maps.newHashMap();
map.put("id","myId");
map.put("email","myEmail");
map.put("paging_size","100");
map.put("page","1");
String generatedReverseRoute = router.getReverseRoute(
ApplicationController.class,
"userDashboard",
"1", "2", "3");
assertEquals(null, generatedReverseRoute);
}
}
| apache-2.0 |
OpenUniversity/ovirt-engine | backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/SetNonOperationalVdsCommand.java | 6809 | package org.ovirt.engine.core.bll;
import java.util.List;
import java.util.Map.Entry;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.job.ExecutionContext;
import org.ovirt.engine.core.bll.job.ExecutionHandler;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.action.SetNonOperationalVdsParameters;
import org.ovirt.engine.core.common.businessentities.NonOperationalReason;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterBrickEntity;
import org.ovirt.engine.core.common.businessentities.gluster.GlusterStatus;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.utils.threadpool.ThreadPoolUtil;
/**
* This command will try to migrate all the vds vms (if needed) and move the vds
* to Non-Operational state
*/
@SuppressWarnings("serial")
@NonTransactiveCommandAttribute
public class SetNonOperationalVdsCommand<T extends SetNonOperationalVdsParameters> extends MaintenanceVdsCommand<T> {
public SetNonOperationalVdsCommand(T parameters) {
this(parameters, null);
}
public SetNonOperationalVdsCommand(T parameters, CommandContext commandContext) {
super(parameters, commandContext);
setStorageDomainId(parameters.getStorageDomainId());
}
/**
* Note: it's ok that this method isn't marked as async command even though it triggers
* migrations as sub-commands, because those migrations are executed as different jobs
*/
@Override
protected void executeCommand() {
setVdsStatus(VDSStatus.NonOperational, getParameters().getNonOperationalReason());
if (getCluster() != null && getCluster().supportsGlusterService()) {
updateBrickStatusDown();
}
// if host failed to recover, no point in sending migrate, as it would fail.
if (getParameters().getNonOperationalReason() != NonOperationalReason.TIMEOUT_RECOVERING_FROM_CRASH) {
orderListOfRunningVmsOnVds(getVdsId());
ThreadPoolUtil.execute(() -> {
// migrate vms according to cluster migrateOnError option
switch (getCluster().getMigrateOnError()) {
case YES:
migrateAllVms(getExecutionContext());
break;
case HA_ONLY:
migrateAllVms(getExecutionContext(), true);
break;
default:
break;
}
});
}
if (getParameters().getNonOperationalReason() == NonOperationalReason.NETWORK_UNREACHABLE) {
log.error("Host '{}' is set to Non-Operational, it is missing the following networks: '{}'",
getVds().getName(), getParameters().getCustomLogValues().get("Networks"));
}
if (getParameters().getNonOperationalReason() == NonOperationalReason.VM_NETWORK_IS_BRIDGELESS) {
log.error("Host '{}' is set to Non-Operational, the following networks are implemented as non-VM"
+ " instead of a VM networks: '{}'",
getVds().getName(), getParameters().getCustomLogValues().get("Networks"));
}
setSucceeded(true);
}
private void updateBrickStatusDown() {
List<GlusterBrickEntity> brickEntities = getDbFacade().getGlusterBrickDao().getGlusterVolumeBricksByServerId(getVdsId());
for (GlusterBrickEntity brick : brickEntities) {
brick.setStatus(GlusterStatus.DOWN);
}
getDbFacade().getGlusterBrickDao().updateBrickStatuses(brickEntities);
}
@Override
protected CommandContext createMigrateVmContext(ExecutionContext parentContext, VM vm) {
return ExecutionHandler.createInternalJobContext(getContext());
}
@Override
protected boolean validate() {
boolean result = true;
if (getVds() == null) {
addValidationMessage(EngineMessage.VDS_INVALID_SERVER_ID);
result = false;
}
return result;
}
@Override
public AuditLogType getAuditLogTypeValue() {
for (Entry<String, String> e : getParameters().getCustomLogValues().entrySet()) {
addCustomValue(e.getKey(), e.getValue());
}
switch (getParameters().getNonOperationalReason()) {
case NETWORK_UNREACHABLE:
return getSucceeded() ? AuditLogType.VDS_SET_NONOPERATIONAL_NETWORK
: AuditLogType.VDS_SET_NONOPERATIONAL_FAILED;
case STORAGE_DOMAIN_UNREACHABLE:
return getSucceeded() ? AuditLogType.VDS_SET_NONOPERATIONAL_DOMAIN
: AuditLogType.VDS_SET_NONOPERATIONAL_DOMAIN_FAILED;
case TIMEOUT_RECOVERING_FROM_CRASH:
return AuditLogType.VDS_RECOVER_FAILED;
case KVM_NOT_RUNNING:
return AuditLogType.VDS_RUN_IN_NO_KVM_MODE;
case VERSION_INCOMPATIBLE_WITH_CLUSTER:
return AuditLogType.VDS_VERSION_NOT_SUPPORTED_FOR_CLUSTER;
case CLUSTER_VERSION_INCOMPATIBLE_WITH_CLUSTER:
return AuditLogType.VDS_CLUSTER_VERSION_NOT_SUPPORTED;
case VM_NETWORK_IS_BRIDGELESS:
return AuditLogType.VDS_SET_NON_OPERATIONAL_VM_NETWORK_IS_BRIDGELESS;
case GLUSTER_COMMAND_FAILED:
return AuditLogType.GLUSTER_COMMAND_FAILED;
case GLUSTER_HOST_UUID_NOT_FOUND:
return AuditLogType.GLUSTER_HOST_UUID_NOT_FOUND;
case GLUSTER_HOST_UUID_ALREADY_EXISTS:
return AuditLogType.GLUSTER_HOST_UUID_ALREADY_EXISTS;
case EMULATED_MACHINES_INCOMPATIBLE_WITH_CLUSTER:
return AuditLogType.EMULATED_MACHINES_INCOMPATIBLE_WITH_CLUSTER;
case EMULATED_MACHINES_INCOMPATIBLE_WITH_CLUSTER_LEVEL:
return AuditLogType.EMULATED_MACHINES_INCOMPATIBLE_WITH_CLUSTER_LEVEL;
case RNG_SOURCES_INCOMPATIBLE_WITH_CLUSTER:
return AuditLogType.RNG_SOURCES_INCOMPATIBLE_WITH_CLUSTER;
case MIXING_RHEL_VERSIONS_IN_CLUSTER:
return AuditLogType.MIXING_RHEL_VERSIONS_IN_CLUSTER;
case UNTRUSTED:
return AuditLogType.VDS_UNTRUSTED;
case HOST_FEATURES_INCOMPATIBILE_WITH_CLUSTER:
return AuditLogType.HOST_FEATURES_INCOMPATIBILE_WITH_CLUSTER;
case LIBRBD_PACKAGE_NOT_AVAILABLE:
return AuditLogType.NO_LIBRBD_PACKAGE_AVAILABLE_ON_VDS;
case VDS_CANNOT_CONNECT_TO_GLUSTERFS:
return AuditLogType.VDS_CANNOT_CONNECT_TO_GLUSTERFS;
default:
return getSucceeded() ? AuditLogType.VDS_SET_NONOPERATIONAL : AuditLogType.VDS_SET_NONOPERATIONAL_FAILED;
}
}
}
| apache-2.0 |
consulo/consulo-soy | src/main/java/com/google/bamboo/soy/parser/impl/SoyNamespaceDeclarationIdentifierImpl.java | 1581 | // This is a generated file. Not intended for manual editing.
package com.google.bamboo.soy.parser.impl;
import java.util.List;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiElementVisitor;
import com.intellij.psi.util.PsiTreeUtil;
import static com.google.bamboo.soy.parser.SoyTypes.*;
import com.google.bamboo.soy.elements.impl.NamespaceDeclarationMixin;
import com.google.bamboo.soy.parser.*;
import com.google.bamboo.soy.stubs.NamespaceDeclarationStub;
import com.intellij.psi.stubs.IStubElementType;
import com.intellij.psi.tree.IElementType;
public class SoyNamespaceDeclarationIdentifierImpl extends NamespaceDeclarationMixin implements SoyNamespaceDeclarationIdentifier {
public SoyNamespaceDeclarationIdentifierImpl(NamespaceDeclarationStub stub, IStubElementType type) {
super(stub, type);
}
public SoyNamespaceDeclarationIdentifierImpl(ASTNode node) {
super(node);
}
public SoyNamespaceDeclarationIdentifierImpl(NamespaceDeclarationStub stub, IElementType type, ASTNode node) {
super(stub, type, node);
}
public void accept(@Nonnull SoyVisitor visitor) {
visitor.visitNamespaceDeclarationIdentifier(this);
}
public void accept(@Nonnull PsiElementVisitor visitor) {
if (visitor instanceof SoyVisitor) accept((SoyVisitor)visitor);
else super.accept(visitor);
}
@Override
@Nonnull
public PsiElement getQualifiedIdentifier() {
return notNullChild(findChildByType(QUALIFIED_IDENTIFIER));
}
}
| apache-2.0 |
kris-sigur/jwat | jwat-common/src/main/java/org/jwat/common/HeaderLineReader.java | 28402 | /**
* Java Web Archive Toolkit - Software to read and validate ARC, WARC
* and GZip files. (http://jwat.org/)
* Copyright 2011-2012 Netarkivet.dk (http://netarkivet.dk/)
*
* 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.jwat.common;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
/**
* Advanced header/line reader which can be configured into difference modes.
* The reader can either read normal lines or header lines.
* Supported encodings are raw, US-ASCII, ISO-8859-1 and UTF-8.
*
* Furthermore header lines can employ linear white space (LWS), quoted text
* and encoded words.
*
* After calling the readLine method additional information is available from
* public fields on the reader.
*
* @author nicl
*/
public class HeaderLineReader {
/*
* Internal states.
*/
/** Initial state for reading a normal line. */
protected static final int S_LINE = 0;
/** Initial state for reading a header line. */
protected static final int S_NAME = 1;
/** State for reading a header value. */
protected static final int S_VALUE = 2;
/** State for reading a LWS character sequence. */
protected static final int S_LWS = 3;
/** State for reading a quoted string. */
protected static final int S_QUOTED_TEXT = 4;
/** State for reading a quoted pair character. */
protected static final int S_QUOTED_PAIR = 5;
/** State for reading a quoted LWS character sequence. */
protected static final int S_QUOTED_LWS = 6;
/** Status for reading an encoded word character sequence. */
protected static final int S_ENCODED_WORD_EQ = 7;
/*
* 8-bit character characteristics.
*/
/** Control character characteristic. */
protected static final int CC_CONTROL = 1;
/** Separator character characteristic. */
protected static final int CC_SEPARATOR_WS = 2;
/** rfc2616 separator characters. */
public static final String separatorsWs = "()<>@,;:\\\"/[]?={} \t";
/** Table of separator characters. */
public static final byte[] charCharacteristicsTab = new byte[256];
/**
* Populate table of separators.
*/
static {
for (int i=0; i<32; ++i) {
if (i != '\t') {
charCharacteristicsTab[i] |= CC_CONTROL;
}
}
charCharacteristicsTab[127] |= CC_CONTROL;
for (int i=0; i<separatorsWs.length(); ++i) {
charCharacteristicsTab[separatorsWs.charAt(i)] |= CC_SEPARATOR_WS;
}
}
/*
* Encoding.
*/
/** Raw encoding identifier. */
public static final int ENC_RAW = 0;
/** US-ASCII encoding identifier. */
public static final int ENC_US_ASCII = 1;
/** ISO-8859-1 encoding identifier. */
public static final int ENC_ISO8859_1 = 2;
/** UTF-8 encoding identifier. */
public static final int ENC_UTF8 = 3;
/** Reusable UTF-8 validation object instance. */
protected final UTF8 utf8 = new UTF8();
/*
* EOL.
*/
/** LF end of line identifier. */
public static final int EOL_LF = 0;
/** CRLF end of line identifier. */
public static final int EOL_CRLF = 1;
/*
* Configuration.
*/
/** Parses a headerline if true and a normal line if false. */
public boolean bNameValue;
/** Identifier for the expected character encoding. */
public int encoding = ENC_RAW;
/** Identifier for the Expected end of line character sequence. */
public int eol = EOL_CRLF;
/** Support LWS. */
public boolean bLWS;
/** Support quoted text. */
public boolean bQuotedText;
/** Support encoded words. */
public boolean bEncodedWords;
/** Reusable <code>StringBuffer</code> for lines. */
protected final StringBuffer lineSb = new StringBuffer();
/** Reusable <code>StringBuffer</code> for name/value strings. */
protected final StringBuffer nvSb = new StringBuffer();
/** Stream used to record the raw characters read by the parser. */
protected ByteArrayOutputStreamWithUnread bytesOut = new ByteArrayOutputStreamWithUnread();
/*
* Error reporting.
*/
/** Bit denoting unexpected EOF. */
public static final int E_BIT_EOF = 1 << 0;
/** Bit denoting a misplaced CR. */
public static final int E_BIT_MISPLACED_CR = 1 << 1;
/** Bit denoting a missing CR. */
public static final int E_BIT_MISSING_CR = 1 << 2;
/** Bit denoting an unexpected CR. */
public static final int E_BIT_UNEXPECTED_CR = 1 << 3;
/** Bit denoting an invalid UTF-8 encoded character. */
public static final int E_BIT_INVALID_UTF8_ENCODING = 1 << 4;
/** Bit denoting an invalid US-ASCII character. */
public static final int E_BIT_INVALID_US_ASCII_CHAR = 1 << 5;
/** Bit denoting an invalid control character. */
public static final int E_BIT_INVALID_CONTROL_CHAR = 1 << 6;
/** Bit denoting an invalid separator character. */
public static final int E_BIT_INVALID_SEPARATOR_CHAR = 1 << 7;
/** Bit denoting a missing quote character. */
public static final int E_BIT_MISSING_QUOTE = 1 << 8;
/** Bit denoting a missing quoted pair character. */
public static final int E_BIT_MISSING_QUOTED_PAIR_CHAR = 1 << 9;
/** Bit denoting an invalid quoted pair character. */
public static final int E_BIT_INVALID_QUOTED_PAIR_CHAR = 1 << 10;
/*
* Internal state.
*/
/** True if the previous character was a CR. */
protected boolean bCr = false;
/** Used by decode method to indicated valid or non valid character. */
protected boolean bValidChar;
/*
* Exposed state.
*/
/** Boolean indicating whether or not EOF has been reached on stream. */
public boolean bEof;
/** Bit field of errors encountered while attempting to read a line. */
public int bfErrors;
/**
* Prohibit public construction.
*/
protected HeaderLineReader() {
}
/**
* Returns a reader with default configuration values.
* @return a reader with default configuration values
*/
public static HeaderLineReader getReader() {
return new HeaderLineReader();
}
/**
* Returns a reader initialized to read normal lines.
* Normal lines being lines with no LWS or key:value headers.
* The reader is configured to expect US-ASCII characters.
* @return a reader to read normal lines
*/
public static HeaderLineReader getLineReader() {
HeaderLineReader hlr = new HeaderLineReader();
hlr.bNameValue = false;
hlr.encoding = ENC_US_ASCII;
return hlr;
}
/**
* Returns a reader initialized to read header lines.
* The reader is configured to expect ISO-8859-1 encoding, LWS,
* quoted text and encoded words. Besides reading key:value headers it will
* also read and return normal lines as defined in the method above.
* @return a reader to read header lines
*/
public static HeaderLineReader getHeaderLineReader() {
HeaderLineReader hlr = new HeaderLineReader();
hlr.bNameValue = true;
hlr.encoding = ENC_ISO8859_1;
//hlr.eol
hlr.bLWS = true;
hlr.bQuotedText = true;
hlr.bEncodedWords = true;
return hlr;
}
/**
* Reads a header/line according to the configuration.
* After calling the readLine method additional information is available
* from public fields on the reader.
* @param in <code>InputStream</code> with characters
* @return result wrapped in a <code>HeaderLine</code> object
* @throws IOException if an i/o error occurs in the underlying input stream
*/
public HeaderLine readLine(PushbackInputStream in) throws IOException {
HeaderLine headerLine = new HeaderLine();
int state;
if (!bNameValue) {
state = S_LINE;
} else {
state = S_NAME;
}
lineSb.setLength(0);
nvSb.setLength(0);
bytesOut = new ByteArrayOutputStreamWithUnread();
bfErrors = 0;
int c;
bCr = false;
boolean bLoop = true;
while (bLoop) {
c = in.read();
if (c != -1) {
bytesOut.write(c);
}
switch (state) {
case S_LINE:
switch (c) {
case -1:
// EOF.
bfErrors |= E_BIT_EOF;
headerLine.type = HeaderLine.HLT_LINE;
headerLine.line = lineSb.toString();
lineSb.setLength(0);
bLoop = false;
break;
case '\r':
bCr = true;
break;
case '\n':
headerLine.type = HeaderLine.HLT_LINE;
headerLine.line = lineSb.toString();
lineSb.setLength(0);
// Check EOL.
check_eol();
bLoop = false;
break;
default:
if (bCr) {
// Misplaced CR.
bfErrors |= E_BIT_MISPLACED_CR;
bCr = false;
}
// Decode character.
c = decode(c, in);
if (c == -1) {
// EOF.
bfErrors |= E_BIT_EOF;
headerLine.type = HeaderLine.HLT_LINE;
headerLine.line = lineSb.toString();
lineSb.setLength(0);
bLoop = false;
} else {
if (bValidChar && encoding != ENC_RAW) {
if (c < 256 && ((charCharacteristicsTab[c] & CC_CONTROL) == CC_CONTROL)) {
bValidChar = false;
// Invalid control char
bfErrors |= E_BIT_INVALID_CONTROL_CHAR;
}
}
if (bValidChar) {
lineSb.append((char) c);
}
}
break;
}
break;
case S_NAME:
switch (c) {
case -1:
// EOF.
bfErrors |= E_BIT_EOF;
headerLine.type = HeaderLine.HLT_LINE;
headerLine.line = lineSb.toString();
lineSb.setLength(0);
nvSb.setLength(0);
bLoop = false;
break;
case '\r':
bCr = true;
break;
case '\n':
headerLine.type = HeaderLine.HLT_LINE;
headerLine.line = lineSb.toString();
lineSb.setLength(0);
nvSb.setLength(0);
// Check EOL.
check_eol();
bLoop = false;
break;
case ':':
headerLine.type = HeaderLine.HLT_HEADERLINE;
headerLine.name = nvSb.toString();
lineSb.setLength(0);
nvSb.setLength(0);
if (bCr) {
// Misplaced CR.
bfErrors |= E_BIT_MISPLACED_CR;
bCr = false;
}
state = S_VALUE;
break;
default:
if (bCr) {
// Misplaced CR.
bfErrors |= E_BIT_MISPLACED_CR;
bCr = false;
}
// Decode character.
c = decode(c, in);
if (c == -1) {
// EOF.
bfErrors |= E_BIT_EOF;
headerLine.type = HeaderLine.HLT_LINE;
headerLine.line = lineSb.toString();
lineSb.setLength(0);
nvSb.setLength(0);
bLoop = false;
} else {
if (bValidChar && encoding != ENC_RAW) {
if (c < 256 && ((charCharacteristicsTab[c] & CC_CONTROL) == CC_CONTROL)) {
bValidChar = false;
// Invalid control char
bfErrors |= E_BIT_INVALID_CONTROL_CHAR;
}
}
if (bValidChar) {
lineSb.append((char) c);
if (c < 256 && ((charCharacteristicsTab[c] & CC_SEPARATOR_WS) == CC_SEPARATOR_WS)) {
bValidChar = false;
// Invalid separator in name
bfErrors |= E_BIT_INVALID_SEPARATOR_CHAR;
}
}
if (bValidChar) {
nvSb.append((char) c);
}
}
break;
}
break;
case S_VALUE:
switch (c) {
case -1:
// EOF.
bfErrors |= E_BIT_EOF;
headerLine.value = trim(nvSb);
nvSb.setLength(0);
bLoop = false;
break;
case '\r':
bCr = true;
break;
case '\n':
// Check EOL.
check_eol();
if (bLWS) {
state = S_LWS;
} else {
headerLine.value = trim(nvSb);
nvSb.setLength(0);
bLoop = false;
}
break;
default:
if (bCr) {
// Misplaced CR.
bfErrors |= E_BIT_MISPLACED_CR;
bCr = false;
}
// Decode character.
c = decode(c, in);
if (c == -1) {
// EOF.
bfErrors |= E_BIT_EOF;
headerLine.value = trim(nvSb);
nvSb.setLength(0);
bLoop = false;
} else {
if (bValidChar && encoding != ENC_RAW) {
if (c < 256 && ((charCharacteristicsTab[c] & CC_CONTROL) == CC_CONTROL)) {
bValidChar = false;
// Invalid control char
bfErrors |= E_BIT_INVALID_CONTROL_CHAR;
}
}
if (bValidChar) {
switch (c) {
case '\"':
nvSb.append((char)c);
if (bQuotedText) {
state = S_QUOTED_TEXT;
}
break;
case '=':
if (bEncodedWords) {
state = S_ENCODED_WORD_EQ;
} else {
nvSb.append((char)c);
}
break;
default:
nvSb.append((char)c);
break;
}
}
}
break;
}
break;
case S_LWS:
switch (c) {
case -1:
// EOF.
//bfErrors |= E_BIT_EOF;
headerLine.value = trim(nvSb);
nvSb.setLength(0);
bLoop = false;
break;
case ' ':
case '\t':
nvSb.append(" ");
state = S_VALUE;
break;
default:
in.unread(c);
bytesOut.unread(c);
headerLine.value = trim(nvSb);
nvSb.setLength(0);
bLoop = false;
break;
}
break;
case S_QUOTED_TEXT:
switch (c) {
case -1:
// EOF.
bfErrors |= E_BIT_MISSING_QUOTE | E_BIT_EOF;
headerLine.value = trim(nvSb);
nvSb.setLength(0);
bLoop = false;
break;
case '\"':
if (bCr) {
// Misplaced CR.
bfErrors |= E_BIT_MISPLACED_CR;
bCr = false;
}
nvSb.append((char)c);
state = S_VALUE;
break;
case '\\':
if (bCr) {
// Misplaced CR.
bfErrors |= E_BIT_MISPLACED_CR;
bCr = false;
}
state = S_QUOTED_PAIR;
break;
case '\r':
bCr = true;
break;
case '\n':
// Check EOL.
check_eol();
if (bLWS) {
state = S_QUOTED_LWS;
} else {
headerLine.value = trim(nvSb);
nvSb.setLength(0);
bLoop = false;
}
break;
default:
if (bCr) {
// Misplaced CR.
bfErrors |= E_BIT_MISPLACED_CR;
bCr = false;
}
// Decode character.
c = decode(c, in);
if (c == -1) {
// EOF.
bfErrors |= E_BIT_MISSING_QUOTE | E_BIT_EOF;
headerLine.value = trim(nvSb);
nvSb.setLength(0);
bLoop = false;
} else {
if (bValidChar && encoding != ENC_RAW) {
if (c < 256 && ((charCharacteristicsTab[c] & CC_CONTROL) == CC_CONTROL)) {
bValidChar = false;
// Invalid control char
bfErrors |= E_BIT_INVALID_CONTROL_CHAR;
}
}
if (bValidChar) {
nvSb.append((char)c);
}
}
break;
}
break;
case S_QUOTED_PAIR:
switch (c) {
case -1:
nvSb.append('\\');
// EOF.
bfErrors |= E_BIT_MISSING_QUOTED_PAIR_CHAR | E_BIT_MISSING_QUOTE | E_BIT_EOF;
headerLine.value = trim(nvSb);
nvSb.setLength(0);
bLoop = false;
break;
default:
// Decode character.
c = decode(c, in);
if (c == -1) {
// EOF.
bfErrors |= E_BIT_MISSING_QUOTED_PAIR_CHAR | E_BIT_MISSING_QUOTE | E_BIT_EOF;
headerLine.value = trim(nvSb);
nvSb.setLength(0);
bLoop = false;
} else {
nvSb.append('\\');
nvSb.append((char)c);
if (!bValidChar) {
bfErrors |= E_BIT_INVALID_QUOTED_PAIR_CHAR;
}
state = S_QUOTED_TEXT;
}
break;
}
break;
case S_QUOTED_LWS:
switch (c) {
case -1:
// EOF.
bfErrors |= E_BIT_MISSING_QUOTE;
headerLine.value = trim(nvSb);
nvSb.setLength(0);
bLoop = false;
break;
case ' ':
case '\t':
nvSb.append(" ");
state = S_QUOTED_TEXT;
break;
default:
in.unread(c);
bytesOut.unread(c);
bfErrors |= E_BIT_MISSING_QUOTE;
headerLine.value = trim(nvSb);
nvSb.setLength(0);
bLoop = false;
break;
}
break;
case S_ENCODED_WORD_EQ:
switch (c) {
case -1:
nvSb.append('=');
// EOF.
bfErrors |= E_BIT_EOF;
headerLine.value = trim(nvSb);
nvSb.setLength(0);
bLoop = false;
break;
case '?':
// Unread "=?", so it can be parsed as an EncodedWord which always starts with "=?"
in.unread('?');
in.unread('=');
bytesOut.unread('?');
bytesOut.unread('=');
EncodedWords ew = EncodedWords.parseEncodedWords(in, true);
/*
if (!ew.bIsValid) {
// TODO Decide whether to report encoded word errors or interpret as non encoded words.
}
*/
nvSb.append("=?");
in.unread(ew.line, 2, ew.line.length - 2);
bytesOut.write("=?".getBytes());
state = S_VALUE;
break;
default:
nvSb.append('=');
in.unread(c);
bytesOut.unread(c);
state = S_VALUE;
break;
}
break;
}
}
headerLine.raw = bytesOut.toByteArray();
headerLine.bfErrors = bfErrors;
bEof = (headerLine.raw.length == 0);
return headerLine;
}
/**
* Decode a character according to the expected encoding.
* @param c first character of the possibly encoded character sequence
* @param in <code>InputStream</code> with possible extra encoded characters.
* @return decoded character
* @throws IOException if an i/o error occurs in the underlying input stream
*/
protected int decode(int c, InputStream in) throws IOException {
switch (encoding) {
case ENC_UTF8:
c = utf8.readUtf8(c, in);
bytesOut.write(utf8.chars_read);
bValidChar = utf8.bValidChar;
if (c != -1) {
if (!bValidChar) {
// Invalid UTF-8 char
bfErrors |= E_BIT_INVALID_UTF8_ENCODING;
}
}
break;
case ENC_US_ASCII:
bValidChar = (c <= 127);
if (!bValidChar) {
// Invalid US-ASCII char
bfErrors |= E_BIT_INVALID_US_ASCII_CHAR;
}
break;
case ENC_ISO8859_1:
// ISO-8859-1 utilizes all 8-bits and requires no decoding.
case ENC_RAW:
// Raw 8-bit character needs no decoding.
default:
bValidChar = true;
break;
}
return c;
}
/**
* Check and report whether the line ended as expected.
*/
protected void check_eol() {
switch (eol) {
case EOL_LF:
if (!bCr) {
// Unexpected CR.
bfErrors |= E_BIT_UNEXPECTED_CR;
}
break;
case EOL_CRLF:
if (!bCr) {
// Missing CR.
bfErrors |= E_BIT_MISSING_CR;
}
break;
}
bCr = false;
}
/**
* Trims the whitespace characters found in the beginning and end of a
* string. Differs from the String method in that it leaves control
* characters.
* @param sb <code>StringBuffer</code> to be trimmed
* @return trimmed string
*/
public static String trim(StringBuffer sb) {
int sIdx = 0;
int eIdx = sb.length();
while (sIdx < eIdx && sb.charAt(sIdx) == ' ') {
++sIdx;
}
while (eIdx > sIdx && sb.charAt(eIdx - 1) == ' ') {
--eIdx;
}
return sb.substring(sIdx, eIdx);
}
/**
* Report bit field errors as diagnoses.
* @param bfErrors bit field with indicated errors
* @param diagnostics diagnostics object used to report diagnoses
*/
public static void report_error(int bfErrors, Diagnostics<Diagnosis> diagnostics) {
if (diagnostics == null) {
throw new IllegalArgumentException("'diagnostics' argument is null");
}
if ((bfErrors & E_BIT_EOF) != 0) {
diagnostics.addError(new Diagnosis(DiagnosisType.ERROR, "header/line", "Unexpected EOF"));
}
if ((bfErrors & E_BIT_MISPLACED_CR) != 0) {
diagnostics.addError(new Diagnosis(DiagnosisType.ERROR, "header/line", "Misplaced CR"));
}
if ((bfErrors & E_BIT_MISSING_CR) != 0) {
diagnostics.addError(new Diagnosis(DiagnosisType.ERROR, "header/line", "Missing CR"));
}
if ((bfErrors & E_BIT_UNEXPECTED_CR) != 0) {
diagnostics.addError(new Diagnosis(DiagnosisType.ERROR, "header/line", "Unexpected CR"));
}
if ((bfErrors & E_BIT_INVALID_UTF8_ENCODING) != 0) {
diagnostics.addError(new Diagnosis(DiagnosisType.ERROR, "header/line", "Invalid UTF-8 encoded character"));
}
if ((bfErrors & E_BIT_INVALID_US_ASCII_CHAR) != 0) {
diagnostics.addError(new Diagnosis(DiagnosisType.ERROR, "header/line", "Invalid US-ASCII character"));
}
if ((bfErrors & E_BIT_INVALID_CONTROL_CHAR) != 0) {
diagnostics.addError(new Diagnosis(DiagnosisType.ERROR, "header/line", "Invalid control character"));
}
if ((bfErrors & E_BIT_INVALID_SEPARATOR_CHAR) != 0) {
diagnostics.addError(new Diagnosis(DiagnosisType.ERROR, "header/line", "Invalid separator character"));
}
if ((bfErrors & E_BIT_MISSING_QUOTE) != 0) {
diagnostics.addError(new Diagnosis(DiagnosisType.ERROR, "header/line", "Missing quote character"));
}
if ((bfErrors & E_BIT_MISSING_QUOTED_PAIR_CHAR) != 0) {
diagnostics.addError(new Diagnosis(DiagnosisType.ERROR, "header/line", "Missing quoted pair character"));
}
if ((bfErrors & E_BIT_INVALID_QUOTED_PAIR_CHAR) != 0) {
diagnostics.addError(new Diagnosis(DiagnosisType.ERROR, "header/line", "Invalid quoted pair character"));
}
}
}
| apache-2.0 |
karol-202/Evolution | src/pl/karol202/evolution/entity/EntityNutrition.java | 853 | /*
Copyright 2017 karol-202
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 pl.karol202.evolution.entity;
public class EntityNutrition extends Component
{
EntityNutrition(Entity entity)
{
super(entity);
}
@Override
void update() { }
public void eat(float energyAmount)
{
entity.addEnergy(energyAmount);
}
} | apache-2.0 |
googleads/google-ads-java | google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/common/UserListInfoOrBuilder.java | 953 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/common/criteria.proto
package com.google.ads.googleads.v10.common;
public interface UserListInfoOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.ads.googleads.v10.common.UserListInfo)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* The User List resource name.
* </pre>
*
* <code>optional string user_list = 2;</code>
* @return Whether the userList field is set.
*/
boolean hasUserList();
/**
* <pre>
* The User List resource name.
* </pre>
*
* <code>optional string user_list = 2;</code>
* @return The userList.
*/
java.lang.String getUserList();
/**
* <pre>
* The User List resource name.
* </pre>
*
* <code>optional string user_list = 2;</code>
* @return The bytes for userList.
*/
com.google.protobuf.ByteString
getUserListBytes();
}
| apache-2.0 |
motorina0/flowable-engine | modules/flowable-rest/src/main/java/org/flowable/rest/service/api/runtime/task/TaskRequest.java | 3934 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.rest.service.api.runtime.task;
import java.util.Date;
/**
* Request body containing a task and general properties.
*
* @author Frederik Heremans
*/
public class TaskRequest {
private String owner;
private String assignee;
private String delegationState;
private String name;
private String description;
private Date dueDate;
private int priority;
private String parentTaskId;
private String category;
private String tenantId;
private String formKey;
private boolean ownerSet;
private boolean assigneeSet;
private boolean delegationStateSet;
private boolean nameSet;
private boolean descriptionSet;
private boolean duedateSet;
private boolean prioritySet;
private boolean parentTaskIdSet;
private boolean categorySet;
private boolean tenantIdSet;
private boolean formKeySet;
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
ownerSet = true;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
assigneeSet = true;
}
public String getDelegationState() {
return delegationState;
}
public void setDelegationState(String delegationState) {
this.delegationState = delegationState;
delegationStateSet = true;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
nameSet = true;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
descriptionSet = true;
}
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
duedateSet = true;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
prioritySet = true;
}
public String getParentTaskId() {
return parentTaskId;
}
public void setParentTaskId(String parentTaskId) {
this.parentTaskId = parentTaskId;
parentTaskIdSet = true;
}
public void setCategory(String category) {
this.category = category;
categorySet = true;
}
public String getCategory() {
return category;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
tenantIdSet = true;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
formKeySet = true;
}
public boolean isOwnerSet() {
return ownerSet;
}
public boolean isAssigneeSet() {
return assigneeSet;
}
public boolean isDelegationStateSet() {
return delegationStateSet;
}
public boolean isNameSet() {
return nameSet;
}
public boolean isDescriptionSet() {
return descriptionSet;
}
public boolean isDuedateSet() {
return duedateSet;
}
public boolean isPrioritySet() {
return prioritySet;
}
public boolean isParentTaskIdSet() {
return parentTaskIdSet;
}
public boolean isCategorySet() {
return categorySet;
}
public boolean isTenantIdSet() {
return tenantIdSet;
}
public boolean isFormKeySet() {
return formKeySet;
}
}
| apache-2.0 |
danielyzc/integrado | integrado-ejb/src/java/be/TipoEmpleado.java | 4958 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package be;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author root
*/
@Entity
@Table(name = "tipo_empleado")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "TipoEmpleado.findAll", query = "SELECT t FROM TipoEmpleado t"),
@NamedQuery(name = "TipoEmpleado.findByIdTipoEmpleado", query = "SELECT t FROM TipoEmpleado t WHERE t.idTipoEmpleado = :idTipoEmpleado"),
@NamedQuery(name = "TipoEmpleado.findByNombre", query = "SELECT t FROM TipoEmpleado t WHERE t.nombre = :nombre"),
@NamedQuery(name = "TipoEmpleado.findByDescripcion", query = "SELECT t FROM TipoEmpleado t WHERE t.descripcion = :descripcion"),
@NamedQuery(name = "TipoEmpleado.findByEstadoExistencia", query = "SELECT t FROM TipoEmpleado t WHERE t.estadoExistencia = :estadoExistencia"),
@NamedQuery(name = "TipoEmpleado.findByFechaRegistro", query = "SELECT t FROM TipoEmpleado t WHERE t.fechaRegistro = :fechaRegistro")})
public class TipoEmpleado implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id_tipo_empleado")
private Integer idTipoEmpleado;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 100)
@Column(name = "nombre")
private String nombre;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 170)
@Column(name = "descripcion")
private String descripcion;
@Basic(optional = false)
@NotNull
@Column(name = "estado_existencia")
private int estadoExistencia;
@Column(name = "fecha_registro")
@Temporal(TemporalType.TIMESTAMP)
private Date fechaRegistro;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "tipoEmpleado", fetch = FetchType.EAGER)
private List<Empleado> empleadoList;
public TipoEmpleado() {
}
public TipoEmpleado(Integer idTipoEmpleado) {
this.idTipoEmpleado = idTipoEmpleado;
}
public TipoEmpleado(Integer idTipoEmpleado, String nombre, String descripcion, int estadoExistencia) {
this.idTipoEmpleado = idTipoEmpleado;
this.nombre = nombre;
this.descripcion = descripcion;
this.estadoExistencia = estadoExistencia;
}
public Integer getIdTipoEmpleado() {
return idTipoEmpleado;
}
public void setIdTipoEmpleado(Integer idTipoEmpleado) {
this.idTipoEmpleado = idTipoEmpleado;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public int getEstadoExistencia() {
return estadoExistencia;
}
public void setEstadoExistencia(int estadoExistencia) {
this.estadoExistencia = estadoExistencia;
}
public Date getFechaRegistro() {
return fechaRegistro;
}
public void setFechaRegistro(Date fechaRegistro) {
this.fechaRegistro = fechaRegistro;
}
@XmlTransient
public List<Empleado> getEmpleadoList() {
return empleadoList;
}
public void setEmpleadoList(List<Empleado> empleadoList) {
this.empleadoList = empleadoList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idTipoEmpleado != null ? idTipoEmpleado.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof TipoEmpleado)) {
return false;
}
TipoEmpleado other = (TipoEmpleado) object;
if ((this.idTipoEmpleado == null && other.idTipoEmpleado != null) || (this.idTipoEmpleado != null && !this.idTipoEmpleado.equals(other.idTipoEmpleado))) {
return false;
}
return true;
}
@Override
public String toString() {
return "be.TipoEmpleado[ idTipoEmpleado=" + idTipoEmpleado + " ]";
}
}
| apache-2.0 |
raywang8341/BTMessenger | app/src/main/java/com/randroid/btmessenger/ClientActivity.java | 5443 | package com.randroid.btmessenger;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.randroid.btmessenger.bluetooth.BluetoothMessage;
import com.randroid.btmessenger.bluetooth.BluetoothUtilities;
import java.util.Date;
public class ClientActivity extends ActionBarActivity {
private MyEditText txtMessage;
private TextView txtMessageHistory;
private Button btnSend;
private String mmacAddress;
@Override
protected void onStart() {
registerReceiver();
super.onStart();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
txtMessage = (MyEditText)findViewById(R.id.txtMessage);
txtMessageHistory = (TextView)findViewById(R.id.txtMessageHistory);
btnSend = (Button)findViewById(R.id.btnSend);
btnSend.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String message = txtMessage.getText().toString();
if(message.length() == 0){
Toast toast = Toast.makeText(ClientActivity.this.getApplicationContext(), "Message can not be empty.", Toast.LENGTH_SHORT);
toast.show();
}
BluetoothMessage bm = new BluetoothMessage(message);
Intent sendDataIntent = new Intent(BluetoothUtilities.ACTION_SEND_MESSAGE);
sendDataIntent.putExtra(BluetoothUtilities.MSG, bm);
sendBroadcast(sendDataIntent);
String msg = "↗️ " + new Date().toLocaleString()
+ " :\r\n" + BluetoothUtilities.space + bm.getMessage() + "\r\n";
txtMessageHistory.append(msg);
txtMessage.setText("");
}
});
Bundle bundle = getIntent().getExtras();
mmacAddress = bundle.getString("MacAddress");
}
private void registerReceiver(){
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothUtilities.ACTION_DATA_AVAILABLE);
intentFilter.addAction(BluetoothUtilities.ACTION_CONNECT_SUCCESS);
intentFilter.addAction(BluetoothUtilities.ACTION_CONNECT_ERROR);
registerReceiver(serverServiceBroadReceiver, intentFilter);
if(mmacAddress != null){
Intent connIntent = new Intent(BluetoothUtilities.ACTION_CONNECT_DEVICE);
connIntent.putExtra("MacAddress", mmacAddress);
sendBroadcast(connIntent);
}
}
private BroadcastReceiver serverServiceBroadReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothUtilities.ACTION_DATA_AVAILABLE.equals(action)) {
BluetoothMessage bm = (BluetoothMessage) intent.getExtras()
.getSerializable(BluetoothUtilities.MSG);
String msg = "↙️ " + new Date().toLocaleString()
+ " :\r\n" + BluetoothUtilities.space + bm.getMessage() + "\r\n";
txtMessageHistory.append(msg);
} else if (BluetoothUtilities.ACTION_CONNECT_SUCCESS.equals(action)) {
String msg = "☑️ " + new Date().toLocaleString()
+ " :\r\n" + BluetoothUtilities.space + "Connected to server successfully.\r\n";
txtMessageHistory.append(msg);
btnSend.setEnabled(true);
}else if(BluetoothUtilities.ACTION_CONNECT_ERROR.equals(action)){
String msg = "☑️ " + new Date().toLocaleString()
+ " :\r\n" + BluetoothUtilities.space + "Connected to server failed.\r\n";
txtMessageHistory.append(msg);
btnSend.setEnabled(false);
}
}
};
@Override
protected void onStop() {
unregisterReceiver();
super.onStop();
}
private void unregisterReceiver(){
Intent startServerService = new Intent(BluetoothUtilities.ACTION_STOP_SERVICE);
sendBroadcast(startServerService);
unregisterReceiver(serverServiceBroadReceiver);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| apache-2.0 |
qiyueW/JWeb | src/main/java/system/web/power/interfaces/UPMDefault.java | 1032 | package system.web.power.interfaces;
import system.web.JWeb;
/**
*
* @author wangchunzi
*/
public class UPMDefault implements UPM {
@Override
public void ggSuccess(String url, JWeb jw) {
}
@Override
public void ggError(String url, JWeb jw) {
}
@Override
public void dlSuccess(String url, JWeb jw) {
}
@Override
public void dlError(String url, JWeb jw) {
}
@Override
public void sqSuccess(String url, JWeb jw) {
}
@Override
public void sqError(String url, JWeb jw) {
}
@Override
public boolean kl_endByTrue(String kl,String url, JWeb jw) {
return true;
}
@Override
public void klError(String kl,String url, JWeb jw) {
}
@Override
public boolean start_endByTrue(String url, JWeb jw) {
return false;
}
@Override
public void end(String url, JWeb jw) {
}
@Override
public void sqNotLogin(String url, JWeb jw) {
}
}
| apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Features/Base/src/test/java/ghidra/program/model/data/StructureBigEndianBitFieldTest.java | 24722 | /* ###
* IP: GHIDRA
*
* 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 ghidra.program.model.data;
import static org.junit.Assert.*;
import org.junit.Test;
public class StructureBigEndianBitFieldTest extends AbstractCompositeBitFieldTest {
// NOTE: verified bitfields sample built with mips-elf-gcc (GCC) 4.9.2
private static DataTypeManager dataMgr;
@Override
protected DataTypeManager getDataTypeManager() {
synchronized (StructureBigEndianBitFieldTest.class) {
if (dataMgr == null) {
DataOrganizationImpl dataOrg = DataOrganizationImpl.getDefaultOrganization(null);
DataOrganizationTestUtils.initDataOrganization32BitMips(dataOrg);
dataMgr = createDataTypeManager("test", dataOrg);
}
return dataMgr;
}
}
@Test
public void testStructureBitFieldsA1() {
Structure struct = getStructure("A1");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/A1\n" +
"pack()\n" +
"Structure A1 {\n" +
" 0 char[5] 5 a \"\"\n" +
" 5 int:3(5) 1 b \"\"\n" +
" 5 int:8(5) 2 c \"\"\n" +
" 6 int:8(5) 2 d \"\"\n" +
" 8 int:6(2) 1 e \"\"\n" +
"}\n" +
"Size = 12 Actual Alignment = 4", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsA2() {
Structure struct = getStructure("A2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/A2\n" +
"pack()\n" +
"Structure A2 {\n" +
" 0 oddStruct 5 a \"\"\n" +
" 5 int:3(5) 1 b \"\"\n" +
" 5 int:8(5) 2 c \"\"\n" +
" 6 int:8(5) 2 d \"\"\n" +
" 8 int:6(2) 1 e \"\"\n" +
"}\n" +
"Size = 12 Actual Alignment = 4", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsA3() {
Structure struct = getStructure("A3");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/A3\n" +
"pack()\n" +
"Structure A3 {\n" +
" 0 char[5] 5 a \"\"\n" +
" 5 int:3(5) 1 b \"\"\n" +
" 5 int:8(5) 2 c \"\"\n" +
" 8 int:85(0) 4 d \"\"\n" +
" 12 int:6(2) 1 e \"\"\n" +
"}\n" +
"Size = 16 Actual Alignment = 4\n", struct);
//@formatter:on
DataTypeComponent c = struct.getComponent(3);
assertTrue(c.isBitFieldComponent());
BitFieldDataType bfDt = (BitFieldDataType) c.getDataType();
assertEquals(4, bfDt.getBaseTypeSize());
assertEquals(32, bfDt.getBitSize());
assertEquals(85, bfDt.getDeclaredBitSize());
}
@Test
public void testStructureBitFieldsB1() {
Structure struct = getStructure("B1");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/B1\n" +
"pack()\n" +
"Structure B1 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 2 short:4(6) 2 d \"\"\n" +
"}\n" +
"Size = 4 Actual Alignment = 4", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsB1Flex() {
Structure struct = getStructure("B1flex");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/B1flex\n" +
"pack()\n" +
"Structure B1flex {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 2 short:4(6) 2 d \"\"\n" +
" 4 long[0] 0 flex \"\"\n" +
"}\n" +
"Size = 4 Actual Alignment = 4", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsB2() {
Structure struct = getStructure("B2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/B2\n" +
"pack()\n" +
"Structure B2 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 2 int:4(6) 2 d \"\"\n" +
"}\n" +
"Size = 4 Actual Alignment = 4", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsB3() {
Structure struct = getStructure("B3");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/B3\n" +
"pack()\n" +
"Structure B3 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 3 char 1 d \"\"\n" +
"}\n" +
"Size = 4 Actual Alignment = 4", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ1() {
Structure struct = getStructure("Z1");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z1\n" +
"pack()\n" +
"Structure Z1 {\n" +
" 0 char 1 a \"\"\n" +
" 4 int:0(7) 0 \"\"\n" +
" 4 ushort:6(2) 1 b \"\"\n" +
" 4 int:8(2) 2 c \"\"\n" +
" 6 short:4(4) 1 d \"\"\n" +
"}\n" +
"Size = 8 Actual Alignment = 4", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ2() {
Structure struct = getStructure("Z2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z2\n" +
"pack()\n" +
"Structure Z2 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 4 int:0(7) 0 \"\"\n" +
" 4 short:4(4) 1 d \"\"\n" +
"}\n" +
"Size = 8 Actual Alignment = 4", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ3() {
Structure struct = getStructure("Z3");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z3\n" +
"pack()\n" +
"Structure Z3 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 2 int:4(6) 2 d \"\"\n" +
" 8 longlong:0(7) 0 \"\"\n" +
"}\n" +
"Size = 8 Actual Alignment = 8", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ4() {
Structure struct = getStructure("Z4");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z4\n" +
"pack()\n" +
"Structure Z4 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 8 longlong:0(7) 0 \"\"\n" +
" 8 char 1 d \"\"\n" +
"}\n" +
"Size = 12 Actual Alignment = 4", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ5() {
Structure struct = getStructure("Z5");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z5\n" +
"pack()\n" +
"Structure Z5 {\n" +
" 0 char 1 a \"\"\n" +
" 4 int:0(7) 0 \"\"\n" +
" 4 longlong:6(2) 1 b \"\"\n" +
" 4 int:8(2) 2 c \"\"\n" +
" 6 char 1 d \"\"\n" +
"}\n" +
"Size = 8 Actual Alignment = 8", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ6() {
Structure struct = getStructure("Z6");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z6\n" +
"pack()\n" +
"Structure Z6 {\n" +
" 0 char 1 a \"\"\n" +
" 4 int:0(7) 0 \"\"\n" +
" 4 longlong:6(2) 1 b \"\"\n" +
" 4 int:8(2) 2 c \"\"\n" +
" 6 char 1 d \"\"\n" +
" 7 longlong:6(2) 1 e \"\"\n" +
" 8 int:8(0) 1 f \"\"\n" +
" 9 char 1 g \"\"\n" +
"}\n" +
"Size = 16 Actual Alignment = 8", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsB1p1() {
Structure struct = getStructure("B1p1");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/B1p1\n" +
"pack(1)\n" +
"Structure B1p1 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 2 short:4(6) 2 d \"\"\n" +
"}\n" +
"Size = 4 Actual Alignment = 1", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsB2p1() {
Structure struct = getStructure("B2p1");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/B2p1\n" +
"pack(1)\n" +
"Structure B2p1 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 2 int:4(6) 2 d \"\"\n" +
"}\n" +
"Size = 4 Actual Alignment = 1", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsB3p1() {
Structure struct = getStructure("B3p1");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/B3p1\n" +
"pack(1)\n" +
"Structure B3p1 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 3 char 1 d \"\"\n" +
"}\n" +
"Size = 4 Actual Alignment = 1", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ1p1() {
Structure struct = getStructure("Z1p1");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z1p1\n" +
"pack(1)\n" +
"Structure Z1p1 {\n" +
" 0 char 1 a \"\"\n" +
" 4 int:0(7) 0 \"\"\n" +
" 4 ushort:6(2) 1 b \"\"\n" +
" 4 int:8(2) 2 c \"\"\n" +
" 5 short:4(6) 2 d \"\"\n" +
"}\n" +
"Size = 7 Actual Alignment = 1", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ2p1() {
Structure struct = getStructure("Z2p1");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z2p1\n" +
"pack(1)\n" +
"Structure Z2p1 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 4 int:0(7) 0 \"\"\n" +
" 4 short:4(4) 1 d \"\"\n" +
"}\n" +
"Size = 5 Actual Alignment = 1", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ3p1() {
Structure struct = getStructure("Z3p1");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z3p1\n" +
"pack(1)\n" +
"Structure Z3p1 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 2 int:4(6) 2 d \"\"\n" +
" 8 longlong:0(7) 0 \"\"\n" +
"}\n" +
"Size = 8 Actual Alignment = 1", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ3p1T() {
Structure struct = getStructure("Z3p1T");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z3p1T\n" +
"pack()\n" +
"Structure Z3p1T {\n" +
" 0 char 1 a \"\"\n" +
" 1 Z3p1 8 z3p1 \"\"\n" +
"}\n" +
"Size = 9 Actual Alignment = 1", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ4p1() {
Structure struct = getStructure("Z4p1");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z4p1\n" +
"pack(1)\n" +
"Structure Z4p1 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 8 longlong:0(7) 0 \"\"\n" +
" 8 char 1 d \"\"\n" +
"}\n" +
"Size = 9 Actual Alignment = 1", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsB1p2() {
Structure struct = getStructure("B1p2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/B1p2\n" +
"pack(2)\n" +
"Structure B1p2 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 2 short:4(6) 2 d \"\"\n" +
"}\n" +
"Size = 4 Actual Alignment = 2", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsB2p2() {
Structure struct = getStructure("B2p2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/B2p2\n" +
"pack(2)\n" +
"Structure B2p2 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 2 int:4(6) 2 d \"\"\n" +
"}\n" +
"Size = 4 Actual Alignment = 2", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsB3p2() {
Structure struct = getStructure("B3p2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/B3p2\n" +
"pack(2)\n" +
"Structure B3p2 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 3 char 1 d \"\"\n" +
"}\n" +
"Size = 4 Actual Alignment = 2", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsB4p2() {
Structure struct = getStructure("B4p2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/B4p2\n" +
"pack(2)\n" +
"Structure B4p2 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 4 longlong 8 d \"\"\n" +
" 12 int:4(4) 1 e \"\"\n" +
"}\n" +
"Size = 14 Actual Alignment = 2", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ1p2() {
Structure struct = getStructure("Z1p2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z1p2\n" +
"pack(2)\n" +
"Structure Z1p2 {\n" +
" 0 char 1 a \"\"\n" +
" 4 int:0(7) 0 \"\"\n" +
" 4 ushort:6(2) 1 b \"\"\n" +
" 4 int:8(2) 2 c \"\"\n" +
" 5 short:4(6) 2 d \"\"\n" +
"}\n" +
"Size = 8 Actual Alignment = 2", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ1p2x() {
Structure struct = getStructure("Z1p2x");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z1p2x\n" +
"pack(2)\n" +
"Structure Z1p2x {\n" +
" 0 char 1 a \"\"\n" +
" 4 int:0(7) 0 \"\"\n" +
" 4 ushort:6(2) 1 b \"\"\n" +
" 4 int:8(2) 2 c \"\"\n" +
" 5 short:4(6) 2 d \"\"\n" +
" 6 short:4(2) 1 d1 \"\"\n" +
" 6 short:4(6) 2 d2 \"\"\n" +
" 7 short:4(2) 1 d3 \"\"\n" +
" 7 short:4(6) 2 d4 \"\"\n" +
" 8 short:4(2) 1 d5 \"\"\n" +
" 8 short:4(6) 2 d6 \"\"\n" +
" 9 short:4(2) 1 d7 \"\"\n" +
" 10 short:0(7) 0 \"\"\n" +
" 10 ushort:6(2) 1 _b \"\"\n" +
" 10 int:8(2) 2 _c \"\"\n" +
" 11 short:4(6) 2 _d \"\"\n" +
" 12 short:4(2) 1 _d1 \"\"\n" +
" 12 short:4(6) 2 _d2 \"\"\n" +
" 13 short:4(2) 1 _d3 \"\"\n" +
" 13 short:4(6) 2 _d4 \"\"\n" +
" 14 short:4(2) 1 _d5 \"\"\n" +
" 14 short:4(6) 2 _d6 \"\"\n" +
" 15 short:4(2) 1 _d7 \"\"\n" +
"}\n" +
"Size = 16 Actual Alignment = 2", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ2p2() {
Structure struct = getStructure("Z2p2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z2p2\n" +
"pack(2)\n" +
"Structure Z2p2 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 4 int:0(7) 0 \"\"\n" +
" 4 short:4(4) 1 d \"\"\n" +
"}\n" +
"Size = 6 Actual Alignment = 2", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ3p2() {
Structure struct = getStructure("Z3p2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z3p2\n" +
"pack(2)\n" +
"Structure Z3p2 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 2 int:4(6) 2 d \"\"\n" +
" 8 longlong:0(7) 0 \"\"\n" +
"}\n" +
"Size = 8 Actual Alignment = 2", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ4p2() {
Structure struct = getStructure("Z4p2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z4p2\n" +
"pack(2)\n" +
"Structure Z4p2 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:6(2) 1 b \"\"\n" +
" 1 int:8(2) 2 c \"\"\n" +
" 8 longlong:0(7) 0 \"\"\n" +
" 8 char 1 d \"\"\n" +
"}\n" +
"Size = 10 Actual Alignment = 2", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ5p2() {
Structure struct = getStructure("Z5p2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z5p2\n" +
"pack(2)\n" +
"Structure Z5p2 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:12(4) 2 b \"\"\n" +
" 2 int:8(4) 2 c \"\"\n" +
" 8 longlong:0(7) 0 \"\"\n" +
" 8 char 1 d \"\"\n" +
"}\n" +
"Size = 10 Actual Alignment = 2", struct);
//@formatter:on
}
@Test
public void testStructureBitFields_x1p2() {
Structure struct = getStructure("x1p2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/x1p2\n" +
"pack(2)\n" +
"Structure x1p2 {\n" +
" 0 char 1 a \"\"\n" +
"}\n" +
"Size = 1 Actual Alignment = 1", struct);
//@formatter:on
}
@Test
public void testStructureBitFields_x2p2() {
Structure struct = getStructure("x2p2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/x2p2\n" +
"pack(2)\n" +
"Structure x2p2 {\n" +
" 0 char 1 a \"\"\n" +
" 1 int:27(5) 4 b \"\"\n" +
"}\n" +
"Size = 6 Actual Alignment = 2", struct);
//@formatter:on
}
@Test
public void testStructureBitFields_x3p2() {
Structure struct = getStructure("x3p2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/x3p2\n" +
"pack(2)\n" +
"Structure x3p2 {\n" +
" 0 char 1 a \"\"\n" +
" 2 short:0(7) 0 \"\"\n" +
" 2 int:27(5) 4 b \"\"\n" +
"}\n" +
"Size = 6 Actual Alignment = 2", struct);
//@formatter:on
}
@Test
public void testStructureBitFields_x4p2() {
Structure struct = getStructure("x4p2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/x4p2\n" +
"pack(2)\n" +
"Structure x4p2 {\n" +
" 0 char 1 a \"\"\n" +
" 1 int:27(5) 4 b \"\"\n" +
" 8 longlong:0(7) 0 \"\"\n" +
"}\n" +
"Size = 8 Actual Alignment = 2", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsZ5p4() {
Structure struct = getStructure("Z5p4");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/Z5p4\n" +
"pack(4)\n" +
"Structure Z5p4 {\n" +
" 0 char 1 a \"\"\n" +
" 1 ushort:12(4) 2 b \"\"\n" +
" 2 int:8(4) 2 c \"\"\n" +
" 8 longlong:0(7) 0 \"\"\n" +
" 8 char 1 d \"\"\n" +
"}\n" +
"Size = 12 Actual Alignment = 4", struct);
//@formatter:on
}
@Test
public void testStructureBitFields_x1p4() {
Structure struct = getStructure("x1p4");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/x1p4\n" +
"pack(4)\n" +
"Structure x1p4 {\n" +
" 0 char 1 a \"\"\n" +
"}\n" +
"Size = 1 Actual Alignment = 1", struct);
//@formatter:on
}
@Test
public void testStructureBitFields_x2p4() {
Structure struct = getStructure("x2p4");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/x2p4\n" +
"pack(4)\n" +
"Structure x2p4 {\n" +
" 0 char 1 a \"\"\n" +
" 1 int:27(5) 4 b \"\"\n" +
"}\n" +
"Size = 8 Actual Alignment = 4", struct);
//@formatter:on
}
@Test
public void testStructureBitFields_x3p4() {
Structure struct = getStructure("x3p4");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/x3p4\n" +
"pack(4)\n" +
"Structure x3p4 {\n" +
" 0 char 1 a \"\"\n" +
" 2 short:0(7) 0 \"\"\n" +
" 2 int:27(5) 4 b \"\"\n" +
"}\n" +
"Size = 8 Actual Alignment = 4", struct);
//@formatter:on
}
@Test
public void testStructureBitFields_x4p4() {
Structure struct = getStructure("x4p4");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/x4p4\n" +
"pack(4)\n" +
"Structure x4p4 {\n" +
" 0 char 1 a \"\"\n" +
" 1 int:27(5) 4 b \"\"\n" +
" 8 longlong:0(7) 0 \"\"\n" +
"}\n" +
"Size = 8 Actual Alignment = 4", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsT1() {
Structure struct = getStructure("T1");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/T1\n" +
"pack()\n" +
"Structure T1 {\n" +
" 0 charTypedef 1 a \"\"\n" +
" 1 myEnum:3(5) 1 b \"\"\n" +
" 1 enumTypedef:3(2) 1 c \"\"\n" +
" 2 charTypedef:7(1) 1 d \"\"\n" +
"}\n" +
"Size = 4 Actual Alignment = 4", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsT2() {
Structure struct = getStructure("T2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/T2\n" +
"pack()\n" +
"Structure T2 {\n" +
" 0 charTypedef 1 a \"\"\n" +
" 1 intTypedef:17(7) 3 b \"\"\n" +
" 3 enumTypedef:3(4) 1 c \"\"\n" +
" 3 charTypedef:3(1) 1 d \"\"\n" +
"}\n" +
"Size = 4 Actual Alignment = 4", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsS1() {
Structure struct = getStructure("S1");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/S1\n" +
"pack()\n" +
"Structure S1 {\n" +
" 0 B1 4 b1 \"\"\n" +
" 4 B2 4 b2 \"\"\n" +
" 8 Z1 8 z1 \"\"\n" +
" 16 Z2 8 z2 \"\"\n" +
" 24 Z3 8 z3 \"\"\n" +
"}\n" +
"Size = 32 Actual Alignment = 8", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsS1p1() {
Structure struct = getStructure("S1p1");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/S1p1\n" +
"pack(1)\n" +
"Structure S1p1 {\n" +
" 0 B1 4 b1 \"\"\n" +
" 4 B2 4 b2 \"\"\n" +
" 8 Z1 8 z1 \"\"\n" +
" 16 Z2 8 z2 \"\"\n" +
" 24 Z3 8 z3 \"\"\n" +
"}\n" +
"Size = 32 Actual Alignment = 1", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsS2p1() {
Structure struct = getStructure("S2p1");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/S2p1\n" +
"pack(1)\n" +
"Structure S2p1 {\n" +
" 0 B1p1 4 b1p1 \"\"\n" +
" 4 B2p1 4 b2p1 \"\"\n" +
" 8 Z1p1 7 z1p1 \"\"\n" +
" 15 Z2p1 5 z2p1 \"\"\n" +
" 20 Z3p1 8 z3p1 \"\"\n" +
"}\n" +
"Size = 28 Actual Alignment = 1", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsS1p2() {
Structure struct = getStructure("S1p2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/S1p2\n" +
"pack(2)\n" +
"Structure S1p2 {\n" +
" 0 B1 4 b1 \"\"\n" +
" 4 B2 4 b2 \"\"\n" +
" 8 Z1 8 z1 \"\"\n" +
" 16 Z2 8 z2 \"\"\n" +
" 24 Z3 8 z3 \"\"\n" +
"}\n" +
"Size = 32 Actual Alignment = 2", struct);
//@formatter:on
}
@Test
public void testStructureBitFieldsS2p2() {
Structure struct = getStructure("S2p2");
//@formatter:off
CompositeTestUtils.assertExpectedComposite(this, "/S2p2\n" +
"pack(2)\n" +
"Structure S2p2 {\n" +
" 0 B1p2 4 b1p2 \"\"\n" +
" 4 B2p2 4 b2p2 \"\"\n" +
" 8 Z1p2 8 z1p2 \"\"\n" +
" 16 Z2p2 6 z2p2 \"\"\n" +
" 22 Z3p2 8 z3p2 \"\"\n" +
"}\n" +
"Size = 30 Actual Alignment = 2", struct);
//@formatter:on
}
}
| apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Debug/Framework-Debugging/src/main/java/ghidra/dbg/target/schema/TargetElementType.java | 855 | /* ###
* IP: GHIDRA
*
* 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 ghidra.dbg.target.schema;
import java.lang.annotation.*;
import ghidra.dbg.target.TargetObject;
@Target({})
@Retention(RetentionPolicy.RUNTIME)
public @interface TargetElementType {
String index() default "";
Class<?> type() default TargetObject.class;
}
| apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Features/Base/src/main/java/ghidra/app/util/viewer/field/DummyFieldFactory.java | 2448 | /* ###
* IP: GHIDRA
*
* 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 ghidra.app.util.viewer.field;
import java.math.BigInteger;
import docking.widgets.fieldpanel.field.*;
import docking.widgets.fieldpanel.support.FieldLocation;
import ghidra.app.util.HighlightProvider;
import ghidra.app.util.viewer.format.FieldFormatModel;
import ghidra.app.util.viewer.format.FormatManager;
import ghidra.app.util.viewer.proxy.ProxyObj;
import ghidra.framework.options.ToolOptions;
import ghidra.program.util.ProgramLocation;
/**
* Generates Dummy Fields.
*/
public class DummyFieldFactory extends FieldFactory {
public DummyFieldFactory(FormatManager mgr) {
super("Dummy", mgr.getDividerModel(), mgr.getFormatHighlightProvider(),
mgr.getDisplayOptions(), mgr.getFieldOptions());
}
@Override
public String getFieldName() {
return "Dummy";
}
@Override
public String getFieldText() {
return "The Dummy Field";
}
@Override
public ListingField getField(ProxyObj<?> obj, int varWidth) {
if (!enabled || obj == null) {
return null;
}
int x = startX + varWidth;
FieldElement text =
new TextFieldElement(new AttributedString("", color, getMetrics()), 0, 0);
return ListingTextField.createSingleLineTextField(this, obj, text, x, width, hlProvider);
}
@Override
public boolean acceptsType(int category, Class<?> proxyObjectClass) {
return false;
}
@Override
public FieldLocation getFieldLocation(ListingField bf, BigInteger index, int fieldNum,
ProgramLocation loc) {
if (loc.getClass() == ProgramLocation.class) {
return new FieldLocation(index, fieldNum, 0, 0);
}
return null;
}
@Override
public ProgramLocation getProgramLocation(int row, int col, ListingField bf) {
return null;
}
@Override
public FieldFactory newInstance(FieldFormatModel formatModel, HighlightProvider hlProvdier,
ToolOptions displayOptions, ToolOptions fieldOptions) {
return this;
}
}
| apache-2.0 |
googleads/googleads-java-lib | modules/dfp_axis/src/main/java/com/google/api/ads/admanager/axis/v202202/CreativeSet.java | 12622 | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* CreativeSet.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.admanager.axis.v202202;
/**
* A creative set is comprised of a master creative and its companion
* creatives.
*/
public class CreativeSet implements java.io.Serializable {
/* Uniquely identifies the {@code CreativeSet}. This attribute
* is
* read-only and is assigned by Google when a creative
* set is created. */
private java.lang.Long id;
/* The name of the creative set. This attribute is required and
* has a
* maximum length of 255 characters. */
private java.lang.String name;
/* The ID of the master creative associated with this creative
* set. This attribute is required. */
private java.lang.Long masterCreativeId;
/* The IDs of the companion creatives associated with this creative
* set. This attribute is
* required. */
private long[] companionCreativeIds;
/* The date and time this creative set was last modified. */
private com.google.api.ads.admanager.axis.v202202.DateTime lastModifiedDateTime;
public CreativeSet() {
}
public CreativeSet(
java.lang.Long id,
java.lang.String name,
java.lang.Long masterCreativeId,
long[] companionCreativeIds,
com.google.api.ads.admanager.axis.v202202.DateTime lastModifiedDateTime) {
this.id = id;
this.name = name;
this.masterCreativeId = masterCreativeId;
this.companionCreativeIds = companionCreativeIds;
this.lastModifiedDateTime = lastModifiedDateTime;
}
@Override
public String toString() {
return com.google.common.base.MoreObjects.toStringHelper(this.getClass())
.omitNullValues()
.add("companionCreativeIds", getCompanionCreativeIds())
.add("id", getId())
.add("lastModifiedDateTime", getLastModifiedDateTime())
.add("masterCreativeId", getMasterCreativeId())
.add("name", getName())
.toString();
}
/**
* Gets the id value for this CreativeSet.
*
* @return id * Uniquely identifies the {@code CreativeSet}. This attribute
* is
* read-only and is assigned by Google when a creative
* set is created.
*/
public java.lang.Long getId() {
return id;
}
/**
* Sets the id value for this CreativeSet.
*
* @param id * Uniquely identifies the {@code CreativeSet}. This attribute
* is
* read-only and is assigned by Google when a creative
* set is created.
*/
public void setId(java.lang.Long id) {
this.id = id;
}
/**
* Gets the name value for this CreativeSet.
*
* @return name * The name of the creative set. This attribute is required and
* has a
* maximum length of 255 characters.
*/
public java.lang.String getName() {
return name;
}
/**
* Sets the name value for this CreativeSet.
*
* @param name * The name of the creative set. This attribute is required and
* has a
* maximum length of 255 characters.
*/
public void setName(java.lang.String name) {
this.name = name;
}
/**
* Gets the masterCreativeId value for this CreativeSet.
*
* @return masterCreativeId * The ID of the master creative associated with this creative
* set. This attribute is required.
*/
public java.lang.Long getMasterCreativeId() {
return masterCreativeId;
}
/**
* Sets the masterCreativeId value for this CreativeSet.
*
* @param masterCreativeId * The ID of the master creative associated with this creative
* set. This attribute is required.
*/
public void setMasterCreativeId(java.lang.Long masterCreativeId) {
this.masterCreativeId = masterCreativeId;
}
/**
* Gets the companionCreativeIds value for this CreativeSet.
*
* @return companionCreativeIds * The IDs of the companion creatives associated with this creative
* set. This attribute is
* required.
*/
public long[] getCompanionCreativeIds() {
return companionCreativeIds;
}
/**
* Sets the companionCreativeIds value for this CreativeSet.
*
* @param companionCreativeIds * The IDs of the companion creatives associated with this creative
* set. This attribute is
* required.
*/
public void setCompanionCreativeIds(long[] companionCreativeIds) {
this.companionCreativeIds = companionCreativeIds;
}
public long getCompanionCreativeIds(int i) {
return this.companionCreativeIds[i];
}
public void setCompanionCreativeIds(int i, long _value) {
this.companionCreativeIds[i] = _value;
}
/**
* Gets the lastModifiedDateTime value for this CreativeSet.
*
* @return lastModifiedDateTime * The date and time this creative set was last modified.
*/
public com.google.api.ads.admanager.axis.v202202.DateTime getLastModifiedDateTime() {
return lastModifiedDateTime;
}
/**
* Sets the lastModifiedDateTime value for this CreativeSet.
*
* @param lastModifiedDateTime * The date and time this creative set was last modified.
*/
public void setLastModifiedDateTime(com.google.api.ads.admanager.axis.v202202.DateTime lastModifiedDateTime) {
this.lastModifiedDateTime = lastModifiedDateTime;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof CreativeSet)) return false;
CreativeSet other = (CreativeSet) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.id==null && other.getId()==null) ||
(this.id!=null &&
this.id.equals(other.getId()))) &&
((this.name==null && other.getName()==null) ||
(this.name!=null &&
this.name.equals(other.getName()))) &&
((this.masterCreativeId==null && other.getMasterCreativeId()==null) ||
(this.masterCreativeId!=null &&
this.masterCreativeId.equals(other.getMasterCreativeId()))) &&
((this.companionCreativeIds==null && other.getCompanionCreativeIds()==null) ||
(this.companionCreativeIds!=null &&
java.util.Arrays.equals(this.companionCreativeIds, other.getCompanionCreativeIds()))) &&
((this.lastModifiedDateTime==null && other.getLastModifiedDateTime()==null) ||
(this.lastModifiedDateTime!=null &&
this.lastModifiedDateTime.equals(other.getLastModifiedDateTime())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getId() != null) {
_hashCode += getId().hashCode();
}
if (getName() != null) {
_hashCode += getName().hashCode();
}
if (getMasterCreativeId() != null) {
_hashCode += getMasterCreativeId().hashCode();
}
if (getCompanionCreativeIds() != null) {
for (int i=0;
i<java.lang.reflect.Array.getLength(getCompanionCreativeIds());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getCompanionCreativeIds(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getLastModifiedDateTime() != null) {
_hashCode += getLastModifiedDateTime().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(CreativeSet.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "CreativeSet"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("id");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "id"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("name");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "name"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("masterCreativeId");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "masterCreativeId"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("companionCreativeIds");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "companionCreativeIds"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
elemField.setMaxOccursUnbounded(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("lastModifiedDateTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "lastModifiedDateTime"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "DateTime"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
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.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
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.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
robertgeiger/incubator-geode | gemfire-core/src/test/java/com/gemstone/gemfire/TXExpiryJUnitTest.java | 13478 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gemstone.gemfire;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import com.gemstone.gemfire.cache.AttributesMutator;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.CacheException;
import com.gemstone.gemfire.cache.CacheFactory;
import com.gemstone.gemfire.cache.CacheListener;
import com.gemstone.gemfire.cache.CacheTransactionManager;
import com.gemstone.gemfire.cache.CommitConflictException;
import com.gemstone.gemfire.cache.EntryEvent;
import com.gemstone.gemfire.cache.ExpirationAction;
import com.gemstone.gemfire.cache.ExpirationAttributes;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionEvent;
import com.gemstone.gemfire.cache.RegionFactory;
import com.gemstone.gemfire.cache.Scope;
import com.gemstone.gemfire.cache.util.CacheListenerAdapter;
import com.gemstone.gemfire.internal.cache.ExpiryTask;
import com.gemstone.gemfire.internal.cache.ExpiryTask.ExpiryTaskListener;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.cache.LocalRegion;
import com.gemstone.gemfire.internal.cache.TXManagerImpl;
import com.gemstone.gemfire.internal.cache.TXStateProxy;
import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
import dunit.DistributedTestCase;
import dunit.DistributedTestCase.WaitCriterion;
/**
* Tests transaction expiration functionality
*
* @author Mitch Thomas
* @since 4.0
*
*/
@Category(IntegrationTest.class)
public class TXExpiryJUnitTest {
protected GemFireCacheImpl cache;
protected CacheTransactionManager txMgr;
protected void createCache() throws CacheException {
Properties p = new Properties();
p.setProperty("mcast-port", "0"); // loner
this.cache = (GemFireCacheImpl) (new CacheFactory(p)).create();
this.txMgr = this.cache.getCacheTransactionManager();
}
private void closeCache() {
if (this.cache != null) {
if (this.txMgr != null) {
try {
this.txMgr.rollback();
} catch (IllegalStateException ignore) {
}
}
this.txMgr = null;
Cache c = this.cache;
this.cache = null;
c.close();
}
}
@Before
public void setUp() throws Exception {
createCache();
}
@After
public void tearDown() throws Exception {
closeCache();
}
@Test
public void testEntryTTLExpiration() throws CacheException {
generalEntryExpirationTest(createRegion("TXEntryTTL"), new ExpirationAttributes(1, ExpirationAction.DESTROY), true);
}
@Test
public void testEntryIdleExpiration() throws CacheException {
generalEntryExpirationTest(createRegion("TXEntryIdle"), new ExpirationAttributes(1, ExpirationAction.DESTROY), false);
}
private Region<String, String> createRegion(String name) {
RegionFactory<String, String> rf = this.cache.createRegionFactory();
rf.setScope(Scope.DISTRIBUTED_NO_ACK);
rf.setStatisticsEnabled(true);
System.setProperty(LocalRegion.EXPIRY_MS_PROPERTY, "true");
try {
return rf.create(name);
}
finally {
System.getProperties().remove(LocalRegion.EXPIRY_MS_PROPERTY);
}
}
public void generalEntryExpirationTest(final Region<String, String> exprReg,
ExpirationAttributes exprAtt,
boolean useTTL)
throws CacheException
{
final LocalRegion lr = (LocalRegion) exprReg;
final boolean wasDestroyed[] = {false};
AttributesMutator<String, String> mutator = exprReg.getAttributesMutator();
final AtomicInteger ac = new AtomicInteger();
final AtomicInteger au = new AtomicInteger();
final AtomicInteger ai = new AtomicInteger();
final AtomicInteger ad = new AtomicInteger();
if (useTTL) {
mutator.setEntryTimeToLive(exprAtt);
} else {
mutator.setEntryIdleTimeout(exprAtt);
}
final CacheListener<String, String> cl = new CacheListenerAdapter<String, String>() {
public void afterCreate(EntryEvent<String, String> e) {
ac.incrementAndGet();
}
public void afterUpdate(EntryEvent<String, String> e) {
au.incrementAndGet();
}
public void afterInvalidate(EntryEvent<String, String> e) {
ai.incrementAndGet();
}
public void afterDestroy(EntryEvent<String, String> e) {
ad.incrementAndGet();
if (e.getKey().equals("key0")) {
synchronized(wasDestroyed) {
wasDestroyed[0] = true;
wasDestroyed.notifyAll();
}
}
}
public void afterRegionInvalidate(RegionEvent<String, String> event) {
fail("Unexpected invocation of afterRegionInvalidate");
}
public void afterRegionDestroy(RegionEvent<String, String> event) {
if (!event.getOperation().isClose()) {
fail("Unexpected invocation of afterRegionDestroy");
}
}
};
mutator.addCacheListener(cl);
try {
ExpiryTask.suspendExpiration();
// Test to ensure an expiration does not cause a conflict
for(int i=0; i<2; i++) {
exprReg.put("key" + i, "value" + i);
}
this.txMgr.begin();
exprReg.put("key0", "value");
waitForEntryExpiration(lr, "key0");
assertEquals("value", exprReg.getEntry("key0").getValue());
try {
ExpiryTask.suspendExpiration();
this.txMgr.commit();
} catch (CommitConflictException error) {
fail("Expiration should not cause commit to fail");
}
assertEquals("value", exprReg.getEntry("key0").getValue());
waitForEntryExpiration(lr, "key0");
synchronized(wasDestroyed) {
assertEquals(true, wasDestroyed[0]);
}
assertTrue(!exprReg.containsKey("key0"));
// key1 is the canary for the rest of the entries
assertTrue(!exprReg.containsKey("key1"));
// rollback and failed commit test, ensure expiration continues
for(int j=0; j<2; j++) {
synchronized(wasDestroyed) {
wasDestroyed[0] = false;
}
ExpiryTask.suspendExpiration();
for(int i=0; i<2; i++) {
exprReg.put("key" + i, "value" + i);
}
this.txMgr.begin();
exprReg.put("key0", "value");
waitForEntryExpiration(lr, "key0");
assertEquals("value", exprReg.getEntry("key0").getValue());
String checkVal;
ExpiryTask.suspendExpiration();
if (j==0) {
checkVal = "value0";
this.txMgr.rollback();
} else {
checkVal = "conflictVal";
final TXManagerImpl txMgrImpl = (TXManagerImpl)this.txMgr;
TXStateProxy tx = txMgrImpl.internalSuspend();
exprReg.put("key0", checkVal);
txMgrImpl.resume(tx);
try {
this.txMgr.commit();
fail("Expected CommitConflictException!");
} catch (CommitConflictException expected) {}
}
waitForEntryExpiration(lr, "key0");
synchronized(wasDestroyed) {
assertEquals(true, wasDestroyed[0]);
}
assertTrue(!exprReg.containsKey("key0"));
// key1 is the canary for the rest of the entries
assertTrue(!exprReg.containsKey("key1"));
}
} finally {
mutator.removeCacheListener(cl);
ExpiryTask.permitExpiration();
}
}
private void waitForEntryExpiration(LocalRegion lr, String key) {
ExpirationDetector detector = new ExpirationDetector(lr.getEntryExpiryTask(key));
ExpiryTask.expiryTaskListener = detector;
try {
ExpiryTask.permitExpiration();
DistributedTestCase.waitForCriterion(detector, 3000, 2, true);
} finally {
ExpiryTask.expiryTaskListener = null;
}
}
private void waitForRegionExpiration(LocalRegion lr, boolean ttl) {
ExpirationDetector detector = new ExpirationDetector(ttl ? lr.getRegionTTLExpiryTask() : lr.getRegionIdleExpiryTask());
ExpiryTask.expiryTaskListener = detector;
try {
ExpiryTask.permitExpiration();
DistributedTestCase.waitForCriterion(detector, 3000, 2, true);
} finally {
ExpiryTask.expiryTaskListener = null;
}
}
/**
* Used to detect that a particular ExpiryTask has expired.
*/
public static class ExpirationDetector implements ExpiryTaskListener, WaitCriterion {
private volatile boolean expired = false;
private final ExpiryTask et;
public ExpirationDetector(ExpiryTask et) {
assertNotNull(et);
this.et = et;
}
@Override
public void afterExpire(ExpiryTask et) {
if (et == this.et) {
this.expired = true;
}
}
@Override
public boolean done() {
return this.expired;
}
@Override
public String description() {
return "the expiry task " + this.et + " did not expire";
}
}
@Test
public void testRegionIdleExpiration() throws CacheException {
Region<String, String> exprReg = createRegion("TXRegionIdle");
generalRegionExpirationTest(exprReg, new ExpirationAttributes(1, ExpirationAction.INVALIDATE), false);
generalRegionExpirationTest(exprReg, new ExpirationAttributes(1, ExpirationAction.DESTROY), false);
}
@Test
public void testRegionTTLExpiration() throws CacheException {
Region<String, String> exprReg = createRegion("TXRegionTTL");
generalRegionExpirationTest(exprReg, new ExpirationAttributes(1, ExpirationAction.INVALIDATE), true);
generalRegionExpirationTest(exprReg, new ExpirationAttributes(1, ExpirationAction.DESTROY), true);
}
private void generalRegionExpirationTest(final Region<String, String> exprReg,
ExpirationAttributes exprAtt,
boolean useTTL)
throws CacheException
{
final LocalRegion lr = (LocalRegion) exprReg;
final ExpirationAction action = exprAtt.getAction();
final boolean regionExpiry[] = {false};
AttributesMutator<String, String> mutator = exprReg.getAttributesMutator();
final CacheListener<String, String> cl = new CacheListenerAdapter<String, String>() {
public void afterRegionInvalidate(RegionEvent<String, String> event) {
synchronized(regionExpiry) {
regionExpiry[0] = true;
regionExpiry.notifyAll();
}
}
public void afterRegionDestroy(RegionEvent<String, String> event) {
if (!event.getOperation().isClose()) {
synchronized(regionExpiry) {
regionExpiry[0] = true;
regionExpiry.notifyAll();
}
}
}
};
mutator.addCacheListener(cl);
// Suspend before enabling region expiration to prevent
// it from happening before we do the put.
ExpiryTask.suspendExpiration();
try {
if (useTTL) {
mutator.setRegionTimeToLive(exprAtt);
} else {
mutator.setRegionIdleTimeout(exprAtt);
}
// Create some keys and age them, I wish we could fake/force the age
// instead of having to actually wait
for(int i=0; i<2; i++) {
exprReg.put("key" + i, "value" + i);
}
String regName = exprReg.getName();
// Test to ensure a region expiration does not cause a conflict
this.txMgr.begin();
exprReg.put("key0", "value");
waitForRegionExpiration(lr, useTTL);
assertEquals("value", exprReg.getEntry("key0").getValue());
try {
ExpiryTask.suspendExpiration();
this.txMgr.commit();
} catch (CommitConflictException error) {
fail("Expiration should not cause commit to fail");
}
assertEquals("value", exprReg.getEntry("key0").getValue());
waitForRegionExpiration(lr, useTTL);
synchronized(regionExpiry) {
assertEquals(true, regionExpiry[0]);
}
if (action == ExpirationAction.DESTROY) {
assertNull("listener saw Region expiration, expected a destroy operation!",
this.cache.getRegion(regName));
} else {
assertTrue("listener saw Region expiration, expected invalidation",
!exprReg.containsValueForKey("key0"));
}
} finally {
if (!exprReg.isDestroyed()) {
mutator.removeCacheListener(cl);
}
ExpiryTask.permitExpiration();
}
// @todo mitch test rollback and failed expiration
}
}
| apache-2.0 |
itsgrimetime/emr-dynamodb-connector | emr-dynamodb-hadoop/src/test/java/org/apache/hadoop/dynamodb/read/PageResultMultiplexerTest.java | 8548 | /**
* Copyright 2012-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.TXT" 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 org.apache.hadoop.dynamodb.read;
import org.apache.hadoop.dynamodb.preader.PageResultMultiplexer;
import org.apache.hadoop.dynamodb.preader.PageResults;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class PageResultMultiplexerTest {
public static final int DEFAULT_CAPACITY = 1000;
/*
* Make sure basic multiplexing works, pages of even sizes - no blocking.
*/
@Test(timeout = 2000)
public void basicMultiplexingTest() throws Exception {
final int BATCH_SIZE = 5;
PageResultMultiplexer<Integer> mux = new PageResultMultiplexer<>(BATCH_SIZE, DEFAULT_CAPACITY);
for (int p = 0; p < BATCH_SIZE; p++) {
mux.addPageResults(new PageResults<>(Arrays.asList(p, p, p), null));
}
mux.setDraining(true);
Integer[] expectedOrder = {0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4};
Assert.assertArrayEquals(expectedOrder, muxToList(mux).toArray());
}
/*
* Multiplex over pages of different sizes
*/
@Test(timeout = 2000)
public void differentSizedPages() throws Exception {
final int BATCH_SIZE = 5;
PageResultMultiplexer<Integer> mux = new PageResultMultiplexer<>(BATCH_SIZE, DEFAULT_CAPACITY);
mux.addPageResults(new PageResults<>(Arrays.asList(1, 1, 1), null));
mux.addPageResults(new PageResults<>(Arrays.asList(2), null));
mux.addPageResults(new PageResults<>(Arrays.asList(3, 3, 3, 3), null));
mux.addPageResults(new PageResults<>(Arrays.asList(4, 4), null));
mux.setDraining(true);
Integer[] expectedOrder = {1, 2, 3, 4, 1, 3, 4, 1, 3, 3};
Assert.assertArrayEquals(expectedOrder, muxToList(mux).toArray());
}
/*
* Test that next() blocks until it has enough pages in the multiplexer, but then fully drains
* once in "drain mode".
*/
@Test(timeout = 2000)
public void testRequiredBatch() throws InterruptedException {
final int BATCH_SIZE = 3;
PageResultMultiplexer<Integer> mux = new PageResultMultiplexer<>(BATCH_SIZE, DEFAULT_CAPACITY);
MuxConsumer consumer = new MuxConsumer(mux);
consumer.start();
mux.addPageResults(new PageResults<>(Arrays.asList(1, 1, 1), null));
mux.addPageResults(new PageResults<>(Arrays.asList(2, 2), null));
// Nothing has been consumed because we haven't reached the max batch
// size yet
Assert.assertEquals(0, consumer.out.size());
// Add one more page to make #pages >= BATCH_SIZE to kick off consuming
// Expect consuming 5 items.
consumer.jobTrackLatch = new CountDownLatch(5);
mux.addPageResults(new PageResults<>(Arrays.asList(3, 3, 3), null));
consumer.jobTrackLatch.await();
Assert.assertArrayEquals(new Integer[]{1, 2, 3, 1, 2}, consumer.out.toArray());
// Kick off drain mode. Remaining items will be fetched
mux.setDraining(true);
consumer.jobFinishLatch.await();
Assert.assertArrayEquals(new Integer[]{1, 2, 3, 1, 2, 3, 1, 3}, consumer.out.toArray());
}
/*
* Test that addPageResults() blocks until there is free capacity.
*/
@Test(timeout = 2000)
public void testMaximumCapacity() throws InterruptedException, IOException {
final int BATCH_SIZE = 1;
final int CAPACITY = 5;
final int PAGE_COUNT = 8;
PageResultMultiplexer<Integer> mux = new PageResultMultiplexer<>(BATCH_SIZE, CAPACITY);
MuxProducer producer = new MuxProducer(mux, PAGE_COUNT);
// Only CAPACITY pages will be added
producer.jobTrackLatch = new CountDownLatch(CAPACITY);
producer.start();
producer.jobTrackLatch.await();
Assert.assertEquals(CAPACITY, producer.idx);
// Remove CAPACITY items from the queue, which effectively removes
// CAPACITY pages because one page has only one item
for (int i = 0; i < CAPACITY; i++) {
Assert.assertNotNull(mux.next());
}
// Producer is now able to add (PAGE_COUNT - CAPACITY) items to mux
producer.jobFinishLatch.await();
Assert.assertEquals(PAGE_COUNT, producer.idx);
// Set the mux in drain mode to consume the remaining items
mux.setDraining(true);
for (int i = 0; i < PAGE_COUNT - CAPACITY; i++) {
Assert.assertNotNull(mux.next());
}
Assert.assertNull(mux.next());
}
@Test(timeout = 100000)
public void testWithMultipleThreads() throws InterruptedException, IOException {
final int BATCH_SIZE = 10;
final int CAPACITY = 1000;
final int PRODUCERS = 100;
final int CONSUMERS = 20;
PageResultMultiplexer<Integer> mux = new PageResultMultiplexer<>(BATCH_SIZE, CAPACITY);
List<MuxProducer> producers = new ArrayList<>(PRODUCERS);
List<MuxConsumer> consumers = new ArrayList<>(CONSUMERS);
// Start consumers
for (int i = 0; i < CONSUMERS; i++) {
MuxConsumer t = new MuxConsumer(mux);
t.start();
consumers.add(t);
}
// Assert that all consumers are alive before starting producers
for (MuxConsumer consumer : consumers) {
Assert.assertTrue(consumer.isAlive());
}
// Start producers
for (int i = 0; i < PRODUCERS; i++) {
MuxProducer t = new MuxProducer(mux, Integer.MAX_VALUE);
t.start();
producers.add(t);
}
// Let them run a second
Thread.sleep(1000);
// Assert that everyone's alive
for (MuxConsumer consumer : consumers) {
Assert.assertTrue(consumer.isAlive());
}
for (MuxProducer producer : producers) {
Assert.assertTrue(producer.isAlive());
}
// Shut producers down.
for (MuxProducer producer : producers) {
producer.alive = false;
producer.join();
producer.jobFinishLatch.await();
}
// Set the mux in drain mode and wait on the consumers
mux.setDraining(true);
for (MuxConsumer consumer : consumers) {
consumer.join();
consumer.jobFinishLatch.await();
}
// success if not timing out
}
/**
* Helper function, fully consume multiplexer output into a list (blocking).
*/
private List<Integer> muxToList(PageResultMultiplexer<Integer> mux) throws
InterruptedException, IOException {
Integer n;
List<Integer> list = new ArrayList<>();
while (true) {
if ((n = mux.next()) == null) {
break;
}
list.add(n);
}
return list;
}
/*
* Helper class, thread that consumes from a multiplexer and appends to a list for inspection.
*/
private static class MuxConsumer extends Thread {
private final PageResultMultiplexer<Integer> mux;
private final CountDownLatch jobFinishLatch = new CountDownLatch(1);
private final List<Integer> out = new ArrayList<>();
private CountDownLatch jobTrackLatch;
public MuxConsumer(PageResultMultiplexer<Integer> mux) {
this.mux = mux;
}
@Override
public void run() {
try {
Integer n;
while ((n = mux.next()) != null) {
out.add(n);
if (jobTrackLatch != null) {
jobTrackLatch.countDown();
}
}
jobFinishLatch.countDown();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
private static class MuxProducer extends Thread {
private final PageResultMultiplexer<Integer> mux;
private final int cnt;
private final CountDownLatch jobFinishLatch = new CountDownLatch(1);
private volatile int idx;
private volatile boolean alive = true;
private CountDownLatch jobTrackLatch;
public MuxProducer(PageResultMultiplexer<Integer> mux, int cnt) {
this.mux = mux;
this.cnt = cnt;
}
@Override
public void run() {
for (idx = 0; idx < cnt && alive; ) {
mux.addPageResults(new PageResults<>(Arrays.asList(idx), null /* lastEvalKey */));
idx++;
if (jobTrackLatch != null) {
jobTrackLatch.countDown();
}
}
jobFinishLatch.countDown();
}
}
}
| apache-2.0 |
LucidWorks/hbase-indexer | hbase-indexer-server/src/main/java/com/ngdata/hbaseindexer/supervisor/IndexerSupervisor.java | 18063 | /*
* Copyright 2013 NGDATA nv
*
* 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.ngdata.hbaseindexer.supervisor;
import static com.ngdata.hbaseindexer.indexer.SolrServerFactory.createCloudSolrServer;
import static com.ngdata.hbaseindexer.indexer.SolrServerFactory.createHttpSolrServers;
import static com.ngdata.hbaseindexer.indexer.SolrServerFactory.createSharder;
import static com.ngdata.hbaseindexer.model.api.IndexerModelEventType.INDEXER_ADDED;
import static com.ngdata.hbaseindexer.model.api.IndexerModelEventType.INDEXER_DELETED;
import static com.ngdata.hbaseindexer.model.api.IndexerModelEventType.INDEXER_UPDATED;
import static com.ngdata.hbaseindexer.util.solr.SolrConnectionParamUtil.getSolrMaxConnectionsPerRoute;
import static com.ngdata.hbaseindexer.util.solr.SolrConnectionParamUtil.getSolrMaxConnectionsTotal;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.base.Objects;
import com.google.common.collect.Maps;
import com.ngdata.hbaseindexer.conf.IndexerComponentFactory;
import com.ngdata.hbaseindexer.conf.IndexerComponentFactoryUtil;
import com.ngdata.hbaseindexer.conf.IndexerConf;
import com.ngdata.hbaseindexer.indexer.DirectSolrClassicInputDocumentWriter;
import com.ngdata.hbaseindexer.indexer.DirectSolrInputDocumentWriter;
import com.ngdata.hbaseindexer.indexer.FusionDocumentWriter;
import com.ngdata.hbaseindexer.indexer.Indexer;
import com.ngdata.hbaseindexer.indexer.IndexingEventListener;
import com.ngdata.hbaseindexer.indexer.Sharder;
import com.ngdata.hbaseindexer.indexer.SolrInputDocumentWriter;
import com.ngdata.hbaseindexer.model.api.IndexerDefinition;
import com.ngdata.hbaseindexer.model.api.IndexerDefinition.IncrementalIndexingState;
import com.ngdata.hbaseindexer.model.api.IndexerModel;
import com.ngdata.hbaseindexer.model.api.IndexerModelEvent;
import com.ngdata.hbaseindexer.model.api.IndexerModelListener;
import com.ngdata.hbaseindexer.model.api.IndexerNotFoundException;
import com.ngdata.hbaseindexer.model.api.IndexerProcessRegistry;
import com.ngdata.hbaseindexer.parse.ResultToSolrMapper;
import com.ngdata.hbaseindexer.util.solr.SolrConnectionParamUtil;
import com.ngdata.sep.impl.SepConsumer;
import com.ngdata.sep.util.io.Closer;
import com.ngdata.sep.util.zookeeper.ZooKeeperItf;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.HTablePool;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.zookeeper.KeeperException;
/**
* Responsible for starting, stopping and restarting {@link Indexer}s for the indexers defined in the
* {@link IndexerModel}.
*/
public class IndexerSupervisor {
private final IndexerModel indexerModel;
private final ZooKeeperItf zk;
private final String hostName;
private final IndexerModelListener listener = new MyListener();
private final Map<String, IndexerHandle> indexers = new HashMap<String, IndexerHandle>();
private final Object indexersLock = new Object();
private final BlockingQueue<IndexerModelEvent> eventQueue = new LinkedBlockingQueue<IndexerModelEvent>();
private EventWorker eventWorker;
private Thread eventWorkerThread;
private HttpClient httpClient;
private final IndexerRegistry indexerRegistry;
private final IndexerProcessRegistry indexerProcessRegistry;
private final Map<String, String> indexerProcessIds;
private final HTablePool htablePool;
private final Configuration hbaseConf;
private final Log log = LogFactory.getLog(getClass());
/**
* Total number of IndexerModel events processed (useful in test cases).
*/
private final AtomicInteger eventCount = new AtomicInteger();
public IndexerSupervisor(IndexerModel indexerModel, ZooKeeperItf zk, String hostName,
IndexerRegistry indexerRegistry, IndexerProcessRegistry indexerProcessRegistry,
HTablePool htablePool, Configuration hbaseConf)
throws IOException, InterruptedException {
this.indexerModel = indexerModel;
this.zk = zk;
this.hostName = hostName;
this.indexerRegistry = indexerRegistry;
this.indexerProcessRegistry = indexerProcessRegistry;
this.indexerProcessIds = Maps.newHashMap();
this.htablePool = htablePool;
this.hbaseConf = hbaseConf;
}
@PostConstruct
public void init() {
eventWorker = new EventWorker();
eventWorkerThread = new Thread(eventWorker, "IndexerWorkerEventWorker");
eventWorkerThread.start();
synchronized (indexersLock) {
Collection<IndexerDefinition> indexerDefs = indexerModel.getIndexers(listener);
for (IndexerDefinition indexerDef : indexerDefs) {
if (shouldRunIndexer(indexerDef)) {
startIndexer(indexerDef);
}
}
}
}
@PreDestroy
public void stop() {
eventWorker.stop();
eventWorkerThread.interrupt();
try {
eventWorkerThread.join();
} catch (InterruptedException e) {
log.info("Interrupted while joining eventWorkerThread.");
}
for (IndexerHandle handle : indexers.values()) {
try {
handle.stop();
} catch (InterruptedException e) {
// Continue the stop procedure
}
}
}
public int getEventCount() {
return eventCount.get();
}
public Set<String> getRunningIndexers() {
return indexers.keySet();
}
public Indexer getIndexer(String name) {
return indexers.get(name).indexer;
}
private void startIndexer(IndexerDefinition indexerDef) {
IndexerHandle handle = null;
SolrClient solr = null;
String indexerProcessId = null;
try {
// If this is an update and the indexer failed to start, it's still in the registry as a
// failed process
if (indexerProcessIds.containsKey(indexerDef.getName())) {
indexerProcessRegistry.unregisterIndexerProcess(indexerProcessIds.remove(indexerDef.getName()));
}
indexerProcessId = indexerProcessRegistry.registerIndexerProcess(indexerDef.getName(), hostName);
indexerProcessIds.put(indexerDef.getName(), indexerProcessId);
// Create and register the indexer
IndexerComponentFactory factory = IndexerComponentFactoryUtil.getComponentFactory(indexerDef.getIndexerComponentFactory(), new ByteArrayInputStream(indexerDef.getConfiguration()), indexerDef.getConnectionParams());
IndexerConf indexerConf = factory.createIndexerConf();
ResultToSolrMapper mapper = factory.createMapper(indexerDef.getName());
Sharder sharder = null;
SolrInputDocumentWriter solrWriter;
PoolingClientConnectionManager connectionManager = null;
if (indexerDef.getConnectionType() == null || indexerDef.getConnectionType().equals("solr")) {
Map<String, String> connectionParams = indexerDef.getConnectionParams();
String solrMode = SolrConnectionParamUtil.getSolrMode(connectionParams);
if (solrMode.equals("cloud")) {
solrWriter = new DirectSolrInputDocumentWriter(indexerDef.getName(), createCloudSolrServer(connectionParams));
} else if (solrMode.equals("classic")) {
connectionManager = new PoolingClientConnectionManager();
connectionManager.setDefaultMaxPerRoute(getSolrMaxConnectionsPerRoute(connectionParams));
connectionManager.setMaxTotal(getSolrMaxConnectionsTotal(connectionParams));
httpClient = new DefaultHttpClient(connectionManager);
List<SolrClient> solrServers = createHttpSolrServers(connectionParams, httpClient);
solrWriter = new DirectSolrClassicInputDocumentWriter(indexerDef.getName(), solrServers);
sharder = createSharder(connectionParams, solrServers.size());
} else if (solrMode.equals("fusion")) {
solrWriter = new FusionDocumentWriter(indexerDef.getName(), connectionParams);
} else {
throw new RuntimeException("Only 'cloud' and 'classic' are valid values for solr.mode, but got " + solrMode);
}
} else {
throw new RuntimeException(
"Invalid connection type: " + indexerDef.getConnectionType() + ". Only 'solr' is supported");
}
Indexer indexer = Indexer.createIndexer(indexerDef.getName(), indexerConf, indexerConf.getTable(),
mapper, htablePool, sharder, solrWriter);
IndexingEventListener eventListener = new IndexingEventListener(
indexer, indexerConf.getTable(), indexerConf.tableNameIsRegex());
int threads = hbaseConf.getInt("hbaseindexer.indexer.threads", 10);
SepConsumer sepConsumer = new SepConsumer(indexerDef.getSubscriptionId(),
indexerDef.getSubscriptionTimestamp(), eventListener, threads, hostName,
zk, hbaseConf, null);
handle = new IndexerHandle(indexerDef, indexer, sepConsumer, solr, connectionManager);
handle.start();
indexers.put(indexerDef.getName(), handle);
indexerRegistry.register(indexerDef.getName(), indexer);
log.info("Started indexer for " + indexerDef.getName());
} catch (Throwable t) {
if (t instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
log.error("Problem starting indexer " + indexerDef.getName(), t);
try {
if (indexerProcessId != null) {
indexerProcessRegistry.setErrorStatus(indexerProcessId, t);
}
} catch (Exception e) {
log.error("Error setting error status on indexer process " + indexerProcessId, e);
}
if (handle != null) {
// stop any listeners that might have been started
try {
handle.stop();
} catch (Throwable t2) {
if (t2 instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
log.error("Problem stopping consumers for failed-to-start indexer '" +
indexerDef.getName() + "'", t2);
}
} else {
// Might be the handle was not yet created, but the solr connection was
Closer.close(solr);
}
}
}
private void restartIndexer(IndexerDefinition indexerDef) {
IndexerHandle handle = indexers.get(indexerDef.getName());
if (handle.indexerDef.getOccVersion() >= indexerDef.getOccVersion()) {
return;
}
boolean relevantChanges = !Arrays.equals(handle.indexerDef.getConfiguration(), indexerDef.getConfiguration()) ||
Objects.equal(handle.indexerDef.getConnectionType(), indexerDef.getConnectionType())
|| !Objects.equal(handle.indexerDef.getConnectionParams(), indexerDef.getConnectionParams());
if (!relevantChanges) {
return;
}
if (stopIndexer(indexerDef.getName())) {
startIndexer(indexerDef);
}
}
private boolean stopIndexer(String indexerName) {
indexerRegistry.unregister(indexerName);
String processId = indexerProcessIds.remove(indexerName);
if (processId == null) {
log.warn("No indexer process to unregister for indexer " + indexerName);
} else {
try {
indexerProcessRegistry.unregisterIndexerProcess(processId);
} catch (Exception e) {
log.error("Error unregistering indexer process (from zookeeper): " + indexerProcessIds, e);
}
}
IndexerHandle handle = indexers.get(indexerName);
if (handle == null) {
return true;
}
try {
handle.stop();
indexers.remove(indexerName);
log.info("Stopped indexer " + indexerName);
return true;
} catch (Throwable t) {
log.fatal("Failed to stop an indexer that should be stopped.", t);
return false;
}
}
private class MyListener implements IndexerModelListener {
@Override
public void process(IndexerModelEvent event) {
try {
// Because the actions we take in response to events might take some time, we
// let the events process by another thread, so that other watchers do not
// have to wait too long.
eventQueue.put(event);
} catch (InterruptedException e) {
log.info("IndexerSupervisor.IndexerModelListener interrupted.");
}
}
}
private boolean shouldRunIndexer(IndexerDefinition indexerDef) {
return indexerDef.getIncrementalIndexingState() == IncrementalIndexingState.SUBSCRIBE_AND_CONSUME &&
indexerDef.getSubscriptionId() != null &&
!indexerDef.getLifecycleState().isDeleteState();
}
private class IndexerHandle {
private final IndexerDefinition indexerDef;
private final Indexer indexer;
private final SepConsumer sepConsumer;
private final SolrClient solrServer;
private final PoolingClientConnectionManager connectionManager;
public IndexerHandle(IndexerDefinition indexerDef, Indexer indexer, SepConsumer sepEventSlave,
SolrClient solrServer, PoolingClientConnectionManager connectionManager) {
this.indexerDef = indexerDef;
this.indexer = indexer;
this.sepConsumer = sepEventSlave;
this.solrServer = solrServer;
this.connectionManager = connectionManager;
}
public void start() throws InterruptedException, KeeperException, IOException {
sepConsumer.start();
}
public void stop() throws InterruptedException {
Closer.close(sepConsumer);
Closer.close(solrServer);
Closer.close(indexer);
Closer.close(connectionManager);
}
}
private class EventWorker implements Runnable {
private volatile boolean stop = false;
public void stop() {
stop = true;
}
@Override
public void run() {
while (!stop) { // We need the stop flag because some code (HBase client code) eats interrupted flags
if (Thread.interrupted()) {
return;
}
try {
int queueSize = eventQueue.size();
if (queueSize >= 10) {
log.warn("EventWorker queue getting large, size = " + queueSize);
}
IndexerModelEvent event = eventQueue.take();
log.debug("Took event from queue: " + event.toString());
if (event.getType() == INDEXER_ADDED || event.getType() == INDEXER_UPDATED) {
try {
IndexerDefinition indexerDef = indexerModel.getIndexer(event.getIndexerName());
if (shouldRunIndexer(indexerDef)) {
if (indexers.containsKey(indexerDef.getName())) {
restartIndexer(indexerDef);
} else {
startIndexer(indexerDef);
}
} else {
stopIndexer(indexerDef.getName());
}
} catch (IndexerNotFoundException e) {
stopIndexer(event.getIndexerName());
} catch (Throwable t) {
log.error("Error in IndexerWorker's IndexerModelListener.", t);
}
} else if (event.getType() == INDEXER_DELETED) {
stopIndexer(event.getIndexerName());
}
eventCount.incrementAndGet();
} catch (InterruptedException e) {
log.info("IndexerWorker.EventWorker interrupted.");
return;
} catch (Throwable t) {
log.error("Error processing indexer model event in IndexerWorker.", t);
}
}
}
}
}
| apache-2.0 |
autumnLei/xiangyu | app/src/main/java/com/example/xiangyu/global/MyApplication.java | 2129 | package com.example.xiangyu.global;
import android.app.Application;
import android.app.Service;
import android.content.Context;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import com.baidu.mapapi.SDKInitializer;
import com.example.xiangyu.R;
import com.example.xiangyu.service.LocationService;
import com.example.xiangyu.ui.XiangYuActivity;
import com.zxy.recovery.core.Recovery;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by Administrator on 2017/3/29.
*/
public class MyApplication extends Application {
private static Context context;
public static int H;
public static List<?> images=new ArrayList<>();
public static List<String> titles=new ArrayList<>();
public LocationService locationService;
public Vibrator mVibrator;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
initBanner();
/***
* 初始化定位sdk,建议在Application中创建
*/
locationService = new LocationService(getApplicationContext());
mVibrator =(Vibrator)getApplicationContext().getSystemService(Service.VIBRATOR_SERVICE);
SDKInitializer.initialize(getApplicationContext());
}
public static Context getContext() {
return context;
}
private void initBanner() {
H = getScreenH(this);
Recovery.getInstance()
.debug(true)
.recoverInBackground(false)
.recoverStack(true)
.mainPage(XiangYuActivity.class)
.init(this);
String[] urls = getResources().getStringArray(R.array.url4);
// String[] tips = getResources().getStringArray(R.array.title);
List list = Arrays.asList(urls);
images = new ArrayList<>(list);
// titles= Arrays.asList(tips);
}
/**
* 获取屏幕高度
* @param aty
* @return
*/
public int getScreenH(Context aty){
DisplayMetrics dm = aty.getResources().getDisplayMetrics();
return dm.heightPixels;
}
}
| apache-2.0 |
nasa/OpenSPIFe | gov.nasa.ensemble.core.model.plan.diff/src/gov/nasa/ensemble/core/model/plan/diff/impl/ChangedByAddingNewElementImpl.java | 1639 | /*******************************************************************************
* Copyright 2014 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* 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 gov.nasa.ensemble.core.model.plan.diff.impl;
import gov.nasa.ensemble.core.model.plan.EPlanChild;
import gov.nasa.ensemble.core.model.plan.EPlanElement;
import gov.nasa.ensemble.core.model.plan.diff.api.ChangedByAddingNewElement;
import gov.nasa.ensemble.core.model.plan.diff.api.PlanDiffList;
public class ChangedByAddingNewElementImpl implements ChangedByAddingNewElement {
private EPlanChild element;
public ChangedByAddingNewElementImpl(EPlanChild element, PlanDiffList diffInfo) {
this.element = element;
}
@Override
public EPlanChild getAddedElement() {
return element;
}
@Override
public EPlanElement getNewParent() {
return element.getParent();
}
@Override
public DiffType getDiffType() {
return DiffType.ADD;
}
}
| apache-2.0 |
bitstorm/Wicket-tutorial-examples | SimpleDropDownChoice/src/main/java/org/wicketTutorial/dropdown/WicketApplication.java | 1454 | /**
* 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.wicketTutorial.dropdown;
import org.wicketTutorial.commons.bootstrap.BootstrapApp;
/**
* Application object for your web application. If you want to run this application without deploying, run the Start class.
*
* @see org.wicketTutorial.dropdown.Start#main(String[])
*/
public class WicketApplication extends BootstrapApp
{
/**
* @see org.apache.wicket.Application#getHomePage()
*/
@Override
public Class<HomePage> getHomePage()
{
return HomePage.class;
}
/**
* @see org.apache.wicket.Application#init()
*/
@Override
public void init()
{
super.init();
// add your configuration here
}
}
| apache-2.0 |
Zahusek/TinyProtocolAPI | com/gmail/zahusek/tinyprotocolapi/api/tab/TabHolder.java | 6513 | package com.gmail.zahusek.tinyprotocolapi.api.tab;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.UUID;
import com.gmail.zahusek.tinyprotocolapi.TinyProtocolAPI;
import com.gmail.zahusek.tinyprotocolapi.api.Preference;
import com.gmail.zahusek.tinyprotocolapi.packet.Packet;
import com.gmail.zahusek.tinyprotocolapi.packet.PacketHeaderFooter;
import com.gmail.zahusek.tinyprotocolapi.packet.PacketPlayerInfo;
import com.gmail.zahusek.tinyprotocolapi.wrapper.WrapperEnum.GameType;
import com.gmail.zahusek.tinyprotocolapi.wrapper.WrapperEnum.InfoAction;
import com.gmail.zahusek.tinyprotocolapi.wrapper.WrapperInfoData;
import com.mojang.authlib.GameProfile;
public class TabHolder implements TabModify
{
final int x = 4, y = 20;
final GameProfile[][] profile = new GameProfile[x][y];
final String uuid = "00000000-0000-%s-0000-000000000000";
final String token = "!@#$^*";
final GameType gamemode = GameType.NOT_SET;
Class<?> plugin;
Preference priority;
boolean exist = false;
String[][] message = new String[x][y];
boolean[][] xmessage = new boolean[x][y];
int[][] signal = new int[x][y];
boolean[][] xsignal = new boolean[x][y];
String[][] texture = new String[x][y];
boolean[][] xtexture = new boolean[x][y];
String _message = "";
int _signal = 0;
String _texture = "MHF_Question";
final PacketPlayerInfo remove = new PacketPlayerInfo(InfoAction.REMOVE_PLAYER);
final PacketHeaderFooter hnf = new PacketHeaderFooter();
TabHolder()
{
final LinkedList<WrapperInfoData> xdefault = new LinkedList<>();
for(int x = 0; x < this.x; x++)
{
for(int y = 0; y < this.y; y++)
{
String idx = digit(x);
String idy = digit(y);
GameProfile profile = this.profile[x][y] = new GameProfile(UUID.fromString(String.format(uuid, idx + idy)), token + idx + token + idy);
xdefault.add(new WrapperInfoData(profile, _signal, gamemode, _message));
}
}
remove.addAll(xdefault);
reset();
}
protected Packet[] update()
{
final PacketPlayerInfo add = new PacketPlayerInfo(InfoAction.ADD_PLAYER);
final PacketPlayerInfo display = new PacketPlayerInfo(InfoAction.UPDATE_DISPLAY_NAME);
final PacketPlayerInfo latency = new PacketPlayerInfo(InfoAction.UPDATE_LATENCY);
for(int x = 0; x < this.x; x++)
{
for(int y = 0; y < this.y; y++)
{
WrapperInfoData data = new WrapperInfoData(profile[x][y], signal[x][y], gamemode, message[x][y]);
if(!exist || !xtexture[x][y])
{
data.setTexture(texture[x][y]);
add.add(data);
xtexture[x][y] = true;
}
if(!xmessage[x][y])
{
display.add(data);
xmessage[x][y] = true;
}
if(!xsignal[x][y])
{
latency.add(data);
xsignal[x][y] = true;
}
}
}
exist = true;
return new Packet[] {add, display, latency};
}
protected Packet[] remove()
{
reset();
return new Packet[] {hnf, remove};
}
@Override
public void setMessage(int x, int y, String message) {
if(this.message[x][y].equals(message)) return;
this.message[x][y] = message;
xmessage[x][y] = false;
}
@Override
public void setTexture(int x, int y, String texture) {
if(this.texture[x][y].equals(texture))return;
this.texture[x][y] = texture;
xtexture[x][y] = false;
}
@Override
public void setSignal(int x, int y, int signal)
{
if(this.signal[x][y] == signal) return;
this.signal[x][y] = signal;
xsignal[x][y] = false;
}
@Override
public void setTexture(String texture) {
for(int x = 0; x < this.x; x++)
for(int y = 0; y < this.y; y++)
setTexture(x, y, texture);
}
@Override
public void setSignal(int signal) {
for(int x = 0; x < this.x; x++)
for(int y = 0; y < this.y; y++)
setSignal(x, y, signal);
}
@Override
public void set(int x, int y, String message, String texture) {
setMessage(x, y, message);
setTexture(x, y, texture);
}
@Override
public void set(int x, int y, String message, int signal) {
setMessage(x, y, message);
setSignal(x, y, signal);
}
@Override
public void set(int x, int y, String message, String texture, int signal) {
setMessage(x, y, message);
setSignal(x, y, signal);
setTexture(x, y, texture);
}
@Override
public void setHeader(Collection<String> header) {
if(header == null || header.isEmpty())
return;
String[] head = header.toArray(new String[header.size()]);
StringBuilder text = new StringBuilder();
text.append(head[0] == null ? _message : head[0]);
for(int i = 1; i < head.length; i++)
text.append("\n" + head[i]);
hnf.setHeader(text.toString());
}
@Override
public void setFooter(Collection<String> footer) {
if(footer == null || footer.isEmpty())
return;
String[] foot = footer.toArray(new String[footer.size()]);
StringBuilder text = new StringBuilder();
text.append(foot[0] == null ? _message : foot[0]);
for(int i = 1; i < foot.length; i++)
text.append("\n" + foot[i]);
hnf.setFooter(text.toString());
}
@Override
public void set(Collection<String> header, Collection<String> footer) {
setHeader(header);
setFooter(footer);
}
@Override
public String getMessage(int x, int y) {
return message[x][y];
}
@Override
public String getTexture(int x, int y) {
return texture[x][y];
}
@Override
public int getSignal(int x, int y) {
return signal[x][y];
}
@Override
public ArrayList<String> getHeader() {
ArrayList<String> head = new ArrayList<>();
String[] text = hnf.getHeader().split("\n");
for(String line : text)
head.add(line);
return head;
}
@Override
public ArrayList<String> getFooter() {
ArrayList<String> foot = new ArrayList<>();
String[] text = hnf.getFooter().split("\n");
for(String line : text)
foot.add(line);
return foot;
}
protected void reset()
{
plugin = TinyProtocolAPI.class;
priority = Preference.LOW;
for(int x = 0; x < this.x; x++)
{
for(int y = 0; y < this.y; y++)
{
message[x][y] = _message;
signal[x][y] = _signal;
texture[x][y] = _texture;
}
}
hnf.setFooter(_message);
hnf.setHeader(_message);
exist = false;
}
protected void takeOver(Class<?> a, Preference b)
{
this.plugin = a;
this.priority = b;
}
String digit (int i)
{return i > 9 ? "" + i : "0" + i;}
} | apache-2.0 |
tolo/JServer | src/java/com/teletalk/jadmin/gui/overview/PropertyDialog.java | 27133 | /*
* Copyright 2007 the project originators.
*
* 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.teletalk.jadmin.gui.overview;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.BevelBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import com.teletalk.jadmin.proxy.PropertyProxy;
/**
* Class implementing the dialog box for editing / viewing a property.
*
* @author Tobias Löfstrand
*
* @since Alpha
*/
public final class PropertyDialog extends JDialog implements ActionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
private JButton ok;
private JButton cancel;
private InputPanel inputPanel;
private PropertyProxy property;
/**
* Creates a new PropertyDialog.
*/
public PropertyDialog(final Frame owner, final PropertyProxy property) throws Exception
{
super(owner, "Change property", true);
this.property = property;
JPanel mainPanel = (JPanel)this.getContentPane();
mainPanel.setLayout(new BorderLayout(3,3));
JPanel propertyPanel = new JPanel(new BorderLayout());
propertyPanel.setBorder(BorderFactory.createEtchedBorder());
String description = property.getDescription();
if(property.isModifiable())
{
int type = property.getType();
if(type == PropertyProxy.BOOLEAN_TYPE)
{
inputPanel = new BooleanInputPanel(this, property);
if(description == null)
description = "Boolean property";
}
else if(type == PropertyProxy.DATE_TYPE)
{
inputPanel = new StringInputPanel(this, property);
if(description == null)
description = "Date property";
}
else if(type == PropertyProxy.ENUM_TYPE)
{
inputPanel = new ChoiceInputPanel(this, property);
if(description == null)
description = "Enumeration property";
}
else if(type == PropertyProxy.NUMBER_TYPE)
{
inputPanel = new StringInputPanel(this, property);
if(description == null)
description = "Number property";
}
else if(type == PropertyProxy.MULTIVALUE_TYPE)
{
String delims = (String)property.getMetaData(PropertyProxy.DELIMETER_CHARS_KEY);
if(delims != null) inputPanel = new MultiValueInputPanel(this, property, delims);
else inputPanel = new StringInputPanel(this, property);
if(description == null)
description = "Multi value property";
}
else if(type == PropertyProxy.STRING_TYPE || type == PropertyProxy.CUSTOM_TYPE)
{
inputPanel = new StringInputPanel(this, property);
if(description == null)
description = "String property";
}
else
{
throw new RuntimeException("Invalid property type - " + type + "!");
}
}
else
{
inputPanel = new UnmodifiablePropertyPanel(this, property);
if(description == null)
description = "Unmodifiable property";
}
JPanel propertyInnerPanel = new JPanel();
propertyInnerPanel.setLayout(new BoxLayout(propertyInnerPanel, BoxLayout.Y_AXIS));
JPanel namePanel = new JPanel(new BorderLayout());
namePanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Property:"));
JPanel nameCompoundPanel = new JPanel();
nameCompoundPanel.setLayout(new BoxLayout(nameCompoundPanel, BoxLayout.Y_AXIS));
JPanel nameInnerPanel1 = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
JTextField nameLabel = new JTextField(property.getName(), 25);
nameLabel.setFont(new Font("SansSerif", Font.BOLD, 11));
nameLabel.setForeground(Color.black);
nameLabel.setScrollOffset(0);
nameLabel.setBackground(this.getBackground());
nameLabel.setEditable(false);
nameLabel.setBorder(BorderFactory.createEmptyBorder());
JLabel nameLabelLabel = new JLabel("Name: ");
nameInnerPanel1.add(nameLabelLabel);
nameInnerPanel1.add(Box.createHorizontalStrut(5));
nameInnerPanel1.add(nameLabel);
nameInnerPanel1.setAlignmentY(0.0f);
JPanel nameInnerPanel2 = new JPanel(new BorderLayout());
JPanel ownerTextPanel = new JPanel();
ownerTextPanel.setLayout(new BoxLayout(ownerTextPanel, BoxLayout.Y_AXIS));
JTextArea ownerText = new JTextArea(property.getParent().getFullName(), 2, 25);
ownerText.setFont(new Font("SansSerif", Font.PLAIN, 11));
ownerText.setForeground(Color.black);
ownerText.setBackground(this.getBackground());
ownerText.setLineWrap(true);
ownerText.setWrapStyleWord(true);
ownerText.setEditable(false);
ownerText.setBorder(BorderFactory.createEmptyBorder());
JScrollPane ownerScroll = new JScrollPane(ownerText, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
ownerScroll.setBorder(BorderFactory.createEmptyBorder());
ownerTextPanel.add(ownerScroll);
ownerTextPanel.add(Box.createGlue());
JPanel ownerLabelPanel = new JPanel();
ownerLabelPanel.setLayout(new BoxLayout(ownerLabelPanel, BoxLayout.Y_AXIS));
JLabel ownerLabel = new JLabel("Owner: ");
ownerLabelPanel.add(ownerLabel);
ownerLabelPanel.add(Box.createGlue());
nameInnerPanel2.add(ownerLabelPanel, BorderLayout.WEST);
nameInnerPanel2.add(ownerTextPanel, BorderLayout.CENTER);
nameInnerPanel2.setAlignmentY(0.0f);
nameCompoundPanel.add(nameInnerPanel1);
nameCompoundPanel.add(nameInnerPanel2);
namePanel.add(Box.createHorizontalStrut(3), BorderLayout.EAST);
namePanel.add(Box.createHorizontalStrut(3), BorderLayout.WEST);
namePanel.add(nameCompoundPanel, BorderLayout.CENTER);
JPanel descriptionPanel = new JPanel(new BorderLayout());
JPanel descriptionTextPanel = new JPanel();
descriptionTextPanel.setLayout(new BoxLayout(descriptionTextPanel, BoxLayout.Y_AXIS));
JTextArea descriptionText = new JTextArea(description, 3, 40);
descriptionText.setFont(new Font("SansSerif", Font.PLAIN, 11));
descriptionText.setForeground(Color.black);
descriptionText.setBackground(this.getBackground());
descriptionText.setLineWrap(true);
descriptionText.setWrapStyleWord(true);
descriptionText.setEditable(false);
descriptionText.setBorder(BorderFactory.createEmptyBorder());
JScrollPane descriptionScroll = new JScrollPane(descriptionText, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
descriptionScroll.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Description:"));
descriptionScroll.setAlignmentY(1.0f);
descriptionTextPanel.add(descriptionScroll);
descriptionTextPanel.add(Box.createGlue());
JPanel descriptionLabelPanel = new JPanel();
descriptionLabelPanel.setLayout(new BoxLayout(descriptionLabelPanel, BoxLayout.Y_AXIS));
JLabel descriptionLabel = new JLabel("Description: ");
descriptionLabelPanel.add(descriptionLabel);
descriptionLabelPanel.add(Box.createGlue());
descriptionPanel.add(descriptionTextPanel, BorderLayout.CENTER);
JPanel inputBorderPanel = new JPanel(new BorderLayout());
inputBorderPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Value:"));
inputBorderPanel.add(inputPanel, BorderLayout.CENTER);
propertyInnerPanel.add(namePanel);
propertyInnerPanel.add(inputBorderPanel);
propertyInnerPanel.add(descriptionPanel);
propertyPanel.add(Box.createVerticalStrut(5), BorderLayout.NORTH);
propertyPanel.add(Box.createHorizontalStrut(5), BorderLayout.EAST);
propertyPanel.add(Box.createHorizontalStrut(5), BorderLayout.WEST);
propertyPanel.add(Box.createVerticalStrut(5), BorderLayout.SOUTH);
propertyPanel.add(propertyInnerPanel, BorderLayout.CENTER);
JPanel propertyPanel2 = new JPanel(new BorderLayout());
propertyPanel2.add(Box.createVerticalStrut(5), BorderLayout.NORTH);
propertyPanel2.add(Box.createHorizontalStrut(5), BorderLayout.EAST);
propertyPanel2.add(Box.createHorizontalStrut(5), BorderLayout.WEST);
propertyPanel2.add(Box.createVerticalStrut(5), BorderLayout.SOUTH);
propertyPanel2.add(propertyPanel, BorderLayout.CENTER);
JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
southPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
if(property.isModifiable())
{
ok = new JButton(" Ok ");
ok.addActionListener(this);
southPanel.add(ok);
cancel = new JButton("Cancel");
cancel.addActionListener(this);
southPanel.add(cancel);
}
else
{
ok = new JButton("Done");
ok.addActionListener(this);
southPanel.add(ok);
}
mainPanel.add(propertyPanel2, BorderLayout.CENTER);
mainPanel.add(southPanel, BorderLayout.SOUTH);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setResizable(false);
pack();
}
/**
* Action event handler method.
*/
public void actionPerformed(final ActionEvent event)
{
if(event.getSource() == ok)
{
doOk();
}
else if(event.getSource() == cancel)
{
dispose();
}
}
/**
* Perform ok button click logic.
*/
void doOk()
{
try
{
if(property.isModifiable())
property.setPropertyValue(inputPanel.getValue());
dispose();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, "Unable to set property (" + e + ")", "Error", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
/*#################################################################
######################### INPUT PANEL CLASSES #########################
#################################################################*/
/**
* Abstract base class for the classes implementing input/view GUI for different types of properties.
*/
private static abstract class InputPanel extends JPanel
{
private final Insets panelInsets = new Insets(5, 5, 5, 5);
protected PropertyDialog propertyDialog;
/**
* Creates a new InputPanel.
*/
public InputPanel(final PropertyDialog propertyDialog)
{
this.propertyDialog = propertyDialog;
}
/**
* Gets the insets of the panel.
*/
public final Insets getInsets()
{
return panelInsets;
}
/**
* Gets the new value.
*/
public abstract String getValue();
}
/*#################################################################
###################### MULTI VALUE INPUT PANEL CLASS #####################
#################################################################*/
/**
* Class implementing a multi value input panel (for MultiValueProperty objects).
*/
private static class MultiValueInputPanel extends InputPanel implements ActionListener //implements MouseListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
private static final int TABLE_WIDTH = 150;
private JTable table;
JScrollPane scrollPane;
private MultiValueTableModel model;
private String delims;
private JButton addButton;
private JButton deleteButton;
private JTextField newValueField;
/**
* Creates a new MultiValueInputPanel.
*/
public MultiValueInputPanel(final PropertyDialog propertyDialog, final PropertyProxy property, final String delims)
{
super(propertyDialog);
this.setLayout(new BorderLayout());
this.delims = delims;
final ArrayList values = new ArrayList();
// Values...
final StringTokenizer tokenizer = new StringTokenizer(property.getValueAsString(), delims);
try
{
while(tokenizer.hasMoreTokens())
{
values.add(tokenizer.nextToken());
}
}
catch(Exception e)
{
e.printStackTrace();
}
//Font plainFont = new Font("SansSerif", Font.PLAIN, 10);
// Panel
JPanel mainPanel = new JPanel(new BorderLayout(5,5));
model = new MultiValueTableModel(values, this);
table = new JTable(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
table.getTableHeader().setReorderingAllowed(false);
MultiValueCellRenderer cell0Renderer = new MultiValueCellRenderer();
table.setDefaultRenderer(table.getColumnClass(0), cell0Renderer);
scrollPane = new JScrollPane(table);
table.setPreferredScrollableViewportSize(new Dimension(TABLE_WIDTH, 50));
initColumnSizes();
JPanel newValuePanel = new JPanel(new BorderLayout());
newValuePanel.setBorder(BorderFactory.createEtchedBorder());
JLabel newValueLabel = new JLabel(" New value: ");
newValueLabel.setFont(new Font("SansSerif", Font.PLAIN, 12));
newValueLabel.setForeground(Color.black);
newValueField = new JTextField(20);
newValuePanel.add(BorderLayout.WEST, newValueLabel);
newValuePanel.add(BorderLayout.CENTER, newValueField);
mainPanel.add(BorderLayout.CENTER, scrollPane);
mainPanel.add(BorderLayout.SOUTH, newValuePanel);
JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
addButton = new JButton(" Add ");
//addButton.setFont(plainFont);
addButton.addActionListener(this);
deleteButton = new JButton("Delete");
//deleteButton.setFont(plainFont);
deleteButton.addActionListener(this);
southPanel.add(addButton);
southPanel.add(Box.createHorizontalStrut(20));
southPanel.add(deleteButton);
add(BorderLayout.CENTER, mainPanel);
add(BorderLayout.SOUTH, southPanel);
}
/**
* Gets the delimeter separated multivalue
*/
public String getValue()
{
java.util.List data = model.getValues();
StringBuffer valueString = new StringBuffer();
for(int i=0; i<data.size(); i++)
{
try
{
table.getCellEditor(i, 1).stopCellEditing(); // Stop cell editing in case the user edited a cell and didn't press return to stop editing...
}
catch(Exception e){}
valueString.append(data.get(i));
if(i < (data.size() - 1)) // If not last
valueString.append(delims.charAt(0)); //Add first delim char
}
return valueString.toString();
}
/**
* Initializes the coulmn sizes used in the table on this panel.
*/
private void initColumnSizes()
{
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
column = table.getColumnModel().getColumn(0);
comp = new JLabel(MultiValueTableModel.columnNames[0]);
headerWidth = comp.getPreferredSize().width;
comp = table.getDefaultRenderer(model.getColumnClass(0)).getTableCellRendererComponent(table, new Integer(12345), false, false, 0, 0);
cellWidth = comp.getPreferredSize().width;
int colum1Width = Math.max(headerWidth, cellWidth);
column.setPreferredWidth((int)(colum1Width * 1.5));
column.setMaxWidth((int)(colum1Width * 2));
}
/**
* Scrolls to the bottom of the table.
*/
public void scrollToBottom()
{
Runnable r = new Runnable()
{
public void run()
{
scrollPane.getVerticalScrollBar().setValue(scrollPane.getVerticalScrollBar().getMaximum());
}
};
SwingUtilities.invokeLater(r);
}
/**
* Action event handler method.
*/
public void actionPerformed(final ActionEvent event)
{
if(event.getSource() == addButton)
{
String newVal = this.newValueField.getText();
if( (newVal != null) && !newVal.equalsIgnoreCase("") )
{
this.model.add(newVal);
}
}
else if(event.getSource() == deleteButton)
{
int[] selectedRows = table.getSelectedRows();
this.model.remove(selectedRows);
}
}
/**
* The table model implementation.
*/
private static final class MultiValueTableModel extends AbstractTableModel
{
/**
*
*/
private static final long serialVersionUID = 1L;
public static String[] columnNames = {"Index", "Value"};
private ArrayList data = null;
private MultiValueInputPanel inputPanel;
/**
* Creates a new MultiValueTableModel.
*/
public MultiValueTableModel(ArrayList data, MultiValueInputPanel inputPanel)
{
super();
this.data = data;
this.inputPanel = inputPanel;
}
/**
* Adds a new value to the model.
*/
public void add(final String value)
{
this.data.add(value);
super.fireTableDataChanged();
inputPanel.scrollToBottom();
}
/**
* Removes the values at the specified indices from the model.
*/
public void remove(final int[] indices)
{
ArrayList newData = (ArrayList)((ArrayList)data).clone();
for(int i=0; i<indices.length; i++)
{
if( indices[i] < data.size() )
newData.remove(data.get(indices[i]));
}
this.data = newData;
super.fireTableDataChanged();
}
/**
* Gets the values in the model.
*/
public java.util.List getValues()
{
return data;
}
/**
* Gets the column count.
*/
public int getColumnCount()
{
return columnNames.length;
}
/**
* Gets the row count.
*/
public int getRowCount()
{
if(data!=null) return data.size(); // + 1; // +1 for new input
else return 0;
}
/**
* Gets the name of the column at the specified index.
*/
public String getColumnName(final int index)
{
return columnNames[index];
}
/**
* Checks if the specified cell is editable.
*/
public boolean isCellEditable(int row, int col)
{
if(col == 0) return false;
else return true;
}
/**
* Gets the value for the specified cell.
*/
public Object getValueAt(int row, int col)
{
try
{
if(col == 0) return new Integer(row);
else if(row < data.size())
{
if(col == 1) return data.get(row);
else return null;
}
else return null;
}
catch(ArrayIndexOutOfBoundsException e)
{
return null;
}
}
/**
* Sets the value in the specified cell.
*/
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
{
if(columnIndex == 1)
{
if(rowIndex < data.size())
{
data.set(rowIndex, aValue);
super.fireTableDataChanged();
}
}
}
}
/**
* Table cell renderer class.
*/
private static final class MultiValueCellRenderer extends DefaultTableCellRenderer
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Creates a new MultiValueCellRenderer.
*/
public MultiValueCellRenderer()
{
super();
}
/**
* Gets the renderer component for the specified cell.
*/
public Component getTableCellRendererComponent(final JTable table, Object value, final boolean isSelected, boolean hasFocus, int row, int column)
{
if(column == 0)
{
JLabel label = new JLabel(value.toString());
label.setOpaque(true);
label.setBackground(Color.lightGray);
label.setForeground(Color.black);
label.setHorizontalAlignment(JLabel.CENTER);
return label;
}
else
{
return super.getTableCellRendererComponent(table, value, isSelected, false, row, column);
}
}
}
}
/*#################################################################
######################## CHOICE INPUT PANEL CLASS ######################
#################################################################*/
/**
* Input panel class for enum/multiple choice values.
*/
private static final class ChoiceInputPanel extends InputPanel
{
/**
*
*/
private static final long serialVersionUID = 1L;
private final JComboBox enums;
/**
* Creates a new ChoiceInputPanel.
*/
public ChoiceInputPanel(final PropertyDialog propertyDialog, final PropertyProxy property)
{
super(propertyDialog);
this.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 3));
Object[] enumObjects = property.getEnumerations();
if(enumObjects == null)
throw new RuntimeException("Unable to initialize EnumProperty - failed to get enumeration objects!");
int selIndex = -1;
String selString = property.getValueAsString();
for(int i=0; i<enumObjects.length; i++)
{
if(enumObjects[i].toString().equals(selString))
{
selIndex = i;
break;
}
}
if(selIndex < 0)
throw new RuntimeException("Unable to initialize EnumProperty - failed to get selected index!");
enums = new JComboBox(enumObjects);
enums.setMaximumRowCount(3);
enums.setSelectedIndex(selIndex);
add(enums);
}
/**
* Gets the new value.
*/
public String getValue()
{
return enums.getSelectedItem().toString();
}
}
/*#################################################################
######################## BOOLEAN INPUT PANEL CLASS ######################
#################################################################*/
/**
* Input panel class for input of boolean values.
*/
private static final class BooleanInputPanel extends InputPanel
{
/**
*
*/
private static final long serialVersionUID = 1L;
private final ButtonGroup bg;
private final JRadioButton trueButton;
private final JRadioButton falseButton;
/**
* Creates BooleanInputPanel.
*/
public BooleanInputPanel(final PropertyDialog propertyDialog, final PropertyProxy property)
{
super(propertyDialog);
this.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 3));
bg = new ButtonGroup();
boolean isTrue = false;
isTrue = property.getValueAsString().equalsIgnoreCase("true");
trueButton = new JRadioButton("true", isTrue);
falseButton = new JRadioButton("false", !isTrue);
trueButton.setFocusPainted(false);
falseButton.setFocusPainted(false);
bg.add(trueButton);
bg.add(falseButton);
add(trueButton);
add(falseButton);
}
/**
* Gets the new value.
*/
public String getValue()
{
if(trueButton.isSelected())
return "true";
else
return "false";
}
}
/*#################################################################
######################## STRING INPUT PANEL CLASS ######################
#################################################################*/
/**
* Input panel class for string values.
*/
private static final class StringInputPanel extends InputPanel implements KeyListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
private final JTextArea value;
public StringInputPanel(final PropertyDialog propertyDialog, final PropertyProxy property)
{
super(propertyDialog);
this.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 3));
value = new JTextArea(property.getValueAsString(), 1, 35);
value.setFont(new Font("SansSerif", Font.PLAIN, 11));
JScrollPane scroll = new JScrollPane(value, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
add(scroll);
this.addKeyListener(this);
value.addKeyListener(this);
scroll.addKeyListener(this);
}
/**
* Gets the new value.
*/
public String getValue()
{
return value.getText();
}
/**
* Key press event handling method.
*/
public void keyPressed(final KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_ENTER)
{
super.propertyDialog.doOk();
e.consume();
}
}
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
}
/*#################################################################
################# UNMODIFIABLE PROPERTY INPUT PANEL CLASS ##################
#################################################################*/
/**
* Input panel class for unmodifiable properties.
*/
private static final class UnmodifiablePropertyPanel extends InputPanel
{
/**
*
*/
private static final long serialVersionUID = 1L;
private final JTextArea value;
/**
* Creates a new UnmodifiablePropertyPanel.
*/
public UnmodifiablePropertyPanel(final PropertyDialog propertyDialog, final PropertyProxy property)
{
super(propertyDialog);
this.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 3));
value = new JTextArea(property.getValueAsString(), 1, 35);
value.setFont(new Font("SansSerif", Font.PLAIN, 11));
value.setEditable(false);
JScrollPane scroll = new JScrollPane(value, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
add(scroll);
}
/**
* Gets the new value.
*/
public String getValue()
{
return value.getText();
}
}
}
| apache-2.0 |
Malanius/Terasology | engine/src/main/java/org/terasology/world/block/BlockComponent.java | 3183 | /*
* Copyright 2013 MovingBlocks
*
* 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.terasology.world.block;
import org.terasology.entitySystem.Component;
import org.terasology.math.JomlUtil;
import org.terasology.math.geom.Vector3i;
import org.terasology.network.Replicate;
/**
* Used for entities representing a block in the world
*/
public final class BlockComponent implements Component {
@Replicate
public Vector3i position = new Vector3i();
@Replicate
public Block block;
public BlockComponent() {
}
/**
* @deprecated This is scheduled for removal in an upcoming version method will be replaced with JOML implementation
* {@link #BlockComponent(Block, org.joml.Vector3i)}.
*/
@Deprecated
public BlockComponent(Block block, Vector3i pos) {
this.block = block;
this.position.set(pos);
}
public BlockComponent(Block block, org.joml.Vector3i pos) {
this.block = block;
this.position.set(JomlUtil.from(pos));
}
/**
* @deprecated Deprecated on 21/Sep/2018, because it is error prone (no defensive copy) and needlessly verbose.
* @deprecated This is scheduled for removal in an upcoming version method will be replaced with JOML implementation
* {@link #getPosition(org.joml.Vector3i)}.
*/
@Deprecated
public Vector3i getPosition() {
return position;
}
/**
* @deprecated Deprecated on 21/Sep/2018, because it is needlessly verbose.
* @deprecated This is scheduled for removal in an upcoming version method will be replaced with JOML implementation
* {@link #setPosition(org.joml.Vector3i)}.
*/
@Deprecated
public void setPosition(Vector3i pos) {
position.set(pos);
}
/**
* @deprecated Deprecated on 21/Sep/2018, because it is error prone (no defensive copy) and needlessly verbose.
*/
@Deprecated
public void setBlock(Block block) {
this.block = block;
}
/**
* @deprecated Deprecated on 21/Sep/2018, because it is error prone (no defensive copy) and needlessly verbose.
*/
@Deprecated
public Block getBlock() {
return block;
}
/**
* get the position
*
* @param dest will hold the result
* @return dest
*/
public org.joml.Vector3i getPosition(org.joml.Vector3i dest) {
dest.set(JomlUtil.from(position));
return dest;
}
/**
* set the position of the {@link BlockComponent}
*
* @param pos position to set
*/
public void setPosition(org.joml.Vector3i pos) {
position.set(JomlUtil.from(pos));
}
}
| apache-2.0 |
chaordic/cassandra | src/java/org/apache/cassandra/db/marshal/AbstractType.java | 12069 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.db.marshal;
import java.io.DataInput;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import org.apache.cassandra.cql3.CQL3Type;
import org.apache.cassandra.cql3.Term;
import org.apache.cassandra.db.TypeSizes;
import org.apache.cassandra.exceptions.SyntaxException;
import org.apache.cassandra.serializers.TypeSerializer;
import org.apache.cassandra.serializers.MarshalException;
import org.github.jamm.Unmetered;
import org.apache.cassandra.io.util.DataOutputPlus;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.utils.ByteBufferUtil;
/**
* Specifies a Comparator for a specific type of ByteBuffer.
*
* Note that empty ByteBuffer are used to represent "start at the beginning"
* or "stop at the end" arguments to get_slice, so the Comparator
* should always handle those values even if they normally do not
* represent a valid ByteBuffer for the type being compared.
*/
@Unmetered
public abstract class AbstractType<T> implements Comparator<ByteBuffer>
{
public final Comparator<ByteBuffer> reverseComparator;
protected AbstractType()
{
reverseComparator = new Comparator<ByteBuffer>()
{
public int compare(ByteBuffer o1, ByteBuffer o2)
{
if (o1.remaining() == 0)
{
return o2.remaining() == 0 ? 0 : -1;
}
if (o2.remaining() == 0)
{
return 1;
}
return AbstractType.this.compare(o2, o1);
}
};
}
public static List<String> asCQLTypeStringList(List<AbstractType<?>> abstractTypes)
{
List<String> r = new ArrayList<>(abstractTypes.size());
for (AbstractType<?> abstractType : abstractTypes)
r.add(abstractType.asCQL3Type().toString());
return r;
}
public T compose(ByteBuffer bytes)
{
return getSerializer().deserialize(bytes);
}
public ByteBuffer decompose(T value)
{
return getSerializer().serialize(value);
}
/** get a string representation of the bytes suitable for log messages */
public String getString(ByteBuffer bytes)
{
if (bytes == null)
return "null";
TypeSerializer<T> serializer = getSerializer();
serializer.validate(bytes);
return serializer.toString(serializer.deserialize(bytes));
}
/** get a byte representation of the given string. */
public abstract ByteBuffer fromString(String source) throws MarshalException;
/** Given a parsed JSON string, return a byte representation of the object.
* @param parsed the result of parsing a json string
**/
public abstract Term fromJSONObject(Object parsed) throws MarshalException;
/** Converts a value to a JSON string. */
public String toJSONString(ByteBuffer buffer, int protocolVersion)
{
return '"' + getSerializer().deserialize(buffer).toString() + '"';
}
/* validate that the byte array is a valid sequence for the type we are supposed to be comparing */
public void validate(ByteBuffer bytes) throws MarshalException
{
getSerializer().validate(bytes);
}
/**
* Validate cell value. Unlike {@linkplain #validate(java.nio.ByteBuffer)},
* cell value is passed to validate its content.
* Usually, this is the same as validate except collection.
*
* @param cellValue ByteBuffer representing cell value
* @throws MarshalException
*/
public void validateCellValue(ByteBuffer cellValue) throws MarshalException
{
validate(cellValue);
}
/* Most of our internal type should override that. */
public CQL3Type asCQL3Type()
{
return new CQL3Type.Custom(this);
}
/**
* Same as compare except that this ignore ReversedType. This is to be use when
* comparing 2 values to decide for a CQL condition (see Operator.isSatisfiedBy) as
* for CQL, ReversedType is simply an "hint" to the storage engine but it does not
* change the meaning of queries per-se.
*/
public int compareForCQL(ByteBuffer v1, ByteBuffer v2)
{
return compare(v1, v2);
}
public abstract TypeSerializer<T> getSerializer();
/* convenience method */
public String getString(Collection<ByteBuffer> names)
{
StringBuilder builder = new StringBuilder();
for (ByteBuffer name : names)
{
builder.append(getString(name)).append(",");
}
return builder.toString();
}
public boolean isCounter()
{
return false;
}
public boolean isFrozenCollection()
{
return isCollection() && !isMultiCell();
}
public static AbstractType<?> parseDefaultParameters(AbstractType<?> baseType, TypeParser parser) throws SyntaxException
{
Map<String, String> parameters = parser.getKeyValueParameters();
String reversed = parameters.get("reversed");
if (reversed != null && (reversed.isEmpty() || reversed.equals("true")))
{
return ReversedType.getInstance(baseType);
}
else
{
return baseType;
}
}
/**
* Returns true if this comparator is compatible with the provided
* previous comparator, that is if previous can safely be replaced by this.
* A comparator cn should be compatible with a previous one cp if forall columns c1 and c2,
* if cn.validate(c1) and cn.validate(c2) and cn.compare(c1, c2) == v,
* then cp.validate(c1) and cp.validate(c2) and cp.compare(c1, c2) == v.
*
* Note that a type should be compatible with at least itself and when in
* doubt, keep the default behavior of not being compatible with any other comparator!
*/
public boolean isCompatibleWith(AbstractType<?> previous)
{
return this.equals(previous);
}
/**
* Returns true if values of the other AbstractType can be read and "reasonably" interpreted by the this
* AbstractType. Note that this is a weaker version of isCompatibleWith, as it does not require that both type
* compare values the same way.
*
* The restriction on the other type being "reasonably" interpreted is to prevent, for example, IntegerType from
* being compatible with all other types. Even though any byte string is a valid IntegerType value, it doesn't
* necessarily make sense to interpret a UUID or a UTF8 string as an integer.
*
* Note that a type should be compatible with at least itself.
*/
public boolean isValueCompatibleWith(AbstractType<?> otherType)
{
return isValueCompatibleWithInternal((otherType instanceof ReversedType) ? ((ReversedType) otherType).baseType : otherType);
}
/**
* Needed to handle ReversedType in value-compatibility checks. Subclasses should implement this instead of
* isValueCompatibleWith().
*/
protected boolean isValueCompatibleWithInternal(AbstractType<?> otherType)
{
return isCompatibleWith(otherType);
}
/**
* @return true IFF the byte representation of this type can be compared unsigned
* and always return the same result as calling this object's compare or compareCollectionMembers methods
*/
public boolean isByteOrderComparable()
{
return false;
}
/**
* An alternative comparison function used by CollectionsType in conjunction with CompositeType.
*
* This comparator is only called to compare components of a CompositeType. It gets the value of the
* previous component as argument (or null if it's the first component of the composite).
*
* Unless you're doing something very similar to CollectionsType, you shouldn't override this.
*/
public int compareCollectionMembers(ByteBuffer v1, ByteBuffer v2, ByteBuffer collectionName)
{
return compare(v1, v2);
}
/**
* An alternative validation function used by CollectionsType in conjunction with CompositeType.
*
* This is similar to the compare function above.
*/
public void validateCollectionMember(ByteBuffer bytes, ByteBuffer collectionName) throws MarshalException
{
validate(bytes);
}
public boolean isCollection()
{
return false;
}
public boolean isMultiCell()
{
return false;
}
public AbstractType<?> freeze()
{
return this;
}
/**
* Returns {@code true} for types where empty should be handled like {@code null} like {@link Int32Type}.
*/
public boolean isEmptyValueMeaningless()
{
return false;
}
/**
* @param ignoreFreezing if true, the type string will not be wrapped with FrozenType(...), even if this type is frozen.
*/
public String toString(boolean ignoreFreezing)
{
return this.toString();
}
/**
* The number of subcomponents this type has.
* This is always 1, i.e. the type has only itself as "subcomponents", except for CompositeType.
*/
public int componentsCount()
{
return 1;
}
/**
* Return a list of the "subcomponents" this type has.
* This always return a singleton list with the type itself except for CompositeType.
*/
public List<AbstractType<?>> getComponents()
{
return Collections.<AbstractType<?>>singletonList(this);
}
/**
* The length of values for this type if all values are of fixed length, -1 otherwise.
*/
protected int valueLengthIfFixed()
{
return -1;
}
// This assumes that no empty values are passed
public void writeValue(ByteBuffer value, DataOutputPlus out) throws IOException
{
assert value.hasRemaining();
if (valueLengthIfFixed() >= 0)
out.write(value);
else
ByteBufferUtil.writeWithLength(value, out);
}
public long writtenLength(ByteBuffer value)
{
assert value.hasRemaining();
return valueLengthIfFixed() >= 0
? value.remaining()
: TypeSizes.sizeofWithLength(value);
}
public ByteBuffer readValue(DataInput in) throws IOException
{
int length = valueLengthIfFixed();
if (length >= 0)
return ByteBufferUtil.read(in, length);
else
return ByteBufferUtil.readWithLength(in);
}
public void skipValue(DataInput in) throws IOException
{
int length = valueLengthIfFixed();
if (length < 0)
length = in.readInt();
FileUtils.skipBytesFully(in, length);
}
/**
* This must be overriden by subclasses if necessary so that for any
* AbstractType, this == TypeParser.parse(toString()).
*
* Note that for backwards compatibility this includes the full classname.
* For CQL purposes the short name is fine.
*/
@Override
public String toString()
{
return getClass().getName();
}
}
| apache-2.0 |
ArpNetworking/commons | src/test/java/com/arpnetworking/commons/builder/processorbuilder/ImmediateBuilder.java | 1196 | /*
* Copyright 2022 Inscope Metrics
*
* 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.arpnetworking.commons.builder.processorbuilder;
import com.arpnetworking.commons.builder.OvalBuilder;
import java.util.function.Function;
/**
* Test class for bean validators.
*
* @param <T> builder type
*
* @author Brandon Arp (brandon dot arp at inscopemetrics dot io)
*/
public abstract class ImmediateBuilder<T> extends OvalBuilder<T> {
/**
* Constructor.
*
* @param targetConstructor the constructor
*/
protected ImmediateBuilder(final Function<? extends ImmediateBuilder<T>, T> targetConstructor) {
super(targetConstructor);
}
}
| apache-2.0 |
NationalSecurityAgency/ghidra | Ghidra/Features/Base/src/test/java/ghidra/app/util/cparser/PreProcessorTest.java | 4802 | /* ###
* IP: GHIDRA
*
* 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 ghidra.app.util.cparser;
import static org.junit.Assert.*;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import org.junit.Test;
import generic.test.AbstractGenericTest;
import ghidra.app.util.cparser.CPP.PreProcessor;
import ghidra.program.model.data.*;
import ghidra.program.model.data.Enum;
public class PreProcessorTest extends AbstractGenericTest {
public PreProcessorTest() {
super();
}
@Test
public void testHeaderParsing() throws Exception {
PreProcessor parser = new PreProcessor();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
parser.setOutputStream(baos);
//// String[] args = new String[] {"-I/local/VisualStudio/Windows/v7.0a/Include", "-I/local/VisualStudio/VS12/include", "-D_WIN32", "-D_CRT_SECURE_NO_WARNINGS"};
// String[] args = new String[] {"-I/local/Mac/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/usr/include",
// "-I/local/Mac/MacOSX.platform/Developer/SDKs/MacOSX10.10.sdk/System/Library/Frameworks/Kernel.framework/Versions/A/Headers/",
// "-D_LARGEFILE64_SOURCE=0","-D__GNUCC__=4.1","-D_DARWIN_C_SOURCE","-DBSD","-D__APPLE__","-D__x86_64__=1"};
// parser.setArgs(args);
// String fullName;
// fullName = "mach/memory_object_types.h";
// parser.parse(fullName);
// fullName = "ctype.h";
// parser.parse(fullName);
//// fullName = "adoguids.h";
//// parser.parse(fullName);
String resourceName = "PreProcessorTest.h";
URL url = PreProcessorTest.class.getResource(resourceName);
parser.parse(url.getFile());
// Uncomment to print out parse results
System.err.println(baos.toString());
String results = baos.toString("ASCII");
int end = results.lastIndexOf(";") + 1;
String endStr = results.substring(end - 9, end);
assertEquals("theEnd();", endStr);
assertTrue("macro expansion _fpl(bob) failed ", results
.indexOf("extern int __declspec(\"fp(\\\"l\\\", \" #bob \")\") __ifplbob;") != -1);
StandAloneDataTypeManager dtMgr = new StandAloneDataTypeManager("parsed");
parser.getDefinitions().populateDefineEquates(dtMgr);
CategoryPath path = new CategoryPath("/PreProcessorTest.h");
path = new CategoryPath(path, "defines");
long value = 32516;
String defname = "DefVal1";
checkDefine(dtMgr, path, value, defname);
value = 0x06010000 + 0xf1;
defname = "DefVal2";
checkDefine(dtMgr, path, value, defname);
value = 0x60010001 & 0x21234 | 1;
defname = "DefVal3";
checkDefine(dtMgr, path, value, defname);
value = 0x1 << (1 + 2 | 4);
defname = "DefVal4";
checkDefine(dtMgr, path, value, defname);
value = (0xFF000000L & (~(0x01000000L | 0x02000000L | 0x04000000L)));
defname = "DefVal5";
checkDefine(dtMgr, path, value, defname);
value = ((0x000F0000L) | (0x00100000L) | 0x3);
defname = "DefVal6";
checkDefine(dtMgr, path, value, defname);
value = 0x40000000L;
defname = "DefVal7";
checkDefine(dtMgr, path, value, defname);
value = ((3 << 13) | (3 << 9) | 4);
defname = "DefVal8";
checkDefine(dtMgr, path, value, defname);
value = ((0x7fff & ~(((1 << 4) - 1))));
defname = "DefVal9";
checkDefine(dtMgr, path, value, defname);
value = ((0x7fff) * 900L / 1000);
defname = "DefVal10";
checkDefine(dtMgr, path, value, defname);
value = 0;
defname = "TOO_MANY_FISH";
checkDefine(dtMgr, path, value, defname);
value = 0x53977;
defname = "ImOctal";
checkDefine(dtMgr, path, value, defname);
defname = "TEST_FAILED";
checkNotDefine(dtMgr, path, defname);
defname = "isDefineOnValue";
value = 1;
checkDefine(dtMgr, path, value, defname);
defname = "BIGNUM";
value = 64 * 16 + 16;
checkDefine(dtMgr, path, value, defname);
}
private void checkDefine(StandAloneDataTypeManager dtMgr, CategoryPath path, long value,
String defname) {
DataType dataType = dtMgr.getDataType(path, "define_" + defname);
String msg = "Define Enum " + defname;
assertNotNull(msg, dataType);
assertTrue(msg, dataType instanceof Enum);
assertEquals(msg, value, ((Enum) dataType).getValue(defname));
}
private void checkNotDefine(StandAloneDataTypeManager dtMgr, CategoryPath path,
String defname) {
DataType dataType = dtMgr.getDataType(path, "define_" + defname);
assertNull(dataType);
}
}
| apache-2.0 |
Ariah-Group/Finance | af_webapp/src/main/java/org/kuali/kfs/module/purap/document/validation/event/AttributedAssignSensitiveDataEvent.java | 2423 | /*
* Copyright 2008-2009 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.kfs.module.purap.document.validation.event;
import java.util.List;
import org.kuali.kfs.module.purap.businessobject.SensitiveData;
import org.kuali.kfs.sys.document.validation.event.AttributedDocumentEventBase;
import org.kuali.rice.krad.document.Document;
public final class AttributedAssignSensitiveDataEvent extends AttributedDocumentEventBase {
private String sensitiveDataAssignmentReason;
private List<SensitiveData> sensitiveDatasAssigned;
/**
* Constructs an AssignSensitiveDataEvent with the given errorPathPrefix, document, and sensitive data list.
*
* @param errorPathPrefix the error path
* @param document document the event was invoked on
* @param sensitiveDatasAssigned the sensitive data list to be checked for assignment
*/
public AttributedAssignSensitiveDataEvent(String errorPathPrefix, Document document, String sensitiveDataAssignmentReason, List<SensitiveData> sensitiveDatasAssigned) {
super("Assign sensitive data to purchase order " + getDocumentId(document), errorPathPrefix, document);
this.sensitiveDataAssignmentReason = sensitiveDataAssignmentReason;
this.sensitiveDatasAssigned = sensitiveDatasAssigned;
}
public String getSensitiveDataAssignmentReason() {
return sensitiveDataAssignmentReason;
}
public void setSensitiveDataAssignmentReason(String sensitiveDataAssignmentReason) {
this.sensitiveDataAssignmentReason = sensitiveDataAssignmentReason;
}
public List<SensitiveData> getSensitiveDatasAssigned() {
return sensitiveDatasAssigned;
}
public void setSensitiveDatasAssigned(List<SensitiveData> sensitiveDatasAssigned) {
this.sensitiveDatasAssigned = sensitiveDatasAssigned;
}
}
| apache-2.0 |
oehf/ipf | commons/ihe/hl7v2/src/main/java/org/openehealth/ipf/commons/ihe/hl7v2/definitions/pam/v25/message/ADT_A54.java | 1919 | /*
* Copyright 2015 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.openehealth.ipf.commons.ihe.hl7v2.definitions.pam.v25.message;
import ca.uhn.hl7v2.model.Structure;
import ca.uhn.hl7v2.model.v25.segment.*;
import ca.uhn.hl7v2.parser.DefaultModelClassFactory;
import ca.uhn.hl7v2.parser.ModelClassFactory;
import org.openehealth.ipf.commons.ihe.hl7v2.definitions.pam.v25.segment.ZBE;
import org.openehealth.ipf.modules.hl7.model.AbstractMessage;
import java.util.Map;
/**
*
*/
public class ADT_A54 extends AbstractMessage {
public ADT_A54() {
this(new DefaultModelClassFactory());
}
public ADT_A54(ModelClassFactory factory) {
super(factory);
}
@Override
protected Map<Class<? extends Structure>, Cardinality> structures(Map<Class<? extends Structure>, Cardinality> s) {
s.put(MSH.class, Cardinality.REQUIRED);
s.put(SFT.class, Cardinality.OPTIONAL_REPEATING);
s.put(EVN.class, Cardinality.REQUIRED);
s.put(PID.class, Cardinality.REQUIRED);
s.put(PD1.class, Cardinality.OPTIONAL);
s.put(ROL.class, Cardinality.OPTIONAL_REPEATING);
s.put(PV1.class, Cardinality.REQUIRED);
s.put(PV2.class, Cardinality.OPTIONAL);
s.put(ZBE.class, Cardinality.OPTIONAL);
s.put(ROL.class, Cardinality.OPTIONAL_REPEATING);
return s;
}
}
| apache-2.0 |
fairytale110/FTMostBeautifyThing | deckview/src/main/java/com/appeaser/deckview/utilities/DVConstants.java | 2793 | package com.appeaser.deckview.utilities;
/**
* Created by Vikram on 02/04/2015.
*/
public class DVConstants {
public static class DebugFlags {
// Enable this with any other debug flag to see more info
public static final boolean Verbose = false;
public static class App {
// Enables debug drawing for the transition thumbnail
public static final boolean EnableTransitionThumbnailDebugMode = false;
// Enables the filtering of tasks according to their grouping
public static final boolean EnableTaskFiltering = false;
// Enables clipping of tasks against each other
public static final boolean EnableTaskStackClipping = true;
// Enables tapping on the TaskBar to launch the task
public static final boolean EnableTaskBarTouchEvents = true;
// Enables app-info pane on long-pressing the icon
public static final boolean EnableDevAppInfoOnLongPress = true;
// Enables debug mode
public static final boolean EnableDebugMode = false;
// Enables the search bar layout
public static final boolean EnableSearchLayout = true;
// Enables the thumbnail alpha on the front-most task
public static final boolean EnableThumbnailAlphaOnFrontmost = false;
// This disables the bitmap and icon caches
public static final boolean DisableBackgroundCache = false;
// Enables the simulated task affiliations
public static final boolean EnableSimulatedTaskGroups = false;
// Defines the number of mock task affiliations per group
public static final int TaskAffiliationsGroupCount = 12;
// Enables us to create mock recents tasks
public static final boolean EnableSystemServicesProxy = false;
// Defines the number of mock recents packages to create
public static final int SystemServicesProxyMockPackageCount = 3;
// Defines the number of mock recents tasks to create
public static final int SystemServicesProxyMockTaskCount = 100;
}
}
public static class Values {
public static class App {
public static int AppWidgetHostId = 1024;
public static String Key_SearchAppWidgetId = "searchAppWidgetId";
public static String Key_DebugModeEnabled = "debugModeEnabled";
public static String DebugModeVersion = "A";
}
public static class DView {
public static final int TaskStackMinOverscrollRange = 32;
public static final int TaskStackMaxOverscrollRange = 128;
public static final int FilterStartDelay = 25;
}
}
}
| apache-2.0 |
cncduLee/bbks-crawer | integration/com/bimoku/integrate/Integrated.java | 8760 | package com.bimoku.integrate;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jettison.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import com.bimoku.common.bean.Book;
import com.bimoku.common.bean.BookDB;
import com.bimoku.common.bean.BookDD;
import com.bimoku.common.bean.BookDetail;
import com.bimoku.common.bean.RealTimeType;
import com.bimoku.util.AllPriceMapper;
import com.bimoku.util.RelationMapper;
import com.bimoku.repository.dao.BookDao;
import com.bimoku.util.filter.FieldFilter;
/**
* @Intro 系统集成模块
* @author LPM
* @date 2013-8-20
*
* 目标:抽取数据插入数据库时,执行此操作!!
* 1、明细库数据插入操作
* 2、根据当前的书籍的isbn,在基本表里面查找是否存在,如果不存在则插入一则数据(基本数据)
* 3、如果存在这条数据的基本数据,则跟新RELATIONSHIP字段
*
*/
public abstract class Integrated {
@Autowired
private BookDao bookDao;
@Autowired
private FieldFilter filter;
/**
* @param detail
*/
public void integrated(BookDetail detail) {
if(detail.getIsbn() == null || "".equals(detail.getIsbn())) return;
BookDetail det = putDataIntoDetail(detail);
if(det == null) return;//当前程序终止!!!
Book book = new Book();
if(det.getIsbn() == null || det.getIsbn().equals("")) return;//终止集成库操作
book.setIsbn(det.getIsbn());
if (!bookDao.isExit(book.getIsbn())) {
try {
book = BookDetail.convert2Book(det);
} catch (JSONException e) {
e.printStackTrace();
}
//给集成数据枷锁
book= Book.lockBook(book, det);
//不存在
bookDao.save(book);
} else {
try {
//先找到
Book bbk = bookDao.getBookByISBN(book.getIsbn());
//数据集成(对象关系映射、重复性校验、重复字段择优)
bbk = adapteData(bbk, det);
//给集成数据枷锁
bbk = Book.lockBook(bbk, det);
//存在,更新就好!!!!
bookDao.update(bbk);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 实时数据集成【包括明细数据管理】
* @param detail
* @param type
*/
public void realTimeIntegrated(BookDetail detail,RealTimeType type){
switch (type) {
case SEARCH_RANK:
detail.setIssearchrank(1);
break;
case NEWS_BOOK:
detail.setIsnewsrank(1);
break;
case PROMOTION_RANK:
detail.setIspromotionrank(1);
break;
case ONSALE_RANK:
detail.setIsonsalerank(1);
break;
default:
break;
}
//调用集成代码
integrated(detail);
}
/**
* 批量集成:
* 从明细表中去取出数据,做逐一的集成操作
* [1000]条一次
* @param details
* @throws Exception
*/
public void butchIntegrated(List<BookDetail> details) throws Exception{
List<Book> books = new ArrayList<Book>();
//2、遍历数据,并处理每一则数据集成
for(BookDetail detail : details){
books.add(integration(detail));
}
//批量插入到集成表
bookDao.batchSave(books);
}
/**
* 集成一则详细数据,返回集成结果
* @param detail
* @return
*/
public Book integration(BookDetail detail){
if(detail.getIsbn() == null || "".equals(detail.getIsbn())) return null;
BookDetail det = putDataIntoDetail(detail);
if(det == null) return null;//当前程序终止!!!
Book book = new Book();
if(det.getIsbn() == null || det.getIsbn().equals("")) return null;//终止集成库操作
book.setIsbn(det.getIsbn());
if (!bookDao.isExit(book.getIsbn())) {
try {
book = BookDetail.convert2Book(det);
} catch (JSONException e) {
e.printStackTrace();
}
//给集成数据枷锁
book= Book.lockBook(book, det);
return book;
} else {
try {
//先找到
Book bbk = bookDao.getBookByISBN(book.getIsbn());
//数据集成(对象关系映射、重复性校验、重复字段择优)
bbk = adapteData(bbk, det);
//给集成数据枷锁
bbk = Book.lockBook(bbk, det);
//存在,更新就好!!!!
return bbk;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
/**
* !!!!!!!!!!!!!!!!!
* 批量明细数据插入
* !!!!!!!!!!!!!!!!!
* @param details
* @return
*/
protected abstract int[] putDatasIntoDetail(List<BookDetail> details);
/**
* (对象关系映射、重复性校验、重复字段择优)
* 数据装载,目的是为了建立本表与明细表的关系
*
* 也就是book表的整合relationship这个字段!!!!!!,
* 存放的是isbn作为唯一的标识!!!!!会改成主键:id
*
* @param book
* @param detail
* @return
* @throws JSONException
*/
private Book adapteData(Book book,BookDetail detail) throws JSONException{
//***************************
// (对象关系映射)
//relationship字段构造!!!!!!
//***************************
String newRelation = RelationMapper.update(book, detail);
book.setRelationship(newRelation);
//***************************
// (价格更新)
//all_price字段构造!!!!!!
//***************************
String newPrice = AllPriceMapper.update(book, detail);
book.setAll_price(newPrice);
//*******************************************
//先处理空字段信息,如果某个字段是空,不论何种情况,允许修改
//*******************************************
book = fileBlank(book,detail);
//***************************
//(重复字段择优)
//使用其他算法进行字段选取1111
//数据编辑条件
//如果当前书籍已经枷锁,(说明已经被豆瓣操作过,)
//则主要更新关系和价格
//【但是,如果某些字段没有时,可以向没有的字段更新数据】
//***************************
if(!Book.isLock(book)){
book = filter(book,detail);
}
return book;
}
/**
* 1、填补book的空字段
* 2、调用子类的特殊处理
* @param book
* @param detail
* @return
*/
private Book fileBlank(Book book, BookDetail detail) {
if(book.getAuthor() == null || "".equals(book.getAuthor()))
book.setAuthor(detail.getAuthor());
if(book.getAuthorIntro() == null || "".equals(book.getAuthorIntro()))
book.setAuthorIntro(detail.getAuthorIntro());
if(book.getCatelog() == null || "".equals(book.getCatelog()))
book.setCatelog(detail.getCatelog());
if(book.getCover_pic() == null || "".equals(book.getCover_pic()))
book.setCover_pic(detail.getCover_pic());
if(book.getDirectory() == null || "".equals(book.getDirectory()))
book.setDirectory(detail.getDirectory());
if(book.getPress() == null || "".equals(book.getPress()))
book.setPress(detail.getPress());
if(book.getTranslator() == null || "".equals(book.getTranslator()))
book.setTranslator(detail.getTranslator());
if(book.getPrice() == null || book.getPrice() == 0)
book.setPrice(detail.getPrice());
return filterFileds(book,detail);
}
/**
* 优先处理字段
* @param book
* @param detail
* @return
*/
private Book filter(Book book,BookDetail detail){
// 首先做最长字符串匹配
book = baseInfoAdapte(book, detail);
//优先选择豆瓣的信息为准
if(detail instanceof BookDB){
//选取豆瓣的字段作为最优方案,bookName为基本字段,必须存在
if(detail.getBookName() != null)
book.setBookname(detail.getBookName());
if(detail.getOutLine() != null)
book.setOutline(detail.getOutLine());
if(detail.getCatelog() != null)
book.setCatelog(detail.getCatelog());
//TODO 待补冲....
}
if(detail instanceof BookDD){
//价格考虑以当当的价格作为官方价格
//TODO 暂定
if(detail.getPrice() != null && detail.getPrice() != 0)
book.setPrice(detail.getPrice());
}
return book;
}
/**
* 基础处理。主要处理的是,【书名,简介】
* @param book
* @param detail
* @return
*/
@SuppressWarnings("static-access")
protected Book baseInfoAdapte(Book book,BookDetail detail){
String[] names = {
book.getBookname(),
detail.getBookName()
};
book.setBookname(filter.longestMatch(names));//最长匹配处理bookname
String[] outline = {
book.getOutline(),
detail.getOutLine()
};
book.setOutline(filter.longestMatch(outline));//最长匹配处理outline
return book;
}
/**
* 明细数据插入
* @param detail
* @return
*/
protected abstract BookDetail putDataIntoDetail(BookDetail detail);
/**
* (重复字段择优)
* 只能更新book中没有的字段。
* @param book
* @return
*/
protected abstract Book filterFileds(Book book,BookDetail detail);
}
| apache-2.0 |
rolandomar/hermes | BFT-SMaRt_Hermes/src/bftsmart/tom/server/defaultservices/DefaultApplicationState.java | 9761 | package bftsmart.tom.server.defaultservices;
/**
* Copyright (c) 2007-2009 Alysson Bessani, Eduardo Alchieri, Paulo Sousa, and the authors indicated in the @author tags
*
* This file is part of SMaRt.
*
* SMaRt is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SMaRt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with SMaRt. If not, see <http://www.gnu.org/licenses/>.
*/
import java.util.Arrays;
import bftsmart.statemanagment.ApplicationState;
/**
* This classe represents a state tranfered from a replica to another. The state associated with the last
* checkpoint together with all the batches of messages received do far, comprises the sender's
* current state
*
* @author Jo�o Sousa
*/
public class DefaultApplicationState implements ApplicationState {
private static final long serialVersionUID = 6771081456095596363L;
protected byte[] state; // State associated with the last checkpoint
protected byte[] stateHash; // Hash of the state associated with the last checkpoint
protected int lastEid = -1; // Execution ID for the last messages batch delivered to the application
protected boolean hasState; // indicates if the replica really had the requested state
private CommandsInfo[] messageBatches; // batches received since the last checkpoint.
private int lastCheckpointEid; // Execution ID for the last checkpoint
private int lastCheckpointRound; // Round for the last checkpoint
private int lastCheckpointLeader; // Leader for the last checkpoint
/**
* Constructs a TansferableState
* This constructor should be used when there is a valid state to construct the object with
* @param messageBatches Batches received since the last checkpoint.
* @param state State associated with the last checkpoint
* @param stateHash Hash of the state associated with the last checkpoint
*/
public DefaultApplicationState(CommandsInfo[] messageBatches, int lastCheckpointEid, int lastCheckpointRound, int lastCheckpointLeader, int lastEid, byte[] state, byte[] stateHash) {
this.messageBatches = messageBatches; // batches received since the last checkpoint.
this.lastCheckpointEid = lastCheckpointEid; // Execution ID for the last checkpoint
this.lastCheckpointRound = lastCheckpointRound; // Round for the last checkpoint
this.lastCheckpointLeader = lastCheckpointLeader; // Leader for the last checkpoint
this.lastEid = lastEid; // Execution ID for the last messages batch delivered to the application
this.state = state; // State associated with the last checkpoint
this.stateHash = stateHash;
this.hasState = true;
}
/**
* Constructs a TansferableState
* This constructor should be used when there isn't a valid state to construct the object with
*/
public DefaultApplicationState() {
this.messageBatches = null; // batches received since the last checkpoint.
this.lastCheckpointEid = -1; // Execution ID for the last checkpoint
this.lastCheckpointRound = -1; // Round for the last checkpoint
this.lastCheckpointLeader = -1; // Leader for the last checkpoint
this.lastEid = -1;
this.state = null; // State associated with the last checkpoint
this.stateHash = null;
this.hasState = false;
}
public void setSerializedState(byte[] state) {
this.state = state;
}
public byte[] getSerializedState() {
return state;
}
/**
* Indicates if the TransferableState object has a valid state
* @return true if it has a valid state, false otherwise
*/
public boolean hasState() {
return hasState;
}
/**
* Retrieves the execution ID for the last messages batch delivered to the application
* @return Execution ID for the last messages batch delivered to the application
*/
public int getLastEid() {
return lastEid;
}
/**
* Retrieves the state associated with the last checkpoint
* @return State associated with the last checkpoint
*/
public byte[] getState() {
return state;
}
/**
* Retrieves the hash of the state associated with the last checkpoint
* @return Hash of the state associated with the last checkpoint
*/
public byte[] getStateHash() {
return stateHash;
}
/**
* Sets the state associated with the last checkpoint
* @param state State associated with the last checkpoint
*/
public void setState(byte[] state) {
this.state = state;
}
/**
* Retrieves all batches of messages
* @return Batch of messages
*/
public CommandsInfo[] getMessageBatches() {
return messageBatches;
}
/**
* Retrieves the specified batch of messages
* @param eid Execution ID associated with the batch to be fetched
* @return The batch of messages associated with the batch correspondent execution ID
*/
public CommandsInfo getMessageBatch(int eid) {
if (eid >= lastCheckpointEid && eid <= lastEid) {
return messageBatches[eid - lastCheckpointEid - 1];
}
else return null;
}
/**
* Retrieves the execution ID for the last checkpoint
* @return Execution ID for the last checkpoint, or -1 if no checkpoint was yet executed
*/
public int getLastCheckpointEid() {
return lastCheckpointEid;
}
/**
* Retrieves the decision round for the last checkpoint
* @return Decision round for the last checkpoint, or -1 if no checkpoint was yet executed
*/
public int getLastCheckpointRound() {
return lastCheckpointRound;
}
/**
* Retrieves the leader for the last checkpoint
* @return Leader for the last checkpoint, or -1 if no checkpoint was yet executed
*/
public int getLastCheckpointLeader() {
return lastCheckpointLeader;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof DefaultApplicationState) {
DefaultApplicationState tState = (DefaultApplicationState) obj;
if ((this.messageBatches != null && tState.messageBatches == null) ||
(this.messageBatches == null && tState.messageBatches != null)) {
//System.out.println("[DefaultApplicationState] returing FALSE1!");
return false;
}
if (this.messageBatches != null && tState.messageBatches != null) {
if (this.messageBatches.length != tState.messageBatches.length) {
//System.out.println("[DefaultApplicationState] returing FALSE2!");
return false;
}
for (int i = 0; i < this.messageBatches.length; i++) {
if (this.messageBatches[i] == null && tState.messageBatches[i] != null) {
//System.out.println("[DefaultApplicationState] returing FALSE3!");
return false;
}
if (this.messageBatches[i] != null && tState.messageBatches[i] == null) {
//System.out.println("[DefaultApplicationState] returing FALSE4!");
return false;
}
if (!(this.messageBatches[i] == null && tState.messageBatches[i] == null) &&
(!this.messageBatches[i].equals(tState.messageBatches[i]))) {
//System.out.println("[DefaultApplicationState] returing FALSE5!" + (this.messageBatches[i] == null) + " " + (tState.messageBatches[i] == null));
return false;
}
}
}
return (Arrays.equals(this.stateHash, tState.stateHash) &&
tState.lastCheckpointEid == this.lastCheckpointEid &&
tState.lastCheckpointRound == this.lastCheckpointRound &&
tState.lastCheckpointLeader == this.lastCheckpointLeader &&
tState.lastEid == this.lastEid && tState.hasState == this.hasState);
}
//System.out.println("[DefaultApplicationState] returing FALSE!");
return false;
}
@Override
public int hashCode() {
int hash = 1;
hash = hash * 31 + this.lastCheckpointEid;
hash = hash * 31 + this.lastCheckpointRound;
hash = hash * 31 + this.lastCheckpointLeader;
hash = hash * 31 + this.lastEid;
hash = hash * 31 + (this.hasState ? 1 : 0);
if (this.stateHash != null) {
for (int i = 0; i < this.stateHash.length; i++) hash = hash * 31 + (int) this.stateHash[i];
} else {
hash = hash * 31 + 0;
}
if (this.messageBatches != null) {
for (int i = 0; i < this.messageBatches.length; i++) {
if (this.messageBatches[i] != null) {
hash = hash * 31 + this.messageBatches[i].hashCode();
} else {
hash = hash * 31 + 0;
}
}
} else {
hash = hash * 31 + 0;
}
return hash;
}
}
| apache-2.0 |
nmorel/gwt-jackson | gwt-jackson/src/main/java/com/github/nmorel/gwtjackson/client/deser/map/TreeMapJsonDeserializer.java | 2443 | /*
* Copyright 2013 Nicolas Morel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.nmorel.gwtjackson.client.deser.map;
import java.util.TreeMap;
import com.github.nmorel.gwtjackson.client.JsonDeserializer;
import com.github.nmorel.gwtjackson.client.deser.map.key.KeyDeserializer;
/**
* Default {@link JsonDeserializer} implementation for {@link TreeMap}.
* <p>Cannot be overriden. Use {@link BaseMapJsonDeserializer}.</p>
*
* @param <K> Type of the keys inside the {@link TreeMap}
* @param <V> Type of the values inside the {@link TreeMap}
* @author Nicolas Morel
* @version $Id: $
*/
public final class TreeMapJsonDeserializer<K, V> extends BaseMapJsonDeserializer<TreeMap<K, V>, K, V> {
/**
* <p>newInstance</p>
*
* @param keyDeserializer {@link KeyDeserializer} used to deserialize the keys.
* @param valueDeserializer {@link JsonDeserializer} used to deserialize the values.
* @param <K> Type of the keys inside the {@link TreeMap}
* @param <V> Type of the values inside the {@link TreeMap}
* @return a new instance of {@link TreeMapJsonDeserializer}
*/
public static <K, V> TreeMapJsonDeserializer<K, V> newInstance( KeyDeserializer<K> keyDeserializer,
JsonDeserializer<V> valueDeserializer ) {
return new TreeMapJsonDeserializer<K, V>( keyDeserializer, valueDeserializer );
}
/**
* @param keyDeserializer {@link KeyDeserializer} used to deserialize the keys.
* @param valueDeserializer {@link JsonDeserializer} used to deserialize the values.
*/
private TreeMapJsonDeserializer( KeyDeserializer<K> keyDeserializer, JsonDeserializer<V> valueDeserializer ) {
super( keyDeserializer, valueDeserializer );
}
/** {@inheritDoc} */
@Override
protected TreeMap<K, V> newMap() {
return new TreeMap<K, V>();
}
}
| apache-2.0 |
deleidos/digitaledge-platform | commons-core/src/main/java/com/deleidos/rtws/commons/util/ca/CAUrl.java | 16214 | /**
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
*
* 1. Definitions.
*
* "License" shall mean the terms and conditions for use, reproduction,
* and distribution as defined by Sections 1 through 9 of this document.
*
* "Licensor" shall mean the copyright owner or entity authorized by
* the copyright owner that is granting the License.
*
* "Legal Entity" shall mean the union of the acting entity and all
* other entities that control, are controlled by, or are under common
* control with that entity. For the purposes of this definition,
* "control" means (i) the power, direct or indirect, to cause the
* direction or management of such entity, whether by contract or
* otherwise, or (ii) ownership of fifty percent (50%) or more of the
* outstanding shares, or (iii) beneficial ownership of such entity.
*
* "You" (or "Your") shall mean an individual or Legal Entity
* exercising permissions granted by this License.
*
* "Source" form shall mean the preferred form for making modifications,
* including but not limited to software source code, documentation
* source, and configuration files.
*
* "Object" form shall mean any form resulting from mechanical
* transformation or translation of a Source form, including but
* not limited to compiled object code, generated documentation,
* and conversions to other media types.
*
* "Work" shall mean the work of authorship, whether in Source or
* Object form, made available under the License, as indicated by a
* copyright notice that is included in or attached to the work
* (an example is provided in the Appendix below).
*
* "Derivative Works" shall mean any work, whether in Source or Object
* form, that is based on (or derived from) the Work and for which the
* editorial revisions, annotations, elaborations, or other modifications
* represent, as a whole, an original work of authorship. For the purposes
* of this License, Derivative Works shall not include works that remain
* separable from, or merely link (or bind by name) to the interfaces of,
* the Work and Derivative Works thereof.
*
* "Contribution" shall mean any work of authorship, including
* the original version of the Work and any modifications or additions
* to that Work or Derivative Works thereof, that is intentionally
* submitted to Licensor for inclusion in the Work by the copyright owner
* or by an individual or Legal Entity authorized to submit on behalf of
* the copyright owner. For the purposes of this definition, "submitted"
* means any form of electronic, verbal, or written communication sent
* to the Licensor or its representatives, including but not limited to
* communication on electronic mailing lists, source code control systems,
* and issue tracking systems that are managed by, or on behalf of, the
* Licensor for the purpose of discussing and improving the Work, but
* excluding communication that is conspicuously marked or otherwise
* designated in writing by the copyright owner as "Not a Contribution."
*
* "Contributor" shall mean Licensor and any individual or Legal Entity
* on behalf of whom a Contribution has been received by Licensor and
* subsequently incorporated within the Work.
*
* 2. Grant of Copyright License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* copyright license to reproduce, prepare Derivative Works of,
* publicly display, publicly perform, sublicense, and distribute the
* Work and such Derivative Works in Source or Object form.
*
* 3. Grant of Patent License. Subject to the terms and conditions of
* this License, each Contributor hereby grants to You a perpetual,
* worldwide, non-exclusive, no-charge, royalty-free, irrevocable
* (except as stated in this section) patent license to make, have made,
* use, offer to sell, sell, import, and otherwise transfer the Work,
* where such license applies only to those patent claims licensable
* by such Contributor that are necessarily infringed by their
* Contribution(s) alone or by combination of their Contribution(s)
* with the Work to which such Contribution(s) was submitted. If You
* institute patent litigation against any entity (including a
* cross-claim or counterclaim in a lawsuit) alleging that the Work
* or a Contribution incorporated within the Work constitutes direct
* or contributory patent infringement, then any patent licenses
* granted to You under this License for that Work shall terminate
* as of the date such litigation is filed.
*
* 4. Redistribution. You may reproduce and distribute copies of the
* Work or Derivative Works thereof in any medium, with or without
* modifications, and in Source or Object form, provided that You
* meet the following conditions:
*
* (a) You must give any other recipients of the Work or
* Derivative Works a copy of this License; and
*
* (b) You must cause any modified files to carry prominent notices
* stating that You changed the files; and
*
* (c) You must retain, in the Source form of any Derivative Works
* that You distribute, all copyright, patent, trademark, and
* attribution notices from the Source form of the Work,
* excluding those notices that do not pertain to any part of
* the Derivative Works; and
*
* (d) If the Work includes a "NOTICE" text file as part of its
* distribution, then any Derivative Works that You distribute must
* include a readable copy of the attribution notices contained
* within such NOTICE file, excluding those notices that do not
* pertain to any part of the Derivative Works, in at least one
* of the following places: within a NOTICE text file distributed
* as part of the Derivative Works; within the Source form or
* documentation, if provided along with the Derivative Works; or,
* within a display generated by the Derivative Works, if and
* wherever such third-party notices normally appear. The contents
* of the NOTICE file are for informational purposes only and
* do not modify the License. You may add Your own attribution
* notices within Derivative Works that You distribute, alongside
* or as an addendum to the NOTICE text from the Work, provided
* that such additional attribution notices cannot be construed
* as modifying the License.
*
* You may add Your own copyright statement to Your modifications and
* may provide additional or different license terms and conditions
* for use, reproduction, or distribution of Your modifications, or
* for any such Derivative Works as a whole, provided Your use,
* reproduction, and distribution of the Work otherwise complies with
* the conditions stated in this License.
*
* 5. Submission of Contributions. Unless You explicitly state otherwise,
* any Contribution intentionally submitted for inclusion in the Work
* by You to the Licensor shall be under the terms and conditions of
* this License, without any additional terms or conditions.
* Notwithstanding the above, nothing herein shall supersede or modify
* the terms of any separate license agreement you may have executed
* with Licensor regarding such Contributions.
*
* 6. Trademarks. This License does not grant permission to use the trade
* names, trademarks, service marks, or product names of the Licensor,
* except as required for reasonable and customary use in describing the
* origin of the Work and reproducing the content of the NOTICE file.
*
* 7. Disclaimer of Warranty. Unless required by applicable law or
* agreed to in writing, Licensor provides the Work (and each
* Contributor provides its Contributions) on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied, including, without limitation, any warranties or conditions
* of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
* PARTICULAR PURPOSE. You are solely responsible for determining the
* appropriateness of using or redistributing the Work and assume any
* risks associated with Your exercise of permissions under this License.
*
* 8. Limitation of Liability. In no event and under no legal theory,
* whether in tort (including negligence), contract, or otherwise,
* unless required by applicable law (such as deliberate and grossly
* negligent acts) or agreed to in writing, shall any Contributor be
* liable to You for damages, including any direct, indirect, special,
* incidental, or consequential damages of any character arising as a
* result of this License or out of the use or inability to use the
* Work (including but not limited to damages for loss of goodwill,
* work stoppage, computer failure or malfunction, or any and all
* other commercial damages or losses), even if such Contributor
* has been advised of the possibility of such damages.
*
* 9. Accepting Warranty or Additional Liability. While redistributing
* the Work or Derivative Works thereof, You may choose to offer,
* and charge a fee for, acceptance of support, warranty, indemnity,
* or other liability obligations and/or rights consistent with this
* License. However, in accepting such obligations, You may act only
* on Your own behalf and on Your sole responsibility, not on behalf
* of any other Contributor, and only if You agree to indemnify,
* defend, and hold each Contributor harmless for any liability
* incurred by, or claims asserted against, such Contributor by reason
* of your accepting any such warranty or additional liability.
*
* END OF TERMS AND CONDITIONS
*
* APPENDIX: How to apply the Apache License to your work.
*
* To apply the Apache License to your work, attach the following
* boilerplate notice, with the fields enclosed by brackets "{}"
* replaced with your own identifying information. (Don't include
* the brackets!) The text should be enclosed in the appropriate
* comment syntax for the file format. We also recommend that a
* file or class name and description of purpose be included on the
* same "printed page" as the copyright notice for easier
* identification within third-party archives.
*
* Copyright {yyyy} {name of copyright owner}
*
* 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.deleidos.rtws.commons.util.ca;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import com.deleidos.rtws.commons.config.RtwsConfig;
import com.deleidos.rtws.commons.config.UserDataProperties;
public class CAUrl {
private static Logger logger = LogManager.getLogger(CAUrl.class);
private static String certUrl = null;
private static String certHost = null;
private CAUrl(){
//do nothing
}
/**
* Gets the CA host name.
*
* @return CA host.
*/
public static String getCAHost(){
return certHost;
}
public static String getCAHostTestUrl(){
if(StringUtils.isBlank(UserDataProperties.getInstance().getString("RTWS_TMS_DNS"))){
return String.format("%s%s/", certHost, RtwsConfig.getInstance().getString("webapp.caapi.url.contextPath"));
}
else{
return String.format("%s%s/", certHost, RtwsConfig.getInstance().getString("webapp.caapi.proxy.path"));
}
}
/**
* Gets the CA base url.
*
* @param path String context
* @return CA url.
*/
public static String getCaApiUrl(String path){
if(CAUrl.certUrl == null){
String certUrl = null;
String urlPath = RtwsConfig.getInstance().getString("webapp.caapi.url.path");
String isGateway = UserDataProperties.getInstance().getString(UserDataProperties.RTWS_IS_GATEWAY);
String gatewayIp = System.getProperty("GATEWAY_IP");
//if user data tms_api is present or if cert host is null
if(StringUtils.isNotBlank(isGateway) == true || StringUtils.isNotBlank(gatewayIp) == true){
if(StringUtils.isNotBlank(isGateway)){
String apiHost = UserDataProperties.getInstance().getString("RTWS_TMS_DNS");
String contextPath = RtwsConfig.getInstance().getString("webapp.caapi.proxy.path");
if(StringUtils.isNotBlank(apiHost)){
certUrl = String.format("%s://%s:%s%s/rest/cert/%s", RtwsConfig.getInstance().getString("webapp.caapi.url.scheme"),
apiHost, RtwsConfig.getInstance().getString("webapp.caapi.url.port"), contextPath, path);
CAUrl.certUrl = String.format("%s://%s:%s%s/rest/cert/", RtwsConfig.getInstance().getString("webapp.caapi.url.scheme"),
apiHost, RtwsConfig.getInstance().getString("webapp.caapi.url.port"), contextPath);
CAUrl.certHost = String.format("%s://%s:%s", RtwsConfig.getInstance().getString("webapp.caapi.url.scheme"),
apiHost, RtwsConfig.getInstance().getString("webapp.caapi.url.port"));
}
else{
logger.error("RTWS_TMS_DNS is not set in user data, exiting certificate generation.");
System.exit(-1);
}
}
else if(StringUtils.isNotBlank(gatewayIp)){
String apiHost = gatewayIp;
certUrl = String.format("%s://%s:%s%s/rest/cert/%s", RtwsConfig.getInstance().getString("webapp.caapi.url.scheme"),
apiHost, RtwsConfig.getInstance().getString("webapp.caapi.url.port"), RtwsConfig.getInstance().getString("webapp.caapi.url.contextPath"), path);
CAUrl.certUrl = String.format("%s://%s:%s%s/rest/cert/", RtwsConfig.getInstance().getString("webapp.caapi.url.scheme"),
apiHost, RtwsConfig.getInstance().getString("webapp.caapi.url.port"), RtwsConfig.getInstance().getString("webapp.caapi.url.contextPath"));
CAUrl.certHost = String.format("%s://%s:%s", RtwsConfig.getInstance().getString("webapp.caapi.url.scheme"),
apiHost, RtwsConfig.getInstance().getString("webapp.caapi.url.port"));
}
else{
logger.error("System property RTWS_TMS_API_IP or RTWS_GATEWAY_IP are not defined, exiting certificate generation.");
System.exit(-1);
}
}
else{
if(StringUtils.isNotBlank(urlPath)){
certUrl = String.format("%s/rest/cert/%s", urlPath, path);
CAUrl.certUrl = String.format("%s/rest/cert/", urlPath);
CAUrl.certHost = String.format("%s://%s:%s", RtwsConfig.getInstance().getString("webapp.caapi.url.scheme"),
RtwsConfig.getInstance().getString("webapp.caapi.url.host"), RtwsConfig.getInstance().getString("webapp.caapi.url.port"));
}
else{
logger.error("Property webapp.caapi.url.pathis not defined, exiting certificate generation.");
System.exit(-1);
}
}
return certUrl;
}
else{
return String.format("%s%s", CAUrl.certUrl, path);
}
}
}
| apache-2.0 |
jenkinsci/jexl | src/java/org/apache/commons/jexl/util/Introspector.java | 2004 | /*
* 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.commons.jexl.util;
import org.apache.commons.jexl.util.introspection.Uberspect;
import org.apache.commons.jexl.util.introspection.UberspectImpl;
import org.apache.commons.jexl.util.introspection.UberspectLoggable;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Little class to manage a Velocity uberspector (Vel 1.4+) for instrospective
* services.
*
* @since 1.0
* @author <a href="mailto:geirm@apache.org">Geir Magnusson Jr.</a>
* @version $Id: Introspector.java 480412 2006-11-29 05:11:23Z bayard $
*/
public class Introspector {
/**
* The uberspector from Velocity that handles all instrospection patterns.
*/
private static Uberspect uberSpect;
static {
Log logger = LogFactory.getLog(Introspector.class);
uberSpect = new UberspectImpl();
((UberspectLoggable) uberSpect).setRuntimeLogger(logger);
}
/**
* For now, expose the raw uberspector to the AST.
*
* @return Uberspect The Velocity uberspector.
*/
public static Uberspect getUberspect() {
return uberSpect;
}
}
| apache-2.0 |
guduchina/jsh_erp | src/main/java/com/jsh/util/SearchConditionUtil.java | 5479 | package com.jsh.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* 根据搜索条件拼装成查询hql语句
*
* @author pengwei_chen
*/
public class SearchConditionUtil {
//拼接字符串的前缀空格字符串
private static final String emptyPrefix = " and ";
/**
* 根据搜索条件自动拼接成hql搜索语句
*
* @param condition 搜索条件 规则:
* 1、类型 n--数字 s--字符串
* 2、属性 eq--等于 neq--不等于 like--像'%XX%' llike--左像'%XX' rlike--右像'XX%' in--包含 gt--大于 gteq--大于等于 lt--小于 lteq--小于等于
* order--value desc asc gy-- group by
* 示例:
* Map<String,Object> condition = new HashMap<String,Object>();
* condition.put("supplier_s_like", "aaa");
* condition.put("contacts_s_llike", "186");
* condition.put("contacts_s_rlike", "186");
* condition.put("phonenum_s_eq", null);
* condition.put("email_n_neq", 23);
* condition.put("description_s_order", "desc");
* @return 封装后的字符串
*/
public static String getCondition(Map<String, Object> condition) {
StringBuffer hql = new StringBuffer();
Set<String> key = condition.keySet();
String groupbyInfo = "";
String orderInfo = "";
for (String keyInfo : key) {
/*
* 1、数组为三个 第一个为对象实例的字段 第二个为字段类型 第三个为属性
* 2、根据分解后的数组拼接搜索条件
*/
Object valueInfo = condition.get(keyInfo);
if (null != valueInfo && valueInfo.toString().length() > 0) {
String[] searchCondition = keyInfo.split("_");
if (searchCondition[1].equals("n"))
hql.append(emptyPrefix).append(searchCondition[0]).append(getType(searchCondition[2])).append(valueInfo);
else if (searchCondition[1].equals("s")) {
if (searchCondition[2].equals("like"))
hql.append(emptyPrefix).append(searchCondition[0]).append(getType(searchCondition[2])).append("'%").append(valueInfo).append("%'");
else if (searchCondition[2].equals("llike"))
hql.append(emptyPrefix).append(searchCondition[0]).append(getType(searchCondition[2])).append("'%").append(valueInfo).append("'");
else if (searchCondition[2].equals("rlike"))
hql.append(emptyPrefix).append(searchCondition[0]).append(getType(searchCondition[2])).append("'").append(valueInfo).append("%'");
else if (searchCondition[2].equals("in"))
hql.append(emptyPrefix).append(searchCondition[0]).append(getType(searchCondition[2])).append("(").append(valueInfo).append(")");
else if (searchCondition[2].equals("order"))
orderInfo = " order by " + searchCondition[0] + " " + valueInfo;
else if (searchCondition[2].equals("gb"))
groupbyInfo = " group by " + searchCondition[0];
else
hql.append(emptyPrefix).append(searchCondition[0]).append(getType(searchCondition[2])).append("'").append(valueInfo).append("'");
}
}
}
return hql.append(groupbyInfo).append(orderInfo).toString();
}
/**
* 获取指定类型的符号
* 属性 eq--等于 neq--不等于 like--像 in--包含 gt--大于 gteq--大于等于 lt--小于 lteq--小于等于 order--value desc asc
*
* @param type type
* @return 类型字符串
*/
private static String getType(String type) {
String typeStr = "";
if (type.equals("eq"))
typeStr = " = ";
else if (type.equals("neq"))
typeStr = " != ";
else if (type.equals("like"))
typeStr = " like ";
else if (type.equals("llike"))
typeStr = " like ";
else if (type.equals("rlike"))
typeStr = " like ";
else if (type.equals("in"))
typeStr = " in ";
else if (type.equals("gt"))
typeStr = " > ";
else if (type.equals("gteq"))
typeStr = " >= ";
else if (type.equals("lt"))
typeStr = " < ";
else if (type.equals("lteq"))
typeStr = " <= ";
else if (type.equals("order"))
typeStr = " order ";
else if (type.equals("gy"))
typeStr = " group by ";
else
typeStr = "unknown";
return typeStr;
}
public static void main(String[] args) {
/**
* 拼接搜索条件
*/
Map<String, Object> condition = new HashMap<String, Object>();
condition.put("supplier_s_like", "aaa");
condition.put("contacts_s_llike", "186");
condition.put("contacts_s_rlike", "186");
condition.put("phonenum_s_eq", null);
condition.put("email_n_neq", 23);
condition.put("description_s_order", "desc");
condition.put("description_s_gb", "aaa");
//获取搜索条件拼接
System.out.println(getCondition(condition));
}
}
| apache-2.0 |
REMEXLabs/SmartFridge | app/src/main/java/com/example/poiz/fridgetablet/data/ShoppingList.java | 2834 | package com.example.poiz.fridgetablet.data;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* class to hold information about a Shoppinglist
*/
public class ShoppingList {
private int id;
private String name;
private Date dateOfCreation;
private int productCount;
List<Product> products = new ArrayList<Product>();
/**
* returns the ID of the Shoppinglist
* @return Integer
*/
public int getId() {
return id;
}
/**
* sets the ID of the Shoppinglist
* @param id
*/
public void setId(int id) {
this.id = id;
}
/**
* Constructor
* @param name
* @param id
* @param dateOfCreation
* @param products
*/
public ShoppingList(String name, int id, Date dateOfCreation, List<Product> products) {
this.name = name;
this.dateOfCreation = dateOfCreation;
this.products = products;
this.id = id;
productCount = products.size();
}
/**
* Constructor
* @param id
* @param name
* @param dateOfCreation
*/
public ShoppingList(int id, String name, Date dateOfCreation) {
this.name = name;
this.dateOfCreation = dateOfCreation;
this.id = id;
}
/**
* sets the amount of Products wich are Stored in the SHoppinglist
* @param productCount
*/
public void setProductCount(int productCount) {
this.productCount = productCount;
}
/**
* returns the Amount of products wich are Stored in the SHoppinglist
* @return integer
*/
public int getProductCount() {
return productCount;
}
/**
* returns the Name of the Shoppinglist
* @return String
*/
public String getName() {
return name;
}
/**
* Sets the Name of the Shoppinglist
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* returns the Date when the Shoppinglist was Created
* @return Date
*/
public Date getDateOfCreation() {
return dateOfCreation;
}
/**
* Sets the Date when the Shoppinglist was created
* @param dateOfCreation
*/
public void setDateOfCreation(Date dateOfCreation) {
this.dateOfCreation = dateOfCreation;
}
/**
* returns a List of all Products wich are stored in the Shoppinglist
* @return
*/
public List<Product> getProducts() {
productCount = products.size();
return products;
}
/**
*Sets a List of all Products wich are stored in the Shoppinglist
* @param products
*/
public void setProducts(List<Product> products) {
this.products = products;
productCount = products.size();
}
} | apache-2.0 |
NLeSC/Aether | src/nl/esciencecenter/aether/impl/CollectedWriteException.java | 2891 | /* $Id: CollectedWriteException.java 11529 2009-11-18 15:53:11Z ceriel $ */
package nl.esciencecenter.aether.impl;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.ArrayList;
/**
* Collects IOExceptions for multicast output streams.
*/
public class CollectedWriteException extends IOException {
/** Added. */
private static final long serialVersionUID = 5494793976122105110L;
private ArrayList<IOException> exceptions = new ArrayList<IOException>();
/**
* Constructs a <code>CollectedWriteException</code> with
* the specified detail message.
*
* @param s the detail message
*/
public CollectedWriteException(String s) {
super(s);
}
/**
* Constructs a <code>CollectedWriteException</code> with
* <code>null</code> as its error detail message.
*/
public CollectedWriteException() {
super();
}
/**
* Adds an exception.
* @param e the exception to be added.
*/
public void add(IOException e) {
exceptions.add(e);
}
/**
* Returns the exceptions.
* @return an array with one element for each exception.
*/
public IOException[] getExceptions() {
return exceptions.toArray(new IOException[exceptions.size()]);
}
public String toString() {
String res = "";
if (exceptions.size() == 0) {
return super.toString();
}
res = "\n--- START OF COLLECTED EXCEPTIONS ---\n";
for (int i = 0; i < exceptions.size(); i++) {
IOException f = exceptions.get(i);
String msg = f.getMessage();
if (msg == null) {
msg = f.toString();
}
res += msg;
res += "\n";
}
res += "--- END OF COLLECTED EXCEPTIONS ---\n";
return res;
}
public void printStackTrace() {
printStackTrace(System.err);
}
public void printStackTrace(PrintStream s) {
if (exceptions.size() == 0) {
super.printStackTrace(s);
return;
}
s.println("--- START OF COLLECTED EXCEPTIONS STACK TRACE ---");
for (int i = 0; i < exceptions.size(); i++) {
IOException f = exceptions.get(i);
f.printStackTrace(s);
}
s.println("--- END OF COLLECTED EXCEPTIONS STACK TRACE ---");
}
public void printStackTrace(PrintWriter s) {
if (exceptions.size() == 0) {
super.printStackTrace(s);
return;
}
s.println("--- START OF COLLECTED EXCEPTIONS STACK TRACE ---");
for (int i = 0; i < exceptions.size(); i++) {
IOException f = exceptions.get(i);
f.printStackTrace(s);
}
s.println("--- END OF COLLECTED EXCEPTIONS STACK TRACE ---");
}
}
| apache-2.0 |
micke-at-hulot/jbpm6jboss7example | src/main/java/se/hulot/jbpm6jboss7example/ejb/ProcessBean.java | 519 | package se.hulot.jbpm6jboss7example.ejb;
import java.util.Map;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;
@Local(ProcessLocal.class)
@Stateless(mappedName="ProcessLocal")
public class ProcessBean implements ProcessLocal {
@EJB
JbpmService jbpmService;
public long startProcess(Map<String, Object> params) throws Exception {
long processInstanceId = jbpmService.createProcess("se.hulot.jbpm6jboss7example", params);
return processInstanceId;
}
}
| apache-2.0 |
CiNC0/Cartier | cartier-commons/src/main/java/xyz/vopen/cartier/commons/plist/NSDictionary.java | 15989 | /*
* plist - An open source library to parse and generate property lists
* Copyright (C) 2014 Daniel Dreibrodt
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package xyz.vopen.cartier.commons.plist;
import java.io.IOException;
import java.util.*;
/**
* A NSDictionary is a collection of keys and values, essentially a Hashtable.
* The keys are simple Strings whereas the values can be any kind of NSObject.
* <p/>
* You can access the keys through the function <code>allKeys()</code>. Access
* to the objects stored for each key is given through the function
* <code>objectoForKey(String key)</code>.
*
* @author Daniel Dreibrodt
* @see Hashtable
* @see NSObject
*/
public class NSDictionary extends NSObject implements Map<String, NSObject> {
private final HashMap<String, NSObject> dict;
/**
* Creates a new empty NSDictionary.
*/
public NSDictionary () {
//With a linked HashMap the order of elements in the dictionary is kept.
dict = new LinkedHashMap<String, NSObject>();
}
/**
* Gets the hashmap which stores the keys and values of this dictionary.
* Changes to the hashmap's contents are directly reflected in this
* dictionary.
*
* @return The hashmap which is used by this dictionary to store its contents.
*/
public HashMap<String, NSObject> getHashMap () {
return dict;
}
/**
* Gets the NSObject stored for the given key.
*
* @param key The key.
* @return The object.
*/
public NSObject objectForKey (String key) {
return dict.get(key);
}
/*
* (non-Javadoc)
*
* @see java.util.Map#size()
*/
public int size () {
return dict.size();
}
/*
* (non-Javadoc)
*
* @see java.util.Map#isEmpty()
*/
public boolean isEmpty () {
return dict.isEmpty();
}
/*
* (non-Javadoc)
*
* @see java.util.Map#containsKey(java.lang.Object)
*/
public boolean containsKey (Object key) {
return dict.containsKey(key);
}
/*
* (non-Javadoc)
*
* @see java.util.Map#containsValue(java.lang.Object)
*/
public boolean containsValue (Object value) {
if (value == null)
return false;
NSObject wrap = fromJavaObject(value);
return dict.containsValue(wrap);
}
/*
* (non-Javadoc)
*
* @see java.util.Map#get(java.lang.Object)
*/
public NSObject get (Object key) {
return dict.get(key);
}
/*
* (non-Javadoc)
*
* @see java.util.Map#putAll(java.util.Map)
*/
public void putAll (Map<? extends String, ? extends NSObject> values) {
for (Object object : values.entrySet()) {
@SuppressWarnings("unchecked")
Entry<String, NSObject> entry = (Entry<String, NSObject>) object;
put(entry.getKey(), entry.getValue());
}
}
/**
* Puts a new key-value pair into this dictionary.
* If the value is null, no operation will be performed on the dictionary.
*
* @param key The key.
* @param obj The value.
* @return The value previously associated to the given key,
* or null, if no value was associated to it.
*/
public NSObject put (String key, NSObject obj) {
if (key == null)
return null;
if (obj == null)
return dict.get(key);
return dict.put(key, obj);
}
/**
* Puts a new key-value pair into this dictionary.
* If key or value are null, no operation will be performed on the dictionary.
*
* @param key The key.
* @param obj The value. Supported object types are numbers, byte-arrays, dates, strings and arrays or sets of those.
* @return The value previously associated to the given key,
* or null, if no value was associated to it.
*/
public NSObject put (String key, Object obj) {
return put(key, fromJavaObject(obj));
}
/**
* Removes a key-value pair from this dictionary.
*
* @param key The key
* @return the value previously associated to the given key.
*/
public NSObject remove (String key) {
return dict.remove(key);
}
/*
* (non-Javadoc)
*
* @see java.util.Map#remove(java.lang.Object)
*/
public NSObject remove (Object key) {
return dict.remove(key);
}
/**
* Removes all key-value pairs from this dictionary.
*
* @see Map#clear()
*/
public void clear () {
dict.clear();
}
/*
* (non-Javadoc)
*
* @see java.util.Map#keySet()
*/
public Set<String> keySet () {
return dict.keySet();
}
/*
* (non-Javadoc)
*
* @see java.util.Map#values()
*/
public Collection<NSObject> values () {
return dict.values();
}
/*
* (non-Javadoc)
*
* @see java.util.Map#entrySet()
*/
public Set<Entry<String, NSObject>> entrySet () {
return dict.entrySet();
}
/**
* Checks whether a given key is contained in this dictionary.
*
* @param key The key that will be searched for.
* @return Whether the key is contained in this dictionary.
*/
public boolean containsKey (String key) {
return dict.containsKey(key);
}
/**
* Checks whether a given value is contained in this dictionary.
*
* @param val The value that will be searched for.
* @return Whether the key is contained in this dictionary.
*/
public boolean containsValue (NSObject val) {
return val != null && dict.containsValue(val);
}
/**
* Checks whether a given value is contained in this dictionary.
*
* @param val The value that will be searched for.
* @return Whether the key is contained in this dictionary.
*/
public boolean containsValue (String val) {
for (NSObject o : dict.values()) {
if (o.getClass().equals(NSString.class)) {
NSString str = (NSString) o;
if (str.getContent().equals(val))
return true;
}
}
return false;
}
/**
* Checks whether a given value is contained in this dictionary.
*
* @param val The value that will be searched for.
* @return Whether the key is contained in this dictionary.
*/
public boolean containsValue (long val) {
for (NSObject o : dict.values()) {
if (o.getClass().equals(NSNumber.class)) {
NSNumber num = (NSNumber) o;
if (num.isInteger() && num.intValue() == val)
return true;
}
}
return false;
}
/**
* Checks whether a given value is contained in this dictionary.
*
* @param val The value that will be searched for.
* @return Whether the key is contained in this dictionary.
*/
public boolean containsValue (double val) {
for (NSObject o : dict.values()) {
if (o.getClass().equals(NSNumber.class)) {
NSNumber num = (NSNumber) o;
if (num.isReal() && num.doubleValue() == val)
return true;
}
}
return false;
}
/**
* Checks whether a given value is contained in this dictionary.
*
* @param val The value that will be searched for.
* @return Whether the key is contained in this dictionary.
*/
public boolean containsValue (boolean val) {
for (NSObject o : dict.values()) {
if (o.getClass().equals(NSNumber.class)) {
NSNumber num = (NSNumber) o;
if (num.isBoolean() && num.boolValue() == val)
return true;
}
}
return false;
}
/**
* Checks whether a given value is contained in this dictionary.
*
* @param val The value that will be searched for.
* @return Whether the key is contained in this dictionary.
*/
public boolean containsValue (Date val) {
for (NSObject o : dict.values()) {
if (o.getClass().equals(NSDate.class)) {
NSDate dat = (NSDate) o;
if (dat.getDate().equals(val))
return true;
}
}
return false;
}
/**
* Checks whether a given value is contained in this dictionary.
*
* @param val The value that will be searched for.
* @return Whether the key is contained in this dictionary.
*/
public boolean containsValue (byte[] val) {
for (NSObject o : dict.values()) {
if (o.getClass().equals(NSData.class)) {
NSData dat = (NSData) o;
if (Arrays.equals(dat.bytes(), val))
return true;
}
}
return false;
}
/**
* Counts the number of contained key-value pairs.
*
* @return The size of this NSDictionary.
*/
public int count () {
return dict.size();
}
@Override
public boolean equals (Object obj) {
return obj.getClass().equals(this.getClass()) && ((NSDictionary) obj).dict.equals(dict);
}
/**
* Gets a list of all keys used in this NSDictionary.
*
* @return The list of all keys used in this NSDictionary.
*/
public String[] allKeys () {
return dict.keySet().toArray(new String[count()]);
}
@Override
public int hashCode () {
int hash = 7;
hash = 83 * hash + (this.dict != null ? this.dict.hashCode() : 0);
return hash;
}
@Override
void toXML (StringBuilder xml, int level) {
indent(xml, level);
xml.append("<dict>");
xml.append(NEWLINE);
for (String key : dict.keySet()) {
NSObject val = objectForKey(key);
indent(xml, level + 1);
xml.append("<key>");
//According to http://www.w3.org/TR/REC-xml/#syntax node values must not
//contain the characters < or &. Also the > character should be escaped.
if (key.contains("&") || key.contains("<") || key.contains(">")) {
xml.append("<![CDATA[");
xml.append(key.replaceAll("]]>", "]]]]><![CDATA[>"));
xml.append("]]>");
} else {
xml.append(key);
}
xml.append("</key>");
xml.append(NEWLINE);
val.toXML(xml, level + 1);
xml.append(NEWLINE);
}
indent(xml, level);
xml.append("</dict>");
}
@Override
void assignIDs (BinaryPropertyListWriter out) {
super.assignIDs(out);
for (Entry<String, NSObject> entry : dict.entrySet()) {
new NSString(entry.getKey()).assignIDs(out);
}
for (Entry<String, NSObject> entry : dict.entrySet()) {
entry.getValue().assignIDs(out);
}
}
@Override
void toBinary (BinaryPropertyListWriter out) throws IOException {
out.writeIntHeader(0xD, dict.size());
Set<Entry<String, NSObject>> entries = dict.entrySet();
for (Entry<String, NSObject> entry : entries) {
out.writeID(out.getID(new NSString(entry.getKey())));
}
for (Entry<String, NSObject> entry : entries) {
out.writeID(out.getID(entry.getValue()));
}
}
/**
* Generates a valid ASCII property list which has this NSDictionary as its
* root object. The generated property list complies with the format as
* described in <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html">
* Property List Programming Guide - Old-Style ASCII Property Lists</a>.
*
* @return ASCII representation of this object.
*/
public String toASCIIPropertyList () {
StringBuilder ascii = new StringBuilder();
toASCII(ascii, 0);
ascii.append(NEWLINE);
return ascii.toString();
}
/**
* Generates a valid ASCII property list in GnuStep format which has this
* NSDictionary as its root object. The generated property list complies with
* the format as described in <a href="http://www.gnustep.org/resources/documentation/Developer/Base/Reference/NSPropertyList.html">
* GnuStep - NSPropertyListSerialization class documentation
* </a>
*
* @return GnuStep ASCII representation of this object.
*/
public String toGnuStepASCIIPropertyList () {
StringBuilder ascii = new StringBuilder();
toASCIIGnuStep(ascii, 0);
ascii.append(NEWLINE);
return ascii.toString();
}
@Override
protected void toASCII (StringBuilder ascii, int level) {
indent(ascii, level);
ascii.append(ASCIIPropertyListParser.DICTIONARY_BEGIN_TOKEN);
ascii.append(NEWLINE);
String[] keys = allKeys();
for (String key : keys) {
NSObject val = objectForKey(key);
indent(ascii, level + 1);
ascii.append('"');
ascii.append(NSString.escapeStringForASCII(key));
ascii.append("\" =");
Class<?> objClass = val.getClass();
if (objClass.equals(NSDictionary.class) || objClass.equals(NSArray.class) || objClass.equals(NSData.class)) {
ascii.append(NEWLINE);
val.toASCII(ascii, level + 2);
} else {
ascii.append(' ');
val.toASCII(ascii, 0);
}
ascii.append(ASCIIPropertyListParser.DICTIONARY_ITEM_DELIMITER_TOKEN);
ascii.append(NEWLINE);
}
indent(ascii, level);
ascii.append(ASCIIPropertyListParser.DICTIONARY_END_TOKEN);
}
@Override
protected void toASCIIGnuStep (StringBuilder ascii, int level) {
indent(ascii, level);
ascii.append(ASCIIPropertyListParser.DICTIONARY_BEGIN_TOKEN);
ascii.append(NEWLINE);
String[] keys = dict.keySet().toArray(new String[dict.size()]);
for (String key : keys) {
NSObject val = objectForKey(key);
indent(ascii, level + 1);
ascii.append('"');
ascii.append(NSString.escapeStringForASCII(key));
ascii.append("\" =");
Class<?> objClass = val.getClass();
if (objClass.equals(NSDictionary.class) || objClass.equals(NSArray.class) || objClass.equals(NSData.class)) {
ascii.append(NEWLINE);
val.toASCIIGnuStep(ascii, level + 2);
} else {
ascii.append(' ');
val.toASCIIGnuStep(ascii, 0);
}
ascii.append(ASCIIPropertyListParser.DICTIONARY_ITEM_DELIMITER_TOKEN);
ascii.append(NEWLINE);
}
indent(ascii, level);
ascii.append(ASCIIPropertyListParser.DICTIONARY_END_TOKEN);
}
}
| apache-2.0 |
multi-os-engine/moe-core | moe.apple/moe.platform.ios/src/main/java/apple/contactsui/CNContactPickerViewController.java | 8924 | /*
Copyright 2014-2016 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apple.contactsui;
import apple.NSObject;
import apple.contactsui.protocol.CNContactPickerDelegate;
import apple.foundation.NSArray;
import apple.foundation.NSBundle;
import apple.foundation.NSCoder;
import apple.foundation.NSMethodSignature;
import apple.foundation.NSPredicate;
import apple.foundation.NSSet;
import apple.uikit.UIViewController;
import org.moe.natj.c.ann.FunctionPtr;
import org.moe.natj.general.NatJ;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Library;
import org.moe.natj.general.ann.Mapped;
import org.moe.natj.general.ann.MappedReturn;
import org.moe.natj.general.ann.NInt;
import org.moe.natj.general.ann.NUInt;
import org.moe.natj.general.ann.Owned;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.VoidPtr;
import org.moe.natj.objc.Class;
import org.moe.natj.objc.ObjCRuntime;
import org.moe.natj.objc.SEL;
import org.moe.natj.objc.ann.ObjCClassBinding;
import org.moe.natj.objc.ann.Selector;
import org.moe.natj.objc.map.ObjCObjectMapper;
/**
* The CNContactPickerViewController allows the user to select one or multiple contacts or properties.
* <p>
* The entire list of contacts will be presented to the user.
* The picker supports both single selection and multi-selection.
* The app does not need access to the user’s contacts and the user will
* not be prompted for access. It will only have access to the final selection of the user.
* Changing the predicates only takes effect before the view is presented.
*/
@Generated
@Library("ContactsUI")
@Runtime(ObjCRuntime.class)
@ObjCClassBinding
public class CNContactPickerViewController extends UIViewController {
static {
NatJ.register();
}
@Generated
protected CNContactPickerViewController(Pointer peer) {
super(peer);
}
@Generated
@Selector("accessInstanceVariablesDirectly")
public static native boolean accessInstanceVariablesDirectly();
@Generated
@Owned
@Selector("alloc")
public static native CNContactPickerViewController alloc();
@Owned
@Generated
@Selector("allocWithZone:")
public static native CNContactPickerViewController allocWithZone(VoidPtr zone);
@Generated
@Selector("attemptRotationToDeviceOrientation")
public static native void attemptRotationToDeviceOrientation();
@Generated
@Selector("automaticallyNotifiesObserversForKey:")
public static native boolean automaticallyNotifiesObserversForKey(String key);
@Generated
@Selector("cancelPreviousPerformRequestsWithTarget:")
public static native void cancelPreviousPerformRequestsWithTarget(@Mapped(ObjCObjectMapper.class) Object aTarget);
@Generated
@Selector("cancelPreviousPerformRequestsWithTarget:selector:object:")
public static native void cancelPreviousPerformRequestsWithTargetSelectorObject(
@Mapped(ObjCObjectMapper.class) Object aTarget, SEL aSelector,
@Mapped(ObjCObjectMapper.class) Object anArgument);
@Generated
@Selector("classFallbacksForKeyedArchiver")
public static native NSArray<String> classFallbacksForKeyedArchiver();
@Generated
@Selector("classForKeyedUnarchiver")
public static native Class classForKeyedUnarchiver();
@Generated
@Selector("clearTextInputContextIdentifier:")
public static native void clearTextInputContextIdentifier(String identifier);
@Generated
@Selector("debugDescription")
public static native String debugDescription_static();
@Generated
@Selector("description")
public static native String description_static();
@Generated
@Selector("hash")
@NUInt
public static native long hash_static();
@Generated
@Selector("instanceMethodForSelector:")
@FunctionPtr(name = "call_instanceMethodForSelector_ret")
public static native NSObject.Function_instanceMethodForSelector_ret instanceMethodForSelector(SEL aSelector);
@Generated
@Selector("instanceMethodSignatureForSelector:")
public static native NSMethodSignature instanceMethodSignatureForSelector(SEL aSelector);
@Generated
@Selector("instancesRespondToSelector:")
public static native boolean instancesRespondToSelector(SEL aSelector);
@Generated
@Selector("isSubclassOfClass:")
public static native boolean isSubclassOfClass(Class aClass);
@Generated
@Selector("keyPathsForValuesAffectingValueForKey:")
public static native NSSet<String> keyPathsForValuesAffectingValueForKey(String key);
@Generated
@Owned
@Selector("new")
public static native CNContactPickerViewController new_objc();
@Generated
@Selector("resolveClassMethod:")
public static native boolean resolveClassMethod(SEL sel);
@Generated
@Selector("resolveInstanceMethod:")
public static native boolean resolveInstanceMethod(SEL sel);
@Generated
@Selector("setVersion:")
public static native void setVersion_static(@NInt long aVersion);
@Generated
@Selector("superclass")
public static native Class superclass_static();
@Generated
@Selector("version")
@NInt
public static native long version_static();
/**
* The delegate to be notified when the user selects a contact or property.
*/
@Generated
@Selector("delegate")
@MappedReturn(ObjCObjectMapper.class)
public native CNContactPickerDelegate delegate();
/**
* The CNContact property keys to display in the contact detail card.
* <p>
* If not set all properties are displayed.
*/
@Generated
@Selector("displayedPropertyKeys")
public native NSArray<String> displayedPropertyKeys();
@Generated
@Selector("init")
public native CNContactPickerViewController init();
@Generated
@Selector("initWithCoder:")
public native CNContactPickerViewController initWithCoder(NSCoder coder);
@Generated
@Selector("initWithNibName:bundle:")
public native CNContactPickerViewController initWithNibNameBundle(String nibNameOrNil, NSBundle nibBundleOrNil);
/**
* e.g. emailAddresses.@count > 0
*/
@Generated
@Selector("predicateForEnablingContact")
public native NSPredicate predicateForEnablingContact();
/**
* e.g. emailAddresses.@count == 1
*/
@Generated
@Selector("predicateForSelectionOfContact")
public native NSPredicate predicateForSelectionOfContact();
/**
* e.g. (key == 'emailAddresses') AND (value LIKE '*@apple.com')
*/
@Generated
@Selector("predicateForSelectionOfProperty")
public native NSPredicate predicateForSelectionOfProperty();
/**
* The delegate to be notified when the user selects a contact or property.
*/
@Generated
@Selector("setDelegate:")
public native void setDelegate_unsafe(@Mapped(ObjCObjectMapper.class) CNContactPickerDelegate value);
/**
* The delegate to be notified when the user selects a contact or property.
*/
@Generated
public void setDelegate(@Mapped(ObjCObjectMapper.class) CNContactPickerDelegate value) {
Object __old = delegate();
if (value != null) {
org.moe.natj.objc.ObjCRuntime.associateObjCObject(this, value);
}
setDelegate_unsafe(value);
if (__old != null) {
org.moe.natj.objc.ObjCRuntime.dissociateObjCObject(this, __old);
}
}
/**
* The CNContact property keys to display in the contact detail card.
* <p>
* If not set all properties are displayed.
*/
@Generated
@Selector("setDisplayedPropertyKeys:")
public native void setDisplayedPropertyKeys(NSArray<String> value);
/**
* e.g. emailAddresses.@count > 0
*/
@Generated
@Selector("setPredicateForEnablingContact:")
public native void setPredicateForEnablingContact(NSPredicate value);
/**
* e.g. emailAddresses.@count == 1
*/
@Generated
@Selector("setPredicateForSelectionOfContact:")
public native void setPredicateForSelectionOfContact(NSPredicate value);
/**
* e.g. (key == 'emailAddresses') AND (value LIKE '*@apple.com')
*/
@Generated
@Selector("setPredicateForSelectionOfProperty:")
public native void setPredicateForSelectionOfProperty(NSPredicate value);
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/AWSServiceCatalog.java | 88464 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.servicecatalog;
import javax.annotation.Generated;
import com.amazonaws.*;
import com.amazonaws.regions.*;
import com.amazonaws.services.servicecatalog.model.*;
/**
* Interface for accessing AWS Service Catalog.
* <p>
* <b>Note:</b> Do not directly implement this interface, new methods are added to it regularly. Extend from
* {@link com.amazonaws.services.servicecatalog.AbstractAWSServiceCatalog} instead.
* </p>
* <p>
* <fullname>AWS Service Catalog</fullname>
* <p>
* <a href="https://aws.amazon.com/servicecatalog/">AWS Service Catalog</a> enables organizations to create and manage
* catalogs of IT services that are approved for use on AWS. To get the most out of this documentation, you should be
* familiar with the terminology discussed in <a
* href="http://docs.aws.amazon.com/servicecatalog/latest/adminguide/what-is_concepts.html">AWS Service Catalog
* Concepts</a>.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public interface AWSServiceCatalog {
/**
* The region metadata service name for computing region endpoints. You can use this value to retrieve metadata
* (such as supported regions) of the service.
*
* @see RegionUtils#getRegionsForService(String)
*/
String ENDPOINT_PREFIX = "servicecatalog";
/**
* Overrides the default endpoint for this client ("servicecatalog.us-east-1.amazonaws.com"). Callers can use this
* method to control which AWS region they want to work with.
* <p>
* Callers can pass in just the endpoint (ex: "servicecatalog.us-east-1.amazonaws.com") or a full URL, including the
* protocol (ex: "servicecatalog.us-east-1.amazonaws.com"). If the protocol is not specified here, the default
* protocol from this client's {@link ClientConfiguration} will be used, which by default is HTTPS.
* <p>
* For more information on using AWS regions with the AWS SDK for Java, and a complete list of all available
* endpoints for all AWS services, see: <a href=
* "https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/java-dg-region-selection.html#region-selection-choose-endpoint"
* > https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/java-dg-region-selection.html#region-selection-
* choose-endpoint</a>
* <p>
* <b>This method is not threadsafe. An endpoint should be configured when the client is created and before any
* service requests are made. Changing it afterwards creates inevitable race conditions for any service requests in
* transit or retrying.</b>
*
* @param endpoint
* The endpoint (ex: "servicecatalog.us-east-1.amazonaws.com") or a full URL, including the protocol (ex:
* "servicecatalog.us-east-1.amazonaws.com") of the region specific AWS endpoint this client will communicate
* with.
* @deprecated use {@link AwsClientBuilder#setEndpointConfiguration(AwsClientBuilder.EndpointConfiguration)} for
* example:
* {@code builder.setEndpointConfiguration(new EndpointConfiguration(endpoint, signingRegion));}
*/
@Deprecated
void setEndpoint(String endpoint);
/**
* An alternative to {@link AWSServiceCatalog#setEndpoint(String)}, sets the regional endpoint for this client's
* service calls. Callers can use this method to control which AWS region they want to work with.
* <p>
* By default, all service endpoints in all regions use the https protocol. To use http instead, specify it in the
* {@link ClientConfiguration} supplied at construction.
* <p>
* <b>This method is not threadsafe. A region should be configured when the client is created and before any service
* requests are made. Changing it afterwards creates inevitable race conditions for any service requests in transit
* or retrying.</b>
*
* @param region
* The region this client will communicate with. See {@link Region#getRegion(com.amazonaws.regions.Regions)}
* for accessing a given region. Must not be null and must be a region where the service is available.
*
* @see Region#getRegion(com.amazonaws.regions.Regions)
* @see Region#createClient(Class, com.amazonaws.auth.AWSCredentialsProvider, ClientConfiguration)
* @see Region#isServiceSupported(String)
* @deprecated use {@link AwsClientBuilder#setRegion(String)}
*/
@Deprecated
void setRegion(Region region);
/**
* <p>
* Accepts an offer to share the specified portfolio.
* </p>
*
* @param acceptPortfolioShareRequest
* @return Result of the AcceptPortfolioShare operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws LimitExceededException
* The current limits of the service would have been exceeded by this operation. Decrease your resource use
* or increase your service limits and retry the operation.
* @sample AWSServiceCatalog.AcceptPortfolioShare
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/AcceptPortfolioShare"
* target="_top">AWS API Documentation</a>
*/
AcceptPortfolioShareResult acceptPortfolioShare(AcceptPortfolioShareRequest acceptPortfolioShareRequest);
/**
* <p>
* Associates the specified budget with the specified resource.
* </p>
*
* @param associateBudgetWithResourceRequest
* @return Result of the AssociateBudgetWithResource operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws DuplicateResourceException
* The specified resource is a duplicate.
* @throws LimitExceededException
* The current limits of the service would have been exceeded by this operation. Decrease your resource use
* or increase your service limits and retry the operation.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.AssociateBudgetWithResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/AssociateBudgetWithResource"
* target="_top">AWS API Documentation</a>
*/
AssociateBudgetWithResourceResult associateBudgetWithResource(AssociateBudgetWithResourceRequest associateBudgetWithResourceRequest);
/**
* <p>
* Associates the specified principal ARN with the specified portfolio.
* </p>
*
* @param associatePrincipalWithPortfolioRequest
* @return Result of the AssociatePrincipalWithPortfolio operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws LimitExceededException
* The current limits of the service would have been exceeded by this operation. Decrease your resource use
* or increase your service limits and retry the operation.
* @sample AWSServiceCatalog.AssociatePrincipalWithPortfolio
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/AssociatePrincipalWithPortfolio"
* target="_top">AWS API Documentation</a>
*/
AssociatePrincipalWithPortfolioResult associatePrincipalWithPortfolio(AssociatePrincipalWithPortfolioRequest associatePrincipalWithPortfolioRequest);
/**
* <p>
* Associates the specified product with the specified portfolio.
* </p>
*
* @param associateProductWithPortfolioRequest
* @return Result of the AssociateProductWithPortfolio operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws LimitExceededException
* The current limits of the service would have been exceeded by this operation. Decrease your resource use
* or increase your service limits and retry the operation.
* @sample AWSServiceCatalog.AssociateProductWithPortfolio
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/AssociateProductWithPortfolio"
* target="_top">AWS API Documentation</a>
*/
AssociateProductWithPortfolioResult associateProductWithPortfolio(AssociateProductWithPortfolioRequest associateProductWithPortfolioRequest);
/**
* <p>
* Associates a self-service action with a provisioning artifact.
* </p>
*
* @param associateServiceActionWithProvisioningArtifactRequest
* @return Result of the AssociateServiceActionWithProvisioningArtifact operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws DuplicateResourceException
* The specified resource is a duplicate.
* @throws LimitExceededException
* The current limits of the service would have been exceeded by this operation. Decrease your resource use
* or increase your service limits and retry the operation.
* @sample AWSServiceCatalog.AssociateServiceActionWithProvisioningArtifact
* @see <a
* href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/AssociateServiceActionWithProvisioningArtifact"
* target="_top">AWS API Documentation</a>
*/
AssociateServiceActionWithProvisioningArtifactResult associateServiceActionWithProvisioningArtifact(
AssociateServiceActionWithProvisioningArtifactRequest associateServiceActionWithProvisioningArtifactRequest);
/**
* <p>
* Associate the specified TagOption with the specified portfolio or product.
* </p>
*
* @param associateTagOptionWithResourceRequest
* @return Result of the AssociateTagOptionWithResource operation returned by the service.
* @throws TagOptionNotMigratedException
* An operation requiring TagOptions failed because the TagOptions migration process has not been performed
* for this account. Please use the AWS console to perform the migration process before retrying the
* operation.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws LimitExceededException
* The current limits of the service would have been exceeded by this operation. Decrease your resource use
* or increase your service limits and retry the operation.
* @throws DuplicateResourceException
* The specified resource is a duplicate.
* @throws InvalidStateException
* An attempt was made to modify a resource that is in a state that is not valid. Check your resources to
* ensure that they are in valid states before retrying the operation.
* @sample AWSServiceCatalog.AssociateTagOptionWithResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/AssociateTagOptionWithResource"
* target="_top">AWS API Documentation</a>
*/
AssociateTagOptionWithResourceResult associateTagOptionWithResource(AssociateTagOptionWithResourceRequest associateTagOptionWithResourceRequest);
/**
* <p>
* Associates multiple self-service actions with provisioning artifacts.
* </p>
*
* @param batchAssociateServiceActionWithProvisioningArtifactRequest
* @return Result of the BatchAssociateServiceActionWithProvisioningArtifact operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.BatchAssociateServiceActionWithProvisioningArtifact
* @see <a
* href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/BatchAssociateServiceActionWithProvisioningArtifact"
* target="_top">AWS API Documentation</a>
*/
BatchAssociateServiceActionWithProvisioningArtifactResult batchAssociateServiceActionWithProvisioningArtifact(
BatchAssociateServiceActionWithProvisioningArtifactRequest batchAssociateServiceActionWithProvisioningArtifactRequest);
/**
* <p>
* Disassociates a batch of self-service actions from the specified provisioning artifact.
* </p>
*
* @param batchDisassociateServiceActionFromProvisioningArtifactRequest
* @return Result of the BatchDisassociateServiceActionFromProvisioningArtifact operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.BatchDisassociateServiceActionFromProvisioningArtifact
* @see <a
* href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/BatchDisassociateServiceActionFromProvisioningArtifact"
* target="_top">AWS API Documentation</a>
*/
BatchDisassociateServiceActionFromProvisioningArtifactResult batchDisassociateServiceActionFromProvisioningArtifact(
BatchDisassociateServiceActionFromProvisioningArtifactRequest batchDisassociateServiceActionFromProvisioningArtifactRequest);
/**
* <p>
* Copies the specified source product to the specified target product or a new product.
* </p>
* <p>
* You can copy a product to the same account or another account. You can copy a product to the same region or
* another region.
* </p>
* <p>
* This operation is performed asynchronously. To track the progress of the operation, use
* <a>DescribeCopyProductStatus</a>.
* </p>
*
* @param copyProductRequest
* @return Result of the CopyProduct operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.CopyProduct
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/CopyProduct" target="_top">AWS API
* Documentation</a>
*/
CopyProductResult copyProduct(CopyProductRequest copyProductRequest);
/**
* <p>
* Creates a constraint.
* </p>
*
* @param createConstraintRequest
* @return Result of the CreateConstraint operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws LimitExceededException
* The current limits of the service would have been exceeded by this operation. Decrease your resource use
* or increase your service limits and retry the operation.
* @throws DuplicateResourceException
* The specified resource is a duplicate.
* @sample AWSServiceCatalog.CreateConstraint
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/CreateConstraint"
* target="_top">AWS API Documentation</a>
*/
CreateConstraintResult createConstraint(CreateConstraintRequest createConstraintRequest);
/**
* <p>
* Creates a portfolio.
* </p>
*
* @param createPortfolioRequest
* @return Result of the CreatePortfolio operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws LimitExceededException
* The current limits of the service would have been exceeded by this operation. Decrease your resource use
* or increase your service limits and retry the operation.
* @throws TagOptionNotMigratedException
* An operation requiring TagOptions failed because the TagOptions migration process has not been performed
* for this account. Please use the AWS console to perform the migration process before retrying the
* operation.
* @sample AWSServiceCatalog.CreatePortfolio
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/CreatePortfolio" target="_top">AWS
* API Documentation</a>
*/
CreatePortfolioResult createPortfolio(CreatePortfolioRequest createPortfolioRequest);
/**
* <p>
* Shares the specified portfolio with the specified account or organization node. Shares to an organization node
* can only be created by the master account of an Organization. AWSOrganizationsAccess must be enabled in order to
* create a portfolio share to an organization node.
* </p>
*
* @param createPortfolioShareRequest
* @return Result of the CreatePortfolioShare operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws LimitExceededException
* The current limits of the service would have been exceeded by this operation. Decrease your resource use
* or increase your service limits and retry the operation.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws OperationNotSupportedException
* The operation is not supported.
* @throws InvalidStateException
* An attempt was made to modify a resource that is in a state that is not valid. Check your resources to
* ensure that they are in valid states before retrying the operation.
* @sample AWSServiceCatalog.CreatePortfolioShare
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/CreatePortfolioShare"
* target="_top">AWS API Documentation</a>
*/
CreatePortfolioShareResult createPortfolioShare(CreatePortfolioShareRequest createPortfolioShareRequest);
/**
* <p>
* Creates a product.
* </p>
*
* @param createProductRequest
* @return Result of the CreateProduct operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws LimitExceededException
* The current limits of the service would have been exceeded by this operation. Decrease your resource use
* or increase your service limits and retry the operation.
* @throws TagOptionNotMigratedException
* An operation requiring TagOptions failed because the TagOptions migration process has not been performed
* for this account. Please use the AWS console to perform the migration process before retrying the
* operation.
* @sample AWSServiceCatalog.CreateProduct
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/CreateProduct" target="_top">AWS
* API Documentation</a>
*/
CreateProductResult createProduct(CreateProductRequest createProductRequest);
/**
* <p>
* Creates a plan. A plan includes the list of resources to be created (when provisioning a new product) or modified
* (when updating a provisioned product) when the plan is executed.
* </p>
* <p>
* You can create one plan per provisioned product. To create a plan for an existing provisioned product, the
* product status must be AVAILBLE or TAINTED.
* </p>
* <p>
* To view the resource changes in the change set, use <a>DescribeProvisionedProductPlan</a>. To create or modify
* the provisioned product, use <a>ExecuteProvisionedProductPlan</a>.
* </p>
*
* @param createProvisionedProductPlanRequest
* @return Result of the CreateProvisionedProductPlan operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidStateException
* An attempt was made to modify a resource that is in a state that is not valid. Check your resources to
* ensure that they are in valid states before retrying the operation.
* @sample AWSServiceCatalog.CreateProvisionedProductPlan
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/CreateProvisionedProductPlan"
* target="_top">AWS API Documentation</a>
*/
CreateProvisionedProductPlanResult createProvisionedProductPlan(CreateProvisionedProductPlanRequest createProvisionedProductPlanRequest);
/**
* <p>
* Creates a provisioning artifact (also known as a version) for the specified product.
* </p>
* <p>
* You cannot create a provisioning artifact for a product that was shared with you.
* </p>
*
* @param createProvisioningArtifactRequest
* @return Result of the CreateProvisioningArtifact operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws LimitExceededException
* The current limits of the service would have been exceeded by this operation. Decrease your resource use
* or increase your service limits and retry the operation.
* @sample AWSServiceCatalog.CreateProvisioningArtifact
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/CreateProvisioningArtifact"
* target="_top">AWS API Documentation</a>
*/
CreateProvisioningArtifactResult createProvisioningArtifact(CreateProvisioningArtifactRequest createProvisioningArtifactRequest);
/**
* <p>
* Creates a self-service action.
* </p>
*
* @param createServiceActionRequest
* @return Result of the CreateServiceAction operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws LimitExceededException
* The current limits of the service would have been exceeded by this operation. Decrease your resource use
* or increase your service limits and retry the operation.
* @sample AWSServiceCatalog.CreateServiceAction
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/CreateServiceAction"
* target="_top">AWS API Documentation</a>
*/
CreateServiceActionResult createServiceAction(CreateServiceActionRequest createServiceActionRequest);
/**
* <p>
* Creates a TagOption.
* </p>
*
* @param createTagOptionRequest
* @return Result of the CreateTagOption operation returned by the service.
* @throws TagOptionNotMigratedException
* An operation requiring TagOptions failed because the TagOptions migration process has not been performed
* for this account. Please use the AWS console to perform the migration process before retrying the
* operation.
* @throws DuplicateResourceException
* The specified resource is a duplicate.
* @throws LimitExceededException
* The current limits of the service would have been exceeded by this operation. Decrease your resource use
* or increase your service limits and retry the operation.
* @sample AWSServiceCatalog.CreateTagOption
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/CreateTagOption" target="_top">AWS
* API Documentation</a>
*/
CreateTagOptionResult createTagOption(CreateTagOptionRequest createTagOptionRequest);
/**
* <p>
* Deletes the specified constraint.
* </p>
*
* @param deleteConstraintRequest
* @return Result of the DeleteConstraint operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.DeleteConstraint
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DeleteConstraint"
* target="_top">AWS API Documentation</a>
*/
DeleteConstraintResult deleteConstraint(DeleteConstraintRequest deleteConstraintRequest);
/**
* <p>
* Deletes the specified portfolio.
* </p>
* <p>
* You cannot delete a portfolio if it was shared with you or if it has associated products, users, constraints, or
* shared accounts.
* </p>
*
* @param deletePortfolioRequest
* @return Result of the DeletePortfolio operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceInUseException
* A resource that is currently in use. Ensure that the resource is not in use and retry the operation.
* @throws TagOptionNotMigratedException
* An operation requiring TagOptions failed because the TagOptions migration process has not been performed
* for this account. Please use the AWS console to perform the migration process before retrying the
* operation.
* @sample AWSServiceCatalog.DeletePortfolio
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DeletePortfolio" target="_top">AWS
* API Documentation</a>
*/
DeletePortfolioResult deletePortfolio(DeletePortfolioRequest deletePortfolioRequest);
/**
* <p>
* Stops sharing the specified portfolio with the specified account or organization node. Shares to an organization
* node can only be deleted by the master account of an Organization.
* </p>
*
* @param deletePortfolioShareRequest
* @return Result of the DeletePortfolioShare operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws OperationNotSupportedException
* The operation is not supported.
* @throws InvalidStateException
* An attempt was made to modify a resource that is in a state that is not valid. Check your resources to
* ensure that they are in valid states before retrying the operation.
* @sample AWSServiceCatalog.DeletePortfolioShare
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DeletePortfolioShare"
* target="_top">AWS API Documentation</a>
*/
DeletePortfolioShareResult deletePortfolioShare(DeletePortfolioShareRequest deletePortfolioShareRequest);
/**
* <p>
* Deletes the specified product.
* </p>
* <p>
* You cannot delete a product if it was shared with you or is associated with a portfolio.
* </p>
*
* @param deleteProductRequest
* @return Result of the DeleteProduct operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws ResourceInUseException
* A resource that is currently in use. Ensure that the resource is not in use and retry the operation.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws TagOptionNotMigratedException
* An operation requiring TagOptions failed because the TagOptions migration process has not been performed
* for this account. Please use the AWS console to perform the migration process before retrying the
* operation.
* @sample AWSServiceCatalog.DeleteProduct
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DeleteProduct" target="_top">AWS
* API Documentation</a>
*/
DeleteProductResult deleteProduct(DeleteProductRequest deleteProductRequest);
/**
* <p>
* Deletes the specified plan.
* </p>
*
* @param deleteProvisionedProductPlanRequest
* @return Result of the DeleteProvisionedProductPlan operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DeleteProvisionedProductPlan
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DeleteProvisionedProductPlan"
* target="_top">AWS API Documentation</a>
*/
DeleteProvisionedProductPlanResult deleteProvisionedProductPlan(DeleteProvisionedProductPlanRequest deleteProvisionedProductPlanRequest);
/**
* <p>
* Deletes the specified provisioning artifact (also known as a version) for the specified product.
* </p>
* <p>
* You cannot delete a provisioning artifact associated with a product that was shared with you. You cannot delete
* the last provisioning artifact for a product, because a product must have at least one provisioning artifact.
* </p>
*
* @param deleteProvisioningArtifactRequest
* @return Result of the DeleteProvisioningArtifact operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws ResourceInUseException
* A resource that is currently in use. Ensure that the resource is not in use and retry the operation.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.DeleteProvisioningArtifact
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DeleteProvisioningArtifact"
* target="_top">AWS API Documentation</a>
*/
DeleteProvisioningArtifactResult deleteProvisioningArtifact(DeleteProvisioningArtifactRequest deleteProvisioningArtifactRequest);
/**
* <p>
* Deletes a self-service action.
* </p>
*
* @param deleteServiceActionRequest
* @return Result of the DeleteServiceAction operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws ResourceInUseException
* A resource that is currently in use. Ensure that the resource is not in use and retry the operation.
* @sample AWSServiceCatalog.DeleteServiceAction
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DeleteServiceAction"
* target="_top">AWS API Documentation</a>
*/
DeleteServiceActionResult deleteServiceAction(DeleteServiceActionRequest deleteServiceActionRequest);
/**
* <p>
* Deletes the specified TagOption.
* </p>
* <p>
* You cannot delete a TagOption if it is associated with a product or portfolio.
* </p>
*
* @param deleteTagOptionRequest
* @return Result of the DeleteTagOption operation returned by the service.
* @throws TagOptionNotMigratedException
* An operation requiring TagOptions failed because the TagOptions migration process has not been performed
* for this account. Please use the AWS console to perform the migration process before retrying the
* operation.
* @throws ResourceInUseException
* A resource that is currently in use. Ensure that the resource is not in use and retry the operation.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DeleteTagOption
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DeleteTagOption" target="_top">AWS
* API Documentation</a>
*/
DeleteTagOptionResult deleteTagOption(DeleteTagOptionRequest deleteTagOptionRequest);
/**
* <p>
* Gets information about the specified constraint.
* </p>
*
* @param describeConstraintRequest
* @return Result of the DescribeConstraint operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DescribeConstraint
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeConstraint"
* target="_top">AWS API Documentation</a>
*/
DescribeConstraintResult describeConstraint(DescribeConstraintRequest describeConstraintRequest);
/**
* <p>
* Gets the status of the specified copy product operation.
* </p>
*
* @param describeCopyProductStatusRequest
* @return Result of the DescribeCopyProductStatus operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DescribeCopyProductStatus
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeCopyProductStatus"
* target="_top">AWS API Documentation</a>
*/
DescribeCopyProductStatusResult describeCopyProductStatus(DescribeCopyProductStatusRequest describeCopyProductStatusRequest);
/**
* <p>
* Gets information about the specified portfolio.
* </p>
*
* @param describePortfolioRequest
* @return Result of the DescribePortfolio operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DescribePortfolio
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribePortfolio"
* target="_top">AWS API Documentation</a>
*/
DescribePortfolioResult describePortfolio(DescribePortfolioRequest describePortfolioRequest);
/**
* <p>
* Gets the status of the specified portfolio share operation. This API can only be called by the master account in
* the organization.
* </p>
*
* @param describePortfolioShareStatusRequest
* @return Result of the DescribePortfolioShareStatus operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws OperationNotSupportedException
* The operation is not supported.
* @sample AWSServiceCatalog.DescribePortfolioShareStatus
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribePortfolioShareStatus"
* target="_top">AWS API Documentation</a>
*/
DescribePortfolioShareStatusResult describePortfolioShareStatus(DescribePortfolioShareStatusRequest describePortfolioShareStatusRequest);
/**
* <p>
* Gets information about the specified product.
* </p>
*
* @param describeProductRequest
* @return Result of the DescribeProduct operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.DescribeProduct
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeProduct" target="_top">AWS
* API Documentation</a>
*/
DescribeProductResult describeProduct(DescribeProductRequest describeProductRequest);
/**
* <p>
* Gets information about the specified product. This operation is run with administrator access.
* </p>
*
* @param describeProductAsAdminRequest
* @return Result of the DescribeProductAsAdmin operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DescribeProductAsAdmin
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeProductAsAdmin"
* target="_top">AWS API Documentation</a>
*/
DescribeProductAsAdminResult describeProductAsAdmin(DescribeProductAsAdminRequest describeProductAsAdminRequest);
/**
* <p>
* Gets information about the specified product.
* </p>
*
* @param describeProductViewRequest
* @return Result of the DescribeProductView operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.DescribeProductView
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeProductView"
* target="_top">AWS API Documentation</a>
*/
DescribeProductViewResult describeProductView(DescribeProductViewRequest describeProductViewRequest);
/**
* <p>
* Gets information about the specified provisioned product.
* </p>
*
* @param describeProvisionedProductRequest
* @return Result of the DescribeProvisionedProduct operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DescribeProvisionedProduct
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeProvisionedProduct"
* target="_top">AWS API Documentation</a>
*/
DescribeProvisionedProductResult describeProvisionedProduct(DescribeProvisionedProductRequest describeProvisionedProductRequest);
/**
* <p>
* Gets information about the resource changes for the specified plan.
* </p>
*
* @param describeProvisionedProductPlanRequest
* @return Result of the DescribeProvisionedProductPlan operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.DescribeProvisionedProductPlan
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeProvisionedProductPlan"
* target="_top">AWS API Documentation</a>
*/
DescribeProvisionedProductPlanResult describeProvisionedProductPlan(DescribeProvisionedProductPlanRequest describeProvisionedProductPlanRequest);
/**
* <p>
* Gets information about the specified provisioning artifact (also known as a version) for the specified product.
* </p>
*
* @param describeProvisioningArtifactRequest
* @return Result of the DescribeProvisioningArtifact operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DescribeProvisioningArtifact
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeProvisioningArtifact"
* target="_top">AWS API Documentation</a>
*/
DescribeProvisioningArtifactResult describeProvisioningArtifact(DescribeProvisioningArtifactRequest describeProvisioningArtifactRequest);
/**
* <p>
* Gets information about the configuration required to provision the specified product using the specified
* provisioning artifact.
* </p>
* <p>
* If the output contains a TagOption key with an empty list of values, there is a TagOption conflict for that key.
* The end user cannot take action to fix the conflict, and launch is not blocked. In subsequent calls to
* <a>ProvisionProduct</a>, do not include conflicted TagOption keys as tags, or this causes the error
* "Parameter validation failed: Missing required parameter in Tags[<i>N</i>]:<i>Value</i>". Tag the provisioned
* product with the value <code>sc-tagoption-conflict-portfolioId-productId</code>.
* </p>
*
* @param describeProvisioningParametersRequest
* @return Result of the DescribeProvisioningParameters operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DescribeProvisioningParameters
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeProvisioningParameters"
* target="_top">AWS API Documentation</a>
*/
DescribeProvisioningParametersResult describeProvisioningParameters(DescribeProvisioningParametersRequest describeProvisioningParametersRequest);
/**
* <p>
* Gets information about the specified request operation.
* </p>
* <p>
* Use this operation after calling a request operation (for example, <a>ProvisionProduct</a>,
* <a>TerminateProvisionedProduct</a>, or <a>UpdateProvisionedProduct</a>).
* </p>
* <note>
* <p>
* If a provisioned product was transferred to a new owner using <a>UpdateProvisionedProductProperties</a>, the new
* owner will be able to describe all past records for that product. The previous owner will no longer be able to
* describe the records, but will be able to use <a>ListRecordHistory</a> to see the product's history from when he
* was the owner.
* </p>
* </note>
*
* @param describeRecordRequest
* @return Result of the DescribeRecord operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DescribeRecord
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeRecord" target="_top">AWS
* API Documentation</a>
*/
DescribeRecordResult describeRecord(DescribeRecordRequest describeRecordRequest);
/**
* <p>
* Describes a self-service action.
* </p>
*
* @param describeServiceActionRequest
* @return Result of the DescribeServiceAction operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DescribeServiceAction
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeServiceAction"
* target="_top">AWS API Documentation</a>
*/
DescribeServiceActionResult describeServiceAction(DescribeServiceActionRequest describeServiceActionRequest);
/**
* @param describeServiceActionExecutionParametersRequest
* @return Result of the DescribeServiceActionExecutionParameters operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DescribeServiceActionExecutionParameters
* @see <a
* href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeServiceActionExecutionParameters"
* target="_top">AWS API Documentation</a>
*/
DescribeServiceActionExecutionParametersResult describeServiceActionExecutionParameters(
DescribeServiceActionExecutionParametersRequest describeServiceActionExecutionParametersRequest);
/**
* <p>
* Gets information about the specified TagOption.
* </p>
*
* @param describeTagOptionRequest
* @return Result of the DescribeTagOption operation returned by the service.
* @throws TagOptionNotMigratedException
* An operation requiring TagOptions failed because the TagOptions migration process has not been performed
* for this account. Please use the AWS console to perform the migration process before retrying the
* operation.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DescribeTagOption
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DescribeTagOption"
* target="_top">AWS API Documentation</a>
*/
DescribeTagOptionResult describeTagOption(DescribeTagOptionRequest describeTagOptionRequest);
/**
* <p>
* Disable portfolio sharing through AWS Organizations feature. This feature will not delete your current shares but
* it will prevent you from creating new shares throughout your organization. Current shares will not be in sync
* with your organization structure if it changes after calling this API. This API can only be called by the master
* account in the organization.
* </p>
*
* @param disableAWSOrganizationsAccessRequest
* @return Result of the DisableAWSOrganizationsAccess operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidStateException
* An attempt was made to modify a resource that is in a state that is not valid. Check your resources to
* ensure that they are in valid states before retrying the operation.
* @throws OperationNotSupportedException
* The operation is not supported.
* @sample AWSServiceCatalog.DisableAWSOrganizationsAccess
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DisableAWSOrganizationsAccess"
* target="_top">AWS API Documentation</a>
*/
DisableAWSOrganizationsAccessResult disableAWSOrganizationsAccess(DisableAWSOrganizationsAccessRequest disableAWSOrganizationsAccessRequest);
/**
* <p>
* Disassociates the specified budget from the specified resource.
* </p>
*
* @param disassociateBudgetFromResourceRequest
* @return Result of the DisassociateBudgetFromResource operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DisassociateBudgetFromResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DisassociateBudgetFromResource"
* target="_top">AWS API Documentation</a>
*/
DisassociateBudgetFromResourceResult disassociateBudgetFromResource(DisassociateBudgetFromResourceRequest disassociateBudgetFromResourceRequest);
/**
* <p>
* Disassociates a previously associated principal ARN from a specified portfolio.
* </p>
*
* @param disassociatePrincipalFromPortfolioRequest
* @return Result of the DisassociatePrincipalFromPortfolio operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DisassociatePrincipalFromPortfolio
* @see <a
* href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DisassociatePrincipalFromPortfolio"
* target="_top">AWS API Documentation</a>
*/
DisassociatePrincipalFromPortfolioResult disassociatePrincipalFromPortfolio(
DisassociatePrincipalFromPortfolioRequest disassociatePrincipalFromPortfolioRequest);
/**
* <p>
* Disassociates the specified product from the specified portfolio.
* </p>
*
* @param disassociateProductFromPortfolioRequest
* @return Result of the DisassociateProductFromPortfolio operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws ResourceInUseException
* A resource that is currently in use. Ensure that the resource is not in use and retry the operation.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.DisassociateProductFromPortfolio
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DisassociateProductFromPortfolio"
* target="_top">AWS API Documentation</a>
*/
DisassociateProductFromPortfolioResult disassociateProductFromPortfolio(DisassociateProductFromPortfolioRequest disassociateProductFromPortfolioRequest);
/**
* <p>
* Disassociates the specified self-service action association from the specified provisioning artifact.
* </p>
*
* @param disassociateServiceActionFromProvisioningArtifactRequest
* @return Result of the DisassociateServiceActionFromProvisioningArtifact operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DisassociateServiceActionFromProvisioningArtifact
* @see <a
* href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DisassociateServiceActionFromProvisioningArtifact"
* target="_top">AWS API Documentation</a>
*/
DisassociateServiceActionFromProvisioningArtifactResult disassociateServiceActionFromProvisioningArtifact(
DisassociateServiceActionFromProvisioningArtifactRequest disassociateServiceActionFromProvisioningArtifactRequest);
/**
* <p>
* Disassociates the specified TagOption from the specified resource.
* </p>
*
* @param disassociateTagOptionFromResourceRequest
* @return Result of the DisassociateTagOptionFromResource operation returned by the service.
* @throws TagOptionNotMigratedException
* An operation requiring TagOptions failed because the TagOptions migration process has not been performed
* for this account. Please use the AWS console to perform the migration process before retrying the
* operation.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.DisassociateTagOptionFromResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/DisassociateTagOptionFromResource"
* target="_top">AWS API Documentation</a>
*/
DisassociateTagOptionFromResourceResult disassociateTagOptionFromResource(DisassociateTagOptionFromResourceRequest disassociateTagOptionFromResourceRequest);
/**
* <p>
* Enable portfolio sharing feature through AWS Organizations. This API will allow Service Catalog to receive
* updates on your organization in order to sync your shares with the current structure. This API can only be called
* by the master account in the organization.
* </p>
* <p>
* By calling this API Service Catalog will make a call to organizations:EnableAWSServiceAccess on your behalf so
* that your shares can be in sync with any changes in your AWS Organizations structure.
* </p>
*
* @param enableAWSOrganizationsAccessRequest
* @return Result of the EnableAWSOrganizationsAccess operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidStateException
* An attempt was made to modify a resource that is in a state that is not valid. Check your resources to
* ensure that they are in valid states before retrying the operation.
* @throws OperationNotSupportedException
* The operation is not supported.
* @sample AWSServiceCatalog.EnableAWSOrganizationsAccess
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/EnableAWSOrganizationsAccess"
* target="_top">AWS API Documentation</a>
*/
EnableAWSOrganizationsAccessResult enableAWSOrganizationsAccess(EnableAWSOrganizationsAccessRequest enableAWSOrganizationsAccessRequest);
/**
* <p>
* Provisions or modifies a product based on the resource changes for the specified plan.
* </p>
*
* @param executeProvisionedProductPlanRequest
* @return Result of the ExecuteProvisionedProductPlan operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidStateException
* An attempt was made to modify a resource that is in a state that is not valid. Check your resources to
* ensure that they are in valid states before retrying the operation.
* @sample AWSServiceCatalog.ExecuteProvisionedProductPlan
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ExecuteProvisionedProductPlan"
* target="_top">AWS API Documentation</a>
*/
ExecuteProvisionedProductPlanResult executeProvisionedProductPlan(ExecuteProvisionedProductPlanRequest executeProvisionedProductPlanRequest);
/**
* <p>
* Executes a self-service action against a provisioned product.
* </p>
*
* @param executeProvisionedProductServiceActionRequest
* @return Result of the ExecuteProvisionedProductServiceAction operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidStateException
* An attempt was made to modify a resource that is in a state that is not valid. Check your resources to
* ensure that they are in valid states before retrying the operation.
* @sample AWSServiceCatalog.ExecuteProvisionedProductServiceAction
* @see <a
* href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ExecuteProvisionedProductServiceAction"
* target="_top">AWS API Documentation</a>
*/
ExecuteProvisionedProductServiceActionResult executeProvisionedProductServiceAction(
ExecuteProvisionedProductServiceActionRequest executeProvisionedProductServiceActionRequest);
/**
* <p>
* Get the Access Status for AWS Organization portfolio share feature. This API can only be called by the master
* account in the organization.
* </p>
*
* @param getAWSOrganizationsAccessStatusRequest
* @return Result of the GetAWSOrganizationsAccessStatus operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws OperationNotSupportedException
* The operation is not supported.
* @sample AWSServiceCatalog.GetAWSOrganizationsAccessStatus
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/GetAWSOrganizationsAccessStatus"
* target="_top">AWS API Documentation</a>
*/
GetAWSOrganizationsAccessStatusResult getAWSOrganizationsAccessStatus(GetAWSOrganizationsAccessStatusRequest getAWSOrganizationsAccessStatusRequest);
/**
* <p>
* Lists all portfolios for which sharing was accepted by this account.
* </p>
*
* @param listAcceptedPortfolioSharesRequest
* @return Result of the ListAcceptedPortfolioShares operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws OperationNotSupportedException
* The operation is not supported.
* @sample AWSServiceCatalog.ListAcceptedPortfolioShares
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListAcceptedPortfolioShares"
* target="_top">AWS API Documentation</a>
*/
ListAcceptedPortfolioSharesResult listAcceptedPortfolioShares(ListAcceptedPortfolioSharesRequest listAcceptedPortfolioSharesRequest);
/**
* <p>
* Lists all the budgets associated to the specified resource.
* </p>
*
* @param listBudgetsForResourceRequest
* @return Result of the ListBudgetsForResource operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.ListBudgetsForResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListBudgetsForResource"
* target="_top">AWS API Documentation</a>
*/
ListBudgetsForResourceResult listBudgetsForResource(ListBudgetsForResourceRequest listBudgetsForResourceRequest);
/**
* <p>
* Lists the constraints for the specified portfolio and product.
* </p>
*
* @param listConstraintsForPortfolioRequest
* @return Result of the ListConstraintsForPortfolio operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.ListConstraintsForPortfolio
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListConstraintsForPortfolio"
* target="_top">AWS API Documentation</a>
*/
ListConstraintsForPortfolioResult listConstraintsForPortfolio(ListConstraintsForPortfolioRequest listConstraintsForPortfolioRequest);
/**
* <p>
* Lists the paths to the specified product. A path is how the user has access to a specified product, and is
* necessary when provisioning a product. A path also determines the constraints put on the product.
* </p>
*
* @param listLaunchPathsRequest
* @return Result of the ListLaunchPaths operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.ListLaunchPaths
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListLaunchPaths" target="_top">AWS
* API Documentation</a>
*/
ListLaunchPathsResult listLaunchPaths(ListLaunchPathsRequest listLaunchPathsRequest);
/**
* <p>
* Lists the organization nodes that have access to the specified portfolio. This API can only be called by the
* master account in the organization.
* </p>
*
* @param listOrganizationPortfolioAccessRequest
* @return Result of the ListOrganizationPortfolioAccess operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws OperationNotSupportedException
* The operation is not supported.
* @sample AWSServiceCatalog.ListOrganizationPortfolioAccess
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListOrganizationPortfolioAccess"
* target="_top">AWS API Documentation</a>
*/
ListOrganizationPortfolioAccessResult listOrganizationPortfolioAccess(ListOrganizationPortfolioAccessRequest listOrganizationPortfolioAccessRequest);
/**
* <p>
* Lists the account IDs that have access to the specified portfolio.
* </p>
*
* @param listPortfolioAccessRequest
* @return Result of the ListPortfolioAccess operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.ListPortfolioAccess
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListPortfolioAccess"
* target="_top">AWS API Documentation</a>
*/
ListPortfolioAccessResult listPortfolioAccess(ListPortfolioAccessRequest listPortfolioAccessRequest);
/**
* <p>
* Lists all portfolios in the catalog.
* </p>
*
* @param listPortfoliosRequest
* @return Result of the ListPortfolios operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.ListPortfolios
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListPortfolios" target="_top">AWS
* API Documentation</a>
*/
ListPortfoliosResult listPortfolios(ListPortfoliosRequest listPortfoliosRequest);
/**
* <p>
* Lists all portfolios that the specified product is associated with.
* </p>
*
* @param listPortfoliosForProductRequest
* @return Result of the ListPortfoliosForProduct operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.ListPortfoliosForProduct
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListPortfoliosForProduct"
* target="_top">AWS API Documentation</a>
*/
ListPortfoliosForProductResult listPortfoliosForProduct(ListPortfoliosForProductRequest listPortfoliosForProductRequest);
/**
* <p>
* Lists all principal ARNs associated with the specified portfolio.
* </p>
*
* @param listPrincipalsForPortfolioRequest
* @return Result of the ListPrincipalsForPortfolio operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.ListPrincipalsForPortfolio
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListPrincipalsForPortfolio"
* target="_top">AWS API Documentation</a>
*/
ListPrincipalsForPortfolioResult listPrincipalsForPortfolio(ListPrincipalsForPortfolioRequest listPrincipalsForPortfolioRequest);
/**
* <p>
* Lists the plans for the specified provisioned product or all plans to which the user has access.
* </p>
*
* @param listProvisionedProductPlansRequest
* @return Result of the ListProvisionedProductPlans operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.ListProvisionedProductPlans
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListProvisionedProductPlans"
* target="_top">AWS API Documentation</a>
*/
ListProvisionedProductPlansResult listProvisionedProductPlans(ListProvisionedProductPlansRequest listProvisionedProductPlansRequest);
/**
* <p>
* Lists all provisioning artifacts (also known as versions) for the specified product.
* </p>
*
* @param listProvisioningArtifactsRequest
* @return Result of the ListProvisioningArtifacts operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.ListProvisioningArtifacts
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListProvisioningArtifacts"
* target="_top">AWS API Documentation</a>
*/
ListProvisioningArtifactsResult listProvisioningArtifacts(ListProvisioningArtifactsRequest listProvisioningArtifactsRequest);
/**
* <p>
* Lists all provisioning artifacts (also known as versions) for the specified self-service action.
* </p>
*
* @param listProvisioningArtifactsForServiceActionRequest
* @return Result of the ListProvisioningArtifactsForServiceAction operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.ListProvisioningArtifactsForServiceAction
* @see <a
* href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListProvisioningArtifactsForServiceAction"
* target="_top">AWS API Documentation</a>
*/
ListProvisioningArtifactsForServiceActionResult listProvisioningArtifactsForServiceAction(
ListProvisioningArtifactsForServiceActionRequest listProvisioningArtifactsForServiceActionRequest);
/**
* <p>
* Lists the specified requests or all performed requests.
* </p>
*
* @param listRecordHistoryRequest
* @return Result of the ListRecordHistory operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.ListRecordHistory
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListRecordHistory"
* target="_top">AWS API Documentation</a>
*/
ListRecordHistoryResult listRecordHistory(ListRecordHistoryRequest listRecordHistoryRequest);
/**
* <p>
* Lists the resources associated with the specified TagOption.
* </p>
*
* @param listResourcesForTagOptionRequest
* @return Result of the ListResourcesForTagOption operation returned by the service.
* @throws TagOptionNotMigratedException
* An operation requiring TagOptions failed because the TagOptions migration process has not been performed
* for this account. Please use the AWS console to perform the migration process before retrying the
* operation.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.ListResourcesForTagOption
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListResourcesForTagOption"
* target="_top">AWS API Documentation</a>
*/
ListResourcesForTagOptionResult listResourcesForTagOption(ListResourcesForTagOptionRequest listResourcesForTagOptionRequest);
/**
* <p>
* Lists all self-service actions.
* </p>
*
* @param listServiceActionsRequest
* @return Result of the ListServiceActions operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.ListServiceActions
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListServiceActions"
* target="_top">AWS API Documentation</a>
*/
ListServiceActionsResult listServiceActions(ListServiceActionsRequest listServiceActionsRequest);
/**
* <p>
* Returns a paginated list of self-service actions associated with the specified Product ID and Provisioning
* Artifact ID.
* </p>
*
* @param listServiceActionsForProvisioningArtifactRequest
* @return Result of the ListServiceActionsForProvisioningArtifact operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.ListServiceActionsForProvisioningArtifact
* @see <a
* href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListServiceActionsForProvisioningArtifact"
* target="_top">AWS API Documentation</a>
*/
ListServiceActionsForProvisioningArtifactResult listServiceActionsForProvisioningArtifact(
ListServiceActionsForProvisioningArtifactRequest listServiceActionsForProvisioningArtifactRequest);
/**
* <p>
* Returns summary information about stack instances that are associated with the specified
* <code>CFN_STACKSET</code> type provisioned product. You can filter for stack instances that are associated with a
* specific AWS account name or region.
* </p>
*
* @param listStackInstancesForProvisionedProductRequest
* @return Result of the ListStackInstancesForProvisionedProduct operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.ListStackInstancesForProvisionedProduct
* @see <a
* href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListStackInstancesForProvisionedProduct"
* target="_top">AWS API Documentation</a>
*/
ListStackInstancesForProvisionedProductResult listStackInstancesForProvisionedProduct(
ListStackInstancesForProvisionedProductRequest listStackInstancesForProvisionedProductRequest);
/**
* <p>
* Lists the specified TagOptions or all TagOptions.
* </p>
*
* @param listTagOptionsRequest
* @return Result of the ListTagOptions operation returned by the service.
* @throws TagOptionNotMigratedException
* An operation requiring TagOptions failed because the TagOptions migration process has not been performed
* for this account. Please use the AWS console to perform the migration process before retrying the
* operation.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.ListTagOptions
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ListTagOptions" target="_top">AWS
* API Documentation</a>
*/
ListTagOptionsResult listTagOptions(ListTagOptionsRequest listTagOptionsRequest);
/**
* <p>
* Provisions the specified product.
* </p>
* <p>
* A provisioned product is a resourced instance of a product. For example, provisioning a product based on a
* CloudFormation template launches a CloudFormation stack and its underlying resources. You can check the status of
* this request using <a>DescribeRecord</a>.
* </p>
* <p>
* If the request contains a tag key with an empty list of values, there is a tag conflict for that key. Do not
* include conflicted keys as tags, or this causes the error
* "Parameter validation failed: Missing required parameter in Tags[<i>N</i>]:<i>Value</i>".
* </p>
*
* @param provisionProductRequest
* @return Result of the ProvisionProduct operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws DuplicateResourceException
* The specified resource is a duplicate.
* @sample AWSServiceCatalog.ProvisionProduct
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ProvisionProduct"
* target="_top">AWS API Documentation</a>
*/
ProvisionProductResult provisionProduct(ProvisionProductRequest provisionProductRequest);
/**
* <p>
* Rejects an offer to share the specified portfolio.
* </p>
*
* @param rejectPortfolioShareRequest
* @return Result of the RejectPortfolioShare operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.RejectPortfolioShare
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/RejectPortfolioShare"
* target="_top">AWS API Documentation</a>
*/
RejectPortfolioShareResult rejectPortfolioShare(RejectPortfolioShareRequest rejectPortfolioShareRequest);
/**
* <p>
* Lists the provisioned products that are available (not terminated).
* </p>
* <p>
* To use additional filtering, see <a>SearchProvisionedProducts</a>.
* </p>
*
* @param scanProvisionedProductsRequest
* @return Result of the ScanProvisionedProducts operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.ScanProvisionedProducts
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/ScanProvisionedProducts"
* target="_top">AWS API Documentation</a>
*/
ScanProvisionedProductsResult scanProvisionedProducts(ScanProvisionedProductsRequest scanProvisionedProductsRequest);
/**
* <p>
* Gets information about the products to which the caller has access.
* </p>
*
* @param searchProductsRequest
* @return Result of the SearchProducts operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.SearchProducts
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/SearchProducts" target="_top">AWS
* API Documentation</a>
*/
SearchProductsResult searchProducts(SearchProductsRequest searchProductsRequest);
/**
* <p>
* Gets information about the products for the specified portfolio or all products.
* </p>
*
* @param searchProductsAsAdminRequest
* @return Result of the SearchProductsAsAdmin operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.SearchProductsAsAdmin
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/SearchProductsAsAdmin"
* target="_top">AWS API Documentation</a>
*/
SearchProductsAsAdminResult searchProductsAsAdmin(SearchProductsAsAdminRequest searchProductsAsAdminRequest);
/**
* <p>
* Gets information about the provisioned products that meet the specified criteria.
* </p>
*
* @param searchProvisionedProductsRequest
* @return Result of the SearchProvisionedProducts operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.SearchProvisionedProducts
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/SearchProvisionedProducts"
* target="_top">AWS API Documentation</a>
*/
SearchProvisionedProductsResult searchProvisionedProducts(SearchProvisionedProductsRequest searchProvisionedProductsRequest);
/**
* <p>
* Terminates the specified provisioned product.
* </p>
* <p>
* This operation does not delete any records associated with the provisioned product.
* </p>
* <p>
* You can check the status of this request using <a>DescribeRecord</a>.
* </p>
*
* @param terminateProvisionedProductRequest
* @return Result of the TerminateProvisionedProduct operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.TerminateProvisionedProduct
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/TerminateProvisionedProduct"
* target="_top">AWS API Documentation</a>
*/
TerminateProvisionedProductResult terminateProvisionedProduct(TerminateProvisionedProductRequest terminateProvisionedProductRequest);
/**
* <p>
* Updates the specified constraint.
* </p>
*
* @param updateConstraintRequest
* @return Result of the UpdateConstraint operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.UpdateConstraint
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/UpdateConstraint"
* target="_top">AWS API Documentation</a>
*/
UpdateConstraintResult updateConstraint(UpdateConstraintRequest updateConstraintRequest);
/**
* <p>
* Updates the specified portfolio.
* </p>
* <p>
* You cannot update a product that was shared with you.
* </p>
*
* @param updatePortfolioRequest
* @return Result of the UpdatePortfolio operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws LimitExceededException
* The current limits of the service would have been exceeded by this operation. Decrease your resource use
* or increase your service limits and retry the operation.
* @throws TagOptionNotMigratedException
* An operation requiring TagOptions failed because the TagOptions migration process has not been performed
* for this account. Please use the AWS console to perform the migration process before retrying the
* operation.
* @sample AWSServiceCatalog.UpdatePortfolio
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/UpdatePortfolio" target="_top">AWS
* API Documentation</a>
*/
UpdatePortfolioResult updatePortfolio(UpdatePortfolioRequest updatePortfolioRequest);
/**
* <p>
* Updates the specified product.
* </p>
*
* @param updateProductRequest
* @return Result of the UpdateProduct operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws TagOptionNotMigratedException
* An operation requiring TagOptions failed because the TagOptions migration process has not been performed
* for this account. Please use the AWS console to perform the migration process before retrying the
* operation.
* @sample AWSServiceCatalog.UpdateProduct
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/UpdateProduct" target="_top">AWS
* API Documentation</a>
*/
UpdateProductResult updateProduct(UpdateProductRequest updateProductRequest);
/**
* <p>
* Requests updates to the configuration of the specified provisioned product.
* </p>
* <p>
* If there are tags associated with the object, they cannot be updated or added. Depending on the specific updates
* requested, this operation can update with no interruption, with some interruption, or replace the provisioned
* product entirely.
* </p>
* <p>
* You can check the status of this request using <a>DescribeRecord</a>.
* </p>
*
* @param updateProvisionedProductRequest
* @return Result of the UpdateProvisionedProduct operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @sample AWSServiceCatalog.UpdateProvisionedProduct
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/UpdateProvisionedProduct"
* target="_top">AWS API Documentation</a>
*/
UpdateProvisionedProductResult updateProvisionedProduct(UpdateProvisionedProductRequest updateProvisionedProductRequest);
/**
* <p>
* Requests updates to the properties of the specified provisioned product.
* </p>
*
* @param updateProvisionedProductPropertiesRequest
* @return Result of the UpdateProvisionedProductProperties operation returned by the service.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidStateException
* An attempt was made to modify a resource that is in a state that is not valid. Check your resources to
* ensure that they are in valid states before retrying the operation.
* @sample AWSServiceCatalog.UpdateProvisionedProductProperties
* @see <a
* href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/UpdateProvisionedProductProperties"
* target="_top">AWS API Documentation</a>
*/
UpdateProvisionedProductPropertiesResult updateProvisionedProductProperties(
UpdateProvisionedProductPropertiesRequest updateProvisionedProductPropertiesRequest);
/**
* <p>
* Updates the specified provisioning artifact (also known as a version) for the specified product.
* </p>
* <p>
* You cannot update a provisioning artifact for a product that was shared with you.
* </p>
*
* @param updateProvisioningArtifactRequest
* @return Result of the UpdateProvisioningArtifact operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.UpdateProvisioningArtifact
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/UpdateProvisioningArtifact"
* target="_top">AWS API Documentation</a>
*/
UpdateProvisioningArtifactResult updateProvisioningArtifact(UpdateProvisioningArtifactRequest updateProvisioningArtifactRequest);
/**
* <p>
* Updates a self-service action.
* </p>
*
* @param updateServiceActionRequest
* @return Result of the UpdateServiceAction operation returned by the service.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.UpdateServiceAction
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/UpdateServiceAction"
* target="_top">AWS API Documentation</a>
*/
UpdateServiceActionResult updateServiceAction(UpdateServiceActionRequest updateServiceActionRequest);
/**
* <p>
* Updates the specified TagOption.
* </p>
*
* @param updateTagOptionRequest
* @return Result of the UpdateTagOption operation returned by the service.
* @throws TagOptionNotMigratedException
* An operation requiring TagOptions failed because the TagOptions migration process has not been performed
* for this account. Please use the AWS console to perform the migration process before retrying the
* operation.
* @throws ResourceNotFoundException
* The specified resource was not found.
* @throws DuplicateResourceException
* The specified resource is a duplicate.
* @throws InvalidParametersException
* One or more parameters provided to the operation are not valid.
* @sample AWSServiceCatalog.UpdateTagOption
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/servicecatalog-2015-12-10/UpdateTagOption" target="_top">AWS
* API Documentation</a>
*/
UpdateTagOptionResult updateTagOption(UpdateTagOptionRequest updateTagOptionRequest);
/**
* Shuts down this client object, releasing any resources that might be held open. This is an optional method, and
* callers are not expected to call it, but can if they want to explicitly release any open resources. Once a client
* has been shutdown, it should not be used to make any more requests.
*/
void shutdown();
/**
* Returns additional metadata for a previously executed successful request, typically used for debugging issues
* where a service isn't acting as expected. This data isn't considered part of the result data returned by an
* operation, so it's available through this separate, diagnostic interface.
* <p>
* Response metadata is only cached for a limited period of time, so if you need to access this extra diagnostic
* information for an executed request, you should use this method to retrieve it as soon as possible after
* executing a request.
*
* @param request
* The originally executed request.
*
* @return The response metadata for the specified request, or null if none is available.
*/
ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request);
}
| apache-2.0 |
sunzhongqiang/mall | src/main/java/com/mmk/goods/condition/SkuCondition.java | 368 | /*
*
* SkuCondition 创建于 2017-04-18 11:24:46 版权归作者和作者当前组织所有
*/
package com.mmk.goods.condition;
import java.util.Date;
import com.mmk.goods.model.Sku;
/**
* SkuCondition : 商品SKU 扩展查询模型
* 2017-04-18 11:24:46
*@author codegenerator
*@version 1.0
*
*/
public class SkuCondition extends Sku{
} | apache-2.0 |
osswangxining/iotplatform | iot-infomgt/iot-infomgt-dao/src/main/java/org/iotp/infomgt/dao/model/nosql/DashboardInfoEntity.java | 7215 | /*******************************************************************************
* Copyright 2017 osswangxining@163.com
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
******************************************************************************/
/**
* Copyright © 2016-2017 The Thingsboard 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.iotp.infomgt.dao.model.nosql;
import static org.iotp.infomgt.dao.model.ModelConstants.DASHBOARD_COLUMN_FAMILY_NAME;
import static org.iotp.infomgt.dao.model.ModelConstants.DASHBOARD_CUSTOMER_ID_PROPERTY;
import static org.iotp.infomgt.dao.model.ModelConstants.DASHBOARD_TENANT_ID_PROPERTY;
import static org.iotp.infomgt.dao.model.ModelConstants.DASHBOARD_TITLE_PROPERTY;
import static org.iotp.infomgt.dao.model.ModelConstants.ID_PROPERTY;
import static org.iotp.infomgt.dao.model.ModelConstants.SEARCH_TEXT_PROPERTY;
import java.util.UUID;
import org.iotp.infomgt.dao.model.SearchTextEntity;
import org.iotp.infomgt.data.DashboardInfo;
import org.iotp.infomgt.data.id.CustomerId;
import org.iotp.infomgt.data.id.DashboardId;
import org.iotp.infomgt.data.id.TenantId;
import com.datastax.driver.core.utils.UUIDs;
import com.datastax.driver.mapping.annotations.Column;
import com.datastax.driver.mapping.annotations.PartitionKey;
import com.datastax.driver.mapping.annotations.Table;
import com.datastax.driver.mapping.annotations.Transient;
@Table(name = DASHBOARD_COLUMN_FAMILY_NAME)
public class DashboardInfoEntity implements SearchTextEntity<DashboardInfo> {
@Transient
private static final long serialVersionUID = 2998395951247446191L;
@PartitionKey(value = 0)
@Column(name = ID_PROPERTY)
private UUID id;
@PartitionKey(value = 1)
@Column(name = DASHBOARD_TENANT_ID_PROPERTY)
private UUID tenantId;
@PartitionKey(value = 2)
@Column(name = DASHBOARD_CUSTOMER_ID_PROPERTY)
private UUID customerId;
@Column(name = DASHBOARD_TITLE_PROPERTY)
private String title;
@Column(name = SEARCH_TEXT_PROPERTY)
private String searchText;
public DashboardInfoEntity() {
super();
}
public DashboardInfoEntity(DashboardInfo dashboardInfo) {
if (dashboardInfo.getId() != null) {
this.id = dashboardInfo.getId().getId();
}
if (dashboardInfo.getTenantId() != null) {
this.tenantId = dashboardInfo.getTenantId().getId();
}
if (dashboardInfo.getCustomerId() != null) {
this.customerId = dashboardInfo.getCustomerId().getId();
}
this.title = dashboardInfo.getTitle();
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public UUID getTenantId() {
return tenantId;
}
public void setTenantId(UUID tenantId) {
this.tenantId = tenantId;
}
public UUID getCustomerId() {
return customerId;
}
public void setCustomerId(UUID customerId) {
this.customerId = customerId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String getSearchTextSource() {
return title;
}
@Override
public void setSearchText(String searchText) {
this.searchText = searchText;
}
public String getSearchText() {
return searchText;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((customerId == null) ? 0 : customerId.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((searchText == null) ? 0 : searchText.hashCode());
result = prime * result + ((tenantId == null) ? 0 : tenantId.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DashboardInfoEntity other = (DashboardInfoEntity) obj;
if (customerId == null) {
if (other.customerId != null)
return false;
} else if (!customerId.equals(other.customerId))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (searchText == null) {
if (other.searchText != null)
return false;
} else if (!searchText.equals(other.searchText))
return false;
if (tenantId == null) {
if (other.tenantId != null)
return false;
} else if (!tenantId.equals(other.tenantId))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DashboardInfoEntity [id=");
builder.append(id);
builder.append(", tenantId=");
builder.append(tenantId);
builder.append(", customerId=");
builder.append(customerId);
builder.append(", title=");
builder.append(title);
builder.append(", searchText=");
builder.append(searchText);
builder.append("]");
return builder.toString();
}
@Override
public DashboardInfo toData() {
DashboardInfo dashboardInfo = new DashboardInfo(new DashboardId(id));
dashboardInfo.setCreatedTime(UUIDs.unixTimestamp(id));
if (tenantId != null) {
dashboardInfo.setTenantId(new TenantId(tenantId));
}
if (customerId != null) {
dashboardInfo.setCustomerId(new CustomerId(customerId));
}
dashboardInfo.setTitle(title);
return dashboardInfo;
}
}
| apache-2.0 |
ernestp/consulo | platform/platform-impl/src/com/intellij/ide/actions/QuickChangeLookAndFeel.java | 2033 | /*
* 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.ide.actions;
import com.intellij.ide.ui.LafManager;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
/**
* @author max
*/
public class QuickChangeLookAndFeel extends QuickSwitchSchemeAction {
@Override
protected void fillActions(Project project, @NotNull DefaultActionGroup group, @NotNull DataContext dataContext) {
final LafManager manager = LafManager.getInstance();
final UIManager.LookAndFeelInfo[] lfs = manager.getInstalledLookAndFeels();
final UIManager.LookAndFeelInfo current = manager.getCurrentLookAndFeel();
for (final UIManager.LookAndFeelInfo lf : lfs) {
group.add(new DumbAwareAction(lf.getName(), "", lf == current ? ourCurrentAction : ourNotCurrentAction) {
@Override
public void actionPerformed(AnActionEvent e) {
final UIManager.LookAndFeelInfo cur = manager.getCurrentLookAndFeel();
if (cur == lf) return;
manager.setCurrentLookAndFeel(lf);
manager.updateUI();
}
});
}
}
@Override
protected boolean isEnabled() {
return LafManager.getInstance().getInstalledLookAndFeels().length > 1;
}
}
| apache-2.0 |
jarekhr/codebreaker | src/main/java/com/jahs/codebreaker/model/PinColor.java | 182 | package com.jahs.codebreaker.model;
/**
* Represents a pin color.
*/
public enum PinColor {
RED,
ORANGE,
YELLOW,
GREEN,
BLUE,
WHITE,
BLACK,
PINK
}
| apache-2.0 |
pwalser75/user-auth | keygen/src/main/java/ch/frostnova/keygen/alphabet/impl/SaveAlphanumericAlphabet.java | 478 | package ch.frostnova.keygen.alphabet.impl;
/**
* Alphanumeric alphabet without similar characters (l,I,1, o,O,0 and B,8)
*
* @author pwalser
* @since 20.02.2017
*/
public class SaveAlphanumericAlphabet extends PredefinedAlphabet {
public static void main(String[] args) {
System.out.println(new AlphanumericAlphabet().allChars());
}
public SaveAlphanumericAlphabet() {
super("2345679ACDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz");
}
}
| apache-2.0 |
OpenGamma/Strata | modules/pricer/src/main/java/com/opengamma/strata/pricer/DiscountFactors.java | 20214 | /*
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.pricer;
import static com.opengamma.strata.pricer.SimpleDiscountFactors.EFFECTIVE_ZERO;
import java.time.LocalDate;
import java.util.Optional;
import com.opengamma.strata.basics.currency.Currency;
import com.opengamma.strata.basics.date.DayCount;
import com.opengamma.strata.collect.ArgChecker;
import com.opengamma.strata.collect.Messages;
import com.opengamma.strata.collect.array.DoubleArray;
import com.opengamma.strata.market.MarketDataView;
import com.opengamma.strata.market.ValueType;
import com.opengamma.strata.market.curve.Curve;
import com.opengamma.strata.market.curve.CurveInfoType;
import com.opengamma.strata.market.curve.InterpolatedNodalCurve;
import com.opengamma.strata.market.param.CurrencyParameterSensitivities;
import com.opengamma.strata.market.param.CurrencyParameterSensitivity;
import com.opengamma.strata.market.param.ParameterPerturbation;
import com.opengamma.strata.market.param.ParameterizedData;
/**
* Provides access to discount factors for a single currency.
* <p>
* The discount factor represents the time value of money for the specified currency
* when comparing the valuation date to the specified date.
*/
public interface DiscountFactors
extends MarketDataView, ParameterizedData {
/**
* Obtains an instance from a curve.
* <p>
* The curve is specified by an instance of {@link Curve}, such as {@link InterpolatedNodalCurve}.
* The curve must have x-values of {@linkplain ValueType#YEAR_FRACTION year fractions} with
* the day count specified. The y-values must be {@linkplain ValueType#ZERO_RATE zero rates}
* or {@linkplain ValueType#DISCOUNT_FACTOR discount factors}.
*
* @param currency the currency
* @param valuationDate the valuation date for which the curve is valid
* @param curve the underlying curve
* @return the discount factors view
*/
public static DiscountFactors of(Currency currency, LocalDate valuationDate, Curve curve) {
if (curve.getMetadata().getYValueType().equals(ValueType.DISCOUNT_FACTOR)) {
return SimpleDiscountFactors.of(currency, valuationDate, curve);
}
if (curve.getMetadata().getYValueType().equals(ValueType.ZERO_RATE)) {
Optional<Integer> frequencyOpt = curve.getMetadata().findInfo(CurveInfoType.COMPOUNDING_PER_YEAR);
if (frequencyOpt.isPresent()) {
return ZeroRatePeriodicDiscountFactors.of(currency, valuationDate, curve);
}
return ZeroRateDiscountFactors.of(currency, valuationDate, curve);
}
throw new IllegalArgumentException(Messages.format(
"Unknown value type in discount curve, must be 'DiscountFactor' or 'ZeroRate' but was '{}'",
curve.getMetadata().getYValueType()));
}
//-------------------------------------------------------------------------
/**
* Gets the currency.
* <p>
* The currency that discount factors are provided for.
*
* @return the currency
*/
public abstract Currency getCurrency();
//-------------------------------------------------------------------------
@Override
public abstract DiscountFactors withParameter(int parameterIndex, double newValue);
@Override
public abstract DiscountFactors withPerturbation(ParameterPerturbation perturbation);
//-------------------------------------------------------------------------
/**
* Calculates the relative time between the valuation date and the specified date.
* <p>
* The {@code double} value returned from this method is used as the input to other methods.
* It is typically calculated from a {@link DayCount}.
*
* @param date the date
* @return the year fraction
* @throws RuntimeException if it is not possible to convert dates to relative times
*/
public abstract double relativeYearFraction(LocalDate date);
/**
* Gets the discount factor for the specified date.
* <p>
* The discount factor represents the time value of money for the specified currency
* when comparing the valuation date to the specified date.
* <p>
* If the valuation date is on or after the specified date, the discount factor is 1.
*
* @param date the date to discount to
* @return the discount factor
* @throws RuntimeException if the value cannot be obtained
*/
public default double discountFactor(LocalDate date) {
double yearFraction = relativeYearFraction(date);
return discountFactor(yearFraction);
}
/**
* Gets the discount factor for specified year fraction.
* <p>
* The year fraction must be based on {@code #relativeYearFraction(LocalDate)}.
*
* @param yearFraction the year fraction
* @return the discount factor
* @throws RuntimeException if the value cannot be obtained
*/
public abstract double discountFactor(double yearFraction);
/**
* Returns the discount factor derivative with respect to the year fraction or time.
* <p>
* The year fraction must be based on {@code #relativeYearFraction(LocalDate)}.
*
* @param yearFraction the year fraction
* @return the discount factor derivative
* @throws RuntimeException if the value cannot be obtained
*/
public abstract double discountFactorTimeDerivative(double yearFraction);
/**
* Gets the discount factor for the specified date with z-spread.
* <p>
* The discount factor represents the time value of money for the specified currency
* when comparing the valuation date to the specified date.
* <p>
* The z-spread is a parallel shift applied to continuously compounded rates or periodic
* compounded rates of the discounting curve.
* <p>
* If the valuation date is on or after the specified date, the discount factor is 1.
*
* @param date the date to discount to
* @param zSpread the z-spread
* @param compoundedRateType the compounded rate type
* @param periodsPerYear the number of periods per year
* @return the discount factor
* @throws RuntimeException if the value cannot be obtained
*/
public default double discountFactorWithSpread(
LocalDate date,
double zSpread,
CompoundedRateType compoundedRateType,
int periodsPerYear) {
double yearFraction = relativeYearFraction(date);
return discountFactorWithSpread(yearFraction, zSpread, compoundedRateType, periodsPerYear);
}
/**
* Gets the discount factor for the specified year fraction with z-spread.
* <p>
* The discount factor represents the time value of money for the specified currency
* when comparing the valuation date to the specified date.
* <p>
* The z-spread is a parallel shift applied to continuously compounded rates or periodic
* compounded rates of the discounting curve.
* <p>
* If the valuation date is on or after the specified date, the discount factor is 1.
* <p>
* The year fraction must be based on {@code #relativeYearFraction(LocalDate)}.
*
* @param yearFraction the year fraction
* @param zSpread the z-spread
* @param compoundedRateType the compounded rate type
* @param periodsPerYear the number of periods per year
* @return the discount factor
* @throws RuntimeException if the value cannot be obtained
*/
public default double discountFactorWithSpread(
double yearFraction,
double zSpread,
CompoundedRateType compoundedRateType,
int periodsPerYear) {
if (Math.abs(yearFraction) < EFFECTIVE_ZERO) {
return 1d;
}
double df = discountFactor(yearFraction);
if (compoundedRateType.equals(CompoundedRateType.PERIODIC)) {
ArgChecker.notNegativeOrZero(periodsPerYear, "periodPerYear");
double ratePeriodicAnnualPlusOne =
Math.pow(df, -1.0 / periodsPerYear / yearFraction) + zSpread / periodsPerYear;
return Math.pow(ratePeriodicAnnualPlusOne, -periodsPerYear * yearFraction);
} else {
return df * Math.exp(-zSpread * yearFraction);
}
}
/**
* Gets the continuously compounded zero rate for the specified date.
* <p>
* The continuously compounded zero rate is coherent to {@link #discountFactor(LocalDate)} along with
* year fraction which is computed internally in each implementation.
*
* @param date the date to discount to
* @return the zero rate
* @throws RuntimeException if the value cannot be obtained
*/
public default double zeroRate(LocalDate date) {
double yearFraction = relativeYearFraction(date);
return zeroRate(yearFraction);
}
/**
* Gets the continuously compounded zero rate for specified year fraction.
* <p>
* The year fraction must be based on {@code #relativeYearFraction(LocalDate)}.
*
* @param yearFraction the year fraction
* @return the zero rate
* @throws RuntimeException if the value cannot be obtained
*/
public abstract double zeroRate(double yearFraction);
//-------------------------------------------------------------------------
/**
* Calculates the zero rate point sensitivity at the specified date.
* <p>
* This returns a sensitivity instance referring to the zero rate sensitivity of the
* points that were queried in the market data.
* The sensitivity typically has the value {@code (-discountFactor * yearFraction)}.
* The sensitivity refers to the result of {@link #discountFactor(LocalDate)}.
*
* @param date the date to discount to
* @return the point sensitivity of the zero rate
* @throws RuntimeException if the result cannot be calculated
*/
public default ZeroRateSensitivity zeroRatePointSensitivity(LocalDate date) {
double yearFraction = relativeYearFraction(date);
return zeroRatePointSensitivity(yearFraction);
}
/**
* Calculates the zero rate point sensitivity at the specified year fraction.
* <p>
* This returns a sensitivity instance referring to the zero rate sensitivity of the
* points that were queried in the market data.
* The sensitivity typically has the value {@code (-discountFactor * yearFraction)}.
* The sensitivity refers to the result of {@link #discountFactor(LocalDate)}.
* <p>
* The year fraction must be based on {@code #relativeYearFraction(LocalDate)}.
*
* @param yearFraction the year fraction
* @return the point sensitivity of the zero rate
* @throws RuntimeException if the result cannot be calculated
*/
public default ZeroRateSensitivity zeroRatePointSensitivity(double yearFraction) {
return zeroRatePointSensitivity(yearFraction, getCurrency());
}
/**
* Calculates the zero rate point sensitivity at the specified date specifying the currency of the sensitivity.
* <p>
* This returns a sensitivity instance referring to the zero rate sensitivity of the
* points that were queried in the market data.
* The sensitivity typically has the value {@code (-discountFactor * yearFraction)}.
* The sensitivity refers to the result of {@link #discountFactor(LocalDate)}.
* <p>
* This method allows the currency of the sensitivity to differ from the currency of the market data.
*
* @param date the date to discount to
* @param sensitivityCurrency the currency of the sensitivity
* @return the point sensitivity of the zero rate
* @throws RuntimeException if the result cannot be calculated
*/
public default ZeroRateSensitivity zeroRatePointSensitivity(LocalDate date, Currency sensitivityCurrency) {
double yearFraction = relativeYearFraction(date);
return zeroRatePointSensitivity(yearFraction, sensitivityCurrency);
}
/**
* Calculates the zero rate point sensitivity at the specified year fraction specifying the currency of the sensitivity.
* <p>
* This returns a sensitivity instance referring to the zero rate sensitivity of the
* points that were queried in the market data.
* The sensitivity typically has the value {@code (-discountFactor * yearFraction)}.
* The sensitivity refers to the result of {@link #discountFactor(LocalDate)}.
* <p>
* This method allows the currency of the sensitivity to differ from the currency of the market data.
* <p>
* The year fraction must be based on {@code #relativeYearFraction(LocalDate)}.
*
* @param yearFraction the year fraction
* @param sensitivityCurrency the currency of the sensitivity
* @return the point sensitivity of the zero rate
* @throws RuntimeException if the result cannot be calculated
*/
public abstract ZeroRateSensitivity zeroRatePointSensitivity(double yearFraction, Currency sensitivityCurrency);
//-------------------------------------------------------------------------
/**
* Calculates the zero rate point sensitivity with z-spread at the specified date.
* <p>
* This returns a sensitivity instance referring to the zero rate sensitivity of the
* points that were queried in the market data.
* The sensitivity refers to the result of {@link #discountFactorWithSpread(LocalDate, double, CompoundedRateType, int)}.
* <p>
* The z-spread is a parallel shift applied to continuously compounded rates or periodic
* compounded rates of the discounting curve.
*
* @param date the date to discount to
* @param zSpread the z-spread
* @param compoundedRateType the compounded rate type
* @param periodsPerYear the number of periods per year
* @return the point sensitivity of the zero rate
* @throws RuntimeException if the result cannot be calculated
*/
public default ZeroRateSensitivity zeroRatePointSensitivityWithSpread(
LocalDate date,
double zSpread,
CompoundedRateType compoundedRateType,
int periodsPerYear) {
double yearFraction = relativeYearFraction(date);
return zeroRatePointSensitivityWithSpread(yearFraction, zSpread, compoundedRateType, periodsPerYear);
}
/**
* Calculates the zero rate point sensitivity with z-spread at the specified year fraction.
* <p>
* This returns a sensitivity instance referring to the zero rate sensitivity of the
* points that were queried in the market data.
* The sensitivity refers to the result of {@link #discountFactorWithSpread(LocalDate, double, CompoundedRateType, int)}.
* <p>
* The z-spread is a parallel shift applied to continuously compounded rates or periodic
* compounded rates of the discounting curve.
* <p>
* The year fraction must be based on {@code #relativeYearFraction(LocalDate)}.
*
* @param yearFraction the year fraction
* @param zSpread the z-spread
* @param compoundedRateType the compounded rate type
* @param periodsPerYear the number of periods per year
* @return the point sensitivity of the zero rate
* @throws RuntimeException if the result cannot be calculated
*/
public default ZeroRateSensitivity zeroRatePointSensitivityWithSpread(
double yearFraction,
double zSpread,
CompoundedRateType compoundedRateType,
int periodsPerYear) {
return zeroRatePointSensitivityWithSpread(yearFraction, getCurrency(), zSpread, compoundedRateType, periodsPerYear);
}
/**
* Calculates the zero rate point sensitivity with z-spread at the specified date specifying
* the currency of the sensitivity.
* <p>
* This returns a sensitivity instance referring to the zero rate sensitivity of the
* points that were queried in the market data.
* The sensitivity refers to the result of {@link #discountFactorWithSpread(LocalDate, double, CompoundedRateType, int)}.
* <p>
* The z-spread is a parallel shift applied to continuously compounded rates or periodic
* compounded rates of the discounting curve.
* <p>
* This method allows the currency of the sensitivity to differ from the currency of the market data.
*
* @param date the date to discount to
* @param sensitivityCurrency the currency of the sensitivity
* @param zSpread the z-spread
* @param compoundedRateType the compounded rate type
* @param periodsPerYear the number of periods per year
* @return the point sensitivity of the zero rate
* @throws RuntimeException if the result cannot be calculated
*/
public default ZeroRateSensitivity zeroRatePointSensitivityWithSpread(
LocalDate date,
Currency sensitivityCurrency,
double zSpread,
CompoundedRateType compoundedRateType,
int periodsPerYear) {
double yearFraction = relativeYearFraction(date);
return zeroRatePointSensitivityWithSpread(yearFraction, sensitivityCurrency, zSpread, compoundedRateType, periodsPerYear);
}
/**
* Calculates the zero rate point sensitivity with z-spread at the specified year fraction specifying
* the currency of the sensitivity.
* <p>
* This returns a sensitivity instance referring to the zero rate sensitivity of the
* points that were queried in the market data.
* The sensitivity refers to the result of {@link #discountFactorWithSpread(LocalDate, double, CompoundedRateType, int)}.
* <p>
* The z-spread is a parallel shift applied to continuously compounded rates or periodic
* compounded rates of the discounting curve.
* <p>
* This method allows the currency of the sensitivity to differ from the currency of the market data.
* <p>
* The year fraction must be based on {@code #relativeYearFraction(LocalDate)}.
*
* @param yearFraction the year fraction
* @param sensitivityCurrency the currency of the sensitivity
* @param zSpread the z-spread
* @param compoundedRateType the compounded rate type
* @param periodsPerYear the number of periods per year
* @return the point sensitivity of the zero rate
* @throws RuntimeException if the result cannot be calculated
*/
public default ZeroRateSensitivity zeroRatePointSensitivityWithSpread(
double yearFraction,
Currency sensitivityCurrency,
double zSpread,
CompoundedRateType compoundedRateType,
int periodsPerYear) {
ZeroRateSensitivity sensi = zeroRatePointSensitivity(yearFraction, sensitivityCurrency);
if (Math.abs(yearFraction) < EFFECTIVE_ZERO) {
return sensi;
}
double factor;
if (compoundedRateType.equals(CompoundedRateType.PERIODIC)) {
double df = discountFactor(yearFraction);
double dfRoot = Math.pow(df, -1d / periodsPerYear / yearFraction);
factor = dfRoot / df / Math.pow(dfRoot + zSpread / periodsPerYear, periodsPerYear * yearFraction + 1d);
} else {
factor = Math.exp(-zSpread * yearFraction);
}
return sensi.multipliedBy(factor);
}
//-------------------------------------------------------------------------
/**
* Calculates the parameter sensitivity from the point sensitivity.
* <p>
* This is used to convert a single point sensitivity to parameter sensitivity.
* The calculation typically involves multiplying the point and unit sensitivities.
*
* @param pointSensitivity the point sensitivity to convert
* @return the parameter sensitivity
* @throws RuntimeException if the result cannot be calculated
*/
public abstract CurrencyParameterSensitivities parameterSensitivity(ZeroRateSensitivity pointSensitivity);
/**
* Creates the parameter sensitivity when the sensitivity values are known.
* <p>
* In most cases, {@link #parameterSensitivity(ZeroRateSensitivity)} should be used and manipulated.
* However, it can be useful to create parameter sensitivity from pre-computed sensitivity values.
* <p>
* There will typically be one {@link CurrencyParameterSensitivity} for each underlying data
* structure, such as a curve. For example, if the discount factors are based on a single discount
* curve, then there will be one {@code CurrencyParameterSensitivity} in the result.
*
* @param currency the currency
* @param sensitivities the sensitivity values, which must match the parameter count
* @return the parameter sensitivity
* @throws RuntimeException if the result cannot be calculated
*/
public abstract CurrencyParameterSensitivities createParameterSensitivity(Currency currency, DoubleArray sensitivities);
}
| apache-2.0 |
Loofer/BaseNetWork | app/src/main/java/org/loofer/retrofit/utils/Preconditions.java | 998 | package org.loofer.retrofit.utils;
import android.support.annotation.Nullable;
/**
* ============================================================
* 版权: xx有限公司 版权所有(c)2017
* <p>
* 作者:Loofer
* 版本:1.0
* 创建日期 :2017/2/26 10:42.
* 描述:
* <p>
* 注:如果您修改了本类请填写以下内容作为记录,如非本人操作劳烦通知,谢谢!!!
* Modified Date Modify Content:
* <p>
* ==========================================================
*/
public class Preconditions {
private Preconditions() {
}
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}
}
| apache-2.0 |
GerardPaligot/ZMessenger | app/src/main/java/org/randoomz/zdsmessenger/pm/queries/NewPrivateTopicQueryParameter.java | 680 | package org.randoomz.zdsmessenger.pm.queries;
import org.randoomz.zdsmessenger.internal.query.Parameter;
import java.util.List;
/**
* Created by gerard on 27/09/2015.
*/
public final class NewPrivateTopicQueryParameter implements Parameter {
public final String token;
public final String title;
public final String subtitle;
public final List<Integer> participants;
public final String text;
public NewPrivateTopicQueryParameter(String token, String title, String subtitle, List<Integer> participants, String text) {
this.token = token;
this.title = title;
this.subtitle = subtitle;
this.participants = participants;
this.text = text;
}
}
| apache-2.0 |
BlesseNtumble/GalaxySpace | src/main/java/galaxyspace/systems/BarnardsSystem/planets/barnarda_c/world/gen/we/Barnarda_C_Mountains.java | 6077 | package galaxyspace.systems.BarnardsSystem.planets.barnarda_c.world.gen.we;
import java.util.Random;
import asmodeuscore.core.utils.worldengine.WE_Biome;
import asmodeuscore.core.utils.worldengine.standardcustomgen.WE_BiomeLayer;
import asmodeuscore.core.utils.worldengine.standardcustomgen.WE_OreGen.BlockPredicate;
import asmodeuscore.core.utils.worldengine.standardcustomgen.WE_SnowGen;
import galaxyspace.systems.BarnardsSystem.core.BRBlocks;
import galaxyspace.systems.BarnardsSystem.planets.barnarda_c.blocks.Barnarda_C_Blocks;
import galaxyspace.systems.BarnardsSystem.planets.barnarda_c.blocks.Barnarda_C_Dandelions;
import galaxyspace.systems.BarnardsSystem.planets.barnarda_c.blocks.Barnarda_C_Grass;
import galaxyspace.systems.BarnardsSystem.planets.barnarda_c.world.gen.WorldGenTree_Small;
import net.minecraft.block.material.Material;
import net.minecraft.entity.monster.EntityEnderman;
import net.minecraft.entity.monster.EntitySkeleton;
import net.minecraft.entity.monster.EntitySpider;
import net.minecraft.entity.monster.EntityZombie;
import net.minecraft.entity.passive.EntityCow;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.feature.WorldGenMinable;
public class Barnarda_C_Mountains extends WE_Biome {
public Barnarda_C_Mountains(double min, double max, int height, double per, int octaves) {
super(new BiomeProperties("barnarda_c_mountains_" + height), new int[] {/*0x89AC76*/ 0x822899, 0x11FF66, 0x985cff});
biomeMinValueOnMap = min;
biomeMaxValueOnMap = max;
biomePersistence = per;
biomeNumberOfOctaves = octaves;
biomeScaleX = 280.0D;
biomeScaleY = 1.7D;
biomeSurfaceHeight = height;
biomeInterpolateQuality = 35;
biomeTemerature = height > 100 ? 0.2F : 0.4F;
//-//
decorateChunkGen_List.clear();
createChunkGen_InXZ_List.clear();
this.spawnableMonsterList.add(new Biome.SpawnListEntry(EntityZombie.class, 10, 1, 2));
this.spawnableMonsterList.add(new Biome.SpawnListEntry(EntitySpider.class, 10, 1, 1));
this.spawnableMonsterList.add(new Biome.SpawnListEntry(EntitySkeleton.class, 10, 1, 2));
this.spawnableMonsterList.add(new Biome.SpawnListEntry(EntityEnderman.class, 10, 1, 2));
this.spawnableCreatureList.add(new Biome.SpawnListEntry(EntityCow.class, 4, 4, 4));
WE_BiomeLayer standardBiomeLayers = new WE_BiomeLayer();
standardBiomeLayers.add(BRBlocks.BARNARDA_C_BLOCKS.getStateFromMeta(3), BRBlocks.BARNARDA_C_BLOCKS.getStateFromMeta(1), -256, 0, -5, -1, true);
standardBiomeLayers.add(BRBlocks.BARNARDA_C_BLOCKS.getStateFromMeta(0), BRBlocks.BARNARDA_C_BLOCKS.getStateFromMeta(3), -256, 0, -1, -1, true);
standardBiomeLayers.add(BRBlocks.BARNARDA_C_GRASS.getStateFromMeta(0), BRBlocks.BARNARDA_C_BLOCKS.getStateFromMeta(0), -256, 0, -256, 0, false);
standardBiomeLayers.add(Blocks.BEDROCK.getDefaultState(), 0, 2, 0, 0, true);
createChunkGen_InXZ_List.add(standardBiomeLayers);
WE_SnowGen snowGen = new WE_SnowGen();
snowGen.snowPoint = 120;
snowGen.randomSnowPoint = 8;
snowGen.snowBlock = Blocks.SNOW.getDefaultState();
snowGen.iceBlock = Blocks.ICE.getDefaultState();
snowGen.freezeMaterial = Material.WATER;
createChunkGen_InXZ_List.add(snowGen);
}
@Override
public void decorateBiome(World world, Random rand, int x, int z)
{
int randPosX = x + rand.nextInt(16) + 8;
int randPosZ = z + rand.nextInt(16) + 8;
BlockPos pos = world.getHeight(new BlockPos(randPosX, 0, randPosZ));
if(rand.nextInt(2) == 0){
randPosX = x + rand.nextInt(16) + 8;
randPosZ = z + rand.nextInt(16) + 8;
pos = world.getHeight(new BlockPos(randPosX, 0, randPosZ));
if(pos.getY() > 120 && pos.getY() < 125)
{
world.setBlockState(pos, Blocks.FLOWING_WATER.getDefaultState(), 3);
}
}
for(int i = 0; i < 40; i++){
randPosX = x + rand.nextInt(16) + 8;
randPosZ = z + rand.nextInt(16) + 8;
pos = world.getHeight(new BlockPos(randPosX, 0, randPosZ));
if(world.isAreaLoaded(pos, 13, false))
new WorldGenMinable(BRBlocks.BARNARDA_C_BLOCKS.getDefaultState().withProperty(Barnarda_C_Blocks.BASIC_TYPE, Barnarda_C_Blocks.EnumBlockBarnardaC.STONE), 25,
new BlockPredicate(
BRBlocks.BARNARDA_C_GRASS.getDefaultState(),
BRBlocks.BARNARDA_C_BLOCKS.getDefaultState().withProperty(Barnarda_C_Blocks.BASIC_TYPE, Barnarda_C_Blocks.EnumBlockBarnardaC.DIRT),
BRBlocks.BARNARDA_C_BLOCKS.getDefaultState().withProperty(Barnarda_C_Blocks.BASIC_TYPE, Barnarda_C_Blocks.EnumBlockBarnardaC.DIRT_1),
BRBlocks.BARNARDA_C_BLOCKS.getDefaultState().withProperty(Barnarda_C_Blocks.BASIC_TYPE, Barnarda_C_Blocks.EnumBlockBarnardaC.STONE)
)).generate(world, rand, pos);
}
for(int y = 0; y < 10; y++) {
randPosX = x + rand.nextInt(16) + 8;
randPosZ = z + rand.nextInt(16) + 8;
pos = world.getHeight(new BlockPos(randPosX, 0, randPosZ));
if(world.getBlockState(pos.down()) == BRBlocks.BARNARDA_C_GRASS.getDefaultState().withProperty(Barnarda_C_Grass.BASIC_TYPE, Barnarda_C_Grass.EnumBlockGrass.GRASS))
world.setBlockState(pos, BRBlocks.BARNARDA_C_DANDELIONS.getDefaultState().withProperty(Barnarda_C_Dandelions.BASIC_TYPE, Barnarda_C_Dandelions.EnumBlockDandelions.GRASS));
}
if(rand.nextInt(10) == 0 && world.getBlockState(pos.down()) == BRBlocks.BARNARDA_C_GRASS.getDefaultState().withProperty(Barnarda_C_Grass.BASIC_TYPE, Barnarda_C_Grass.EnumBlockGrass.GRASS)) {
randPosX = x + rand.nextInt(16) + 8;
randPosZ = z + rand.nextInt(16) + 8;
pos = world.getHeight(new BlockPos(randPosX, 0, randPosZ));
new WorldGenTree_Small(BRBlocks.BARNARDA_C_VIOLET_LOG.getDefaultState(), BRBlocks.BARNARDA_C_LEAVES.getStateFromMeta(0), rand.nextInt(3)).generate(world, rand, pos);
}
}
}
| apache-2.0 |
smoope/java-sdk | src/test/java/com/smoope/sdk/resources/BusinessesResourceTest.java | 222 | package com.smoope.sdk.resources;
public interface BusinessesResourceTest {
void update();
void get();
void searchBusinesses();
void getLogo();
void getLogoByBusiness();
void uploadLogo();
}
| apache-2.0 |
NEUROINFORMATICS-GROUP-FAV-KIV-ZCU/elfyz-data-mobile-logger | src/cz/zcu/kiv/mobile/logger/data/database/WeightScaleMeasurementTable.java | 7546 | package cz.zcu.kiv.mobile.logger.data.database;
import java.util.Date;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import cz.zcu.kiv.mobile.logger.data.database.exceptions.DatabaseException;
import cz.zcu.kiv.mobile.logger.data.types.weight_scale.WeightScaleAdvancedMeasurement;
import cz.zcu.kiv.mobile.logger.data.types.weight_scale.WeightScaleBasicMeasurement;
public class WeightScaleMeasurementTable extends ARecordTable<WeightScaleMeasurementTable.WSDataObserver> {
private static final String TAG = WeightScaleMeasurementTable.class.getSimpleName();
private static final String TABLE_NAME = "ws_measurement";
public static final String COLUMN_BASIC = "basic";
public static final String COLUMN_TIME = "time";
public static final String COLUMN_WEIGHT = "weight";
public static final String COLUMN_HYDRATION_PERCENTAGE = "hydration_percentage";
public static final String COLUMN_FAT_PERCENTAGE = "fat_percentage";
public static final String COLUMN_MUSCLE_MASS = "muscle_mass";
public static final String COLUMN_BONE_MASS = "bone_mass";
public static final String COLUMN_ACTIVE_METABOLIC_RATE = "active_metabolic_rate";
public static final String COLUMN_BASAL_METABOLIC_RATE = "basal_metabolic_rate";
private static final String[] COLUMNS_MEASUREMENT_ALL = new String[]{COLUMN_ID, COLUMN_TIME, COLUMN_BASIC, COLUMN_WEIGHT, COLUMN_HYDRATION_PERCENTAGE, COLUMN_FAT_PERCENTAGE, COLUMN_MUSCLE_MASS, COLUMN_BONE_MASS, COLUMN_ACTIVE_METABOLIC_RATE, COLUMN_BASAL_METABOLIC_RATE, COLUMN_UPLOADED};
private static final String ORDER_MEASUREMENTS_DESC = COLUMN_TIME + " DESC";
private static final String ORDER_MEASUREMENTS_ASC = COLUMN_TIME + " ASC";
public WeightScaleMeasurementTable(SQLiteOpenHelper openHelper, int tableID) {
super(openHelper, tableID);
}
@Override
void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY,"
+ COLUMN_USER_ID + " INTEGER NOT NULL,"
+ COLUMN_BASIC + " INTEGER NOT NULL,"
+ COLUMN_TIME + " INTEGER NOT NULL,"
+ COLUMN_WEIGHT + " REAL NOT NULL,"
+ COLUMN_HYDRATION_PERCENTAGE + " REAL NULL,"
+ COLUMN_FAT_PERCENTAGE + " REAL NULL,"
+ COLUMN_MUSCLE_MASS + " REAL NULL,"
+ COLUMN_BONE_MASS + " REAL NULL,"
+ COLUMN_ACTIVE_METABOLIC_RATE + " REAL NULL,"
+ COLUMN_BASAL_METABOLIC_RATE + " REAL NULL,"
+ COLUMN_UPLOADED + " INTEGER NOT NULL,"
+ "FOREIGN KEY (" + COLUMN_USER_ID + ") REFERENCES " + ProfileTable.TABLE_NAME + " (" + COLUMN_ID + ") ON DELETE CASCADE"
+ ");");
}
@Override
void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {
int upgradeVersion = oldVersion;
if(upgradeVersion != currentVersion){
Log.d(TAG, "Wasn't able to upgrade the database. Wiping and rebuilding...");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
public long addMeasurement(long userID,
boolean basic, long estTimestamp, double weight, Double hydrationPercentage,
Double fatPercentage, Double muscleMass, Double boneMass,
Double activeMetabolicRate, Double basalMetabolicRate, boolean uploaded) throws DatabaseException {
SQLiteDatabase db = getDatabase();
ContentValues values = new ContentValues(11);
values.put(COLUMN_USER_ID, userID);
values.put(COLUMN_BASIC, basic ? VALUE_TRUE : VALUE_FALSE);
values.put(COLUMN_TIME, estTimestamp);
values.put(COLUMN_WEIGHT, weight);
values.put(COLUMN_HYDRATION_PERCENTAGE, hydrationPercentage);
values.put(COLUMN_FAT_PERCENTAGE, fatPercentage);
values.put(COLUMN_MUSCLE_MASS, muscleMass);
values.put(COLUMN_BONE_MASS, boneMass);
values.put(COLUMN_ACTIVE_METABOLIC_RATE, activeMetabolicRate);
values.put(COLUMN_BASAL_METABOLIC_RATE, basalMetabolicRate);
values.put(COLUMN_UPLOADED, uploaded ? VALUE_TRUE : VALUE_FALSE);
try{
long id = db.insertOrThrow(TABLE_NAME, null, values);
for (WSDataObserver o : observers) {
o.onWSMeasurementAdded(id);
}
return id;
}
catch(Exception e){
throw new DatabaseException(e);
}
}
public long addBasicMeasurement(long userID, WeightScaleBasicMeasurement data) throws DatabaseException {
return addMeasurement(userID, true, data.getEstTimestamp(), data.getBodyWeight().doubleValue(), null, null, null, null, null, null, data.isUploaded());
}
public long addAdvancedMeasurement(long userID, WeightScaleAdvancedMeasurement data) throws DatabaseException {
return addMeasurement(userID, false, data.getEstTimestamp(), data.getBodyWeight().doubleValue(),
data.getHydrationPercentage().doubleValue(), data.getBodyFatPercentage().doubleValue(),
data.getMuscleMass().doubleValue(), data.getBoneMass().doubleValue(),
data.getActiveMetabolicRate().doubleValue(), data.getBasalMetabolicRate().doubleValue(), data.isUploaded());
}
public Cursor getMeasurements(long profileID) throws DatabaseException {
return getMeasurements(profileID, false);
}
public Cursor getMeasurements(long profileID, boolean ascending) throws DatabaseException {
SQLiteDatabase db = getDatabase();
try {
String[] selectionArgs = new String[]{ String.valueOf(profileID) };
return db.query(TABLE_NAME, COLUMNS_MEASUREMENT_ALL, WHERE_USER_ID, selectionArgs, null, null, ascending ? ORDER_MEASUREMENTS_ASC : ORDER_MEASUREMENTS_DESC);
}
catch(Exception e) {
throw new DatabaseException(e);
}
}
public Cursor getMeasurements(long profileID, boolean ascending, Date dateFrom, Date dateTo) throws DatabaseException {
SQLiteDatabase db = getDatabase();
try {
String[] selectionArgs = new String[]{
String.valueOf(profileID),
String.valueOf(dateFrom.getTime()),
String.valueOf(dateTo.getTime())};
return db.query(TABLE_NAME, COLUMNS_MEASUREMENT_ALL, WHERE_USER_ID_AND_DATES, selectionArgs, null, null, ascending ? ORDER_MEASUREMENTS_ASC : ORDER_MEASUREMENTS_DESC);
}
catch(Exception e) {
throw new DatabaseException(e);
}
}
public Cursor getMeasurements(long[] ids) throws DatabaseException {
SQLiteDatabase db = getDatabase();
try {
return db.query(TABLE_NAME, COLUMNS_MEASUREMENT_ALL, WHERE_IDS_IN_ + assemblePlaceholders(ids.length), toStringArray(ids), null, null, ORDER_MEASUREMENTS_ASC);
}
catch(Exception e) {
throw new DatabaseException(e);
}
}
public void setUploaded(long[] ids) throws DatabaseException {
SQLiteDatabase db = getDatabase();
try {
ContentValues values = new ContentValues(1);
values.put(COLUMN_UPLOADED, VALUE_TRUE);
db.update(TABLE_NAME, values, WHERE_IDS_IN_ + assemblePlaceholders(ids.length), toStringArray(ids));
for (WSDataObserver observer : observers) {
observer.onWSMeasurementsUpdated(ids);
}
}
catch(Exception e) {
throw new DatabaseException(e);
}
}
@Override
protected String getTableName() {
return TABLE_NAME;
}
public interface WSDataObserver extends ARecordTable.IRecordDataObserver {
void onWSMeasurementAdded(long id);
void onWSMeasurementsUpdated(long[] ids);
}
}
| apache-2.0 |
alladin-IT/open-rmbt | RMBTClient/src/at/alladin/rmbt/client/applet/RMBTApplet.java | 14018 | /*******************************************************************************
* Copyright 2013-2015 alladin-IT GmbH
*
* 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.alladin.rmbt.client.applet;
import java.applet.Applet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;
import net.measurementlab.ndt.NdtTests;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import at.alladin.rmbt.client.QualityOfServiceTest;
import at.alladin.rmbt.client.RMBTClient;
import at.alladin.rmbt.client.TestResult;
import at.alladin.rmbt.client.helper.Config;
import at.alladin.rmbt.client.helper.ControlServerConnection;
import at.alladin.rmbt.client.helper.IntermediateResult;
import at.alladin.rmbt.client.helper.NdtStatus;
import at.alladin.rmbt.client.helper.RevisionHelper;
import at.alladin.rmbt.client.helper.TestStatus;
import at.alladin.rmbt.client.ndt.NDTRunner;
import at.alladin.rmbt.client.v2.task.QoSTestEnum;
import at.alladin.rmbt.client.v2.task.result.QoSResultCollector;
import at.alladin.rmbt.client.v2.task.service.TestSettings;
public class RMBTApplet extends Applet
{
public final static String PARAM_UUID = "uuid";
public final static String PARAM_RUN_QOS = "runQos";
public final static String PARAM_RUN_NDT = "runNdt";
public final static String PARAM_QOS_SSL = "qosSsl";
private static final long serialVersionUID = 1L;
private RMBTClient client;
private volatile boolean start = false;
private volatile boolean runRMBT = false;
private volatile boolean ndtActivated = false;
private volatile String uuid;
private volatile ArrayList<String> geoInfo = null;
private final AtomicReference<NDTRunner> ndtRunnerHolder = new AtomicReference<NDTRunner>();
private volatile Integer zip;
private volatile String product;
@Override
public void init()
{
System.out.println(String.format("initializing applet %s", RevisionHelper.getVerboseRevision()));
System.out.println("supported HTML named parameters: ");
System.out.println("runNdt \n\toptions: true, false \t default: false \t functionality: run NDT test");
System.out.println("runQos \n\toptions: true, false \t default: false \t functionality: run QoS test");
System.out.println("qosSsl \n\toptions: true, false \t default: true \t functionality: run QoS test with SSL");
String param = getParameter(PARAM_RUN_QOS);
final boolean runQoS= Boolean.parseBoolean(param == null ? "false" : param.trim());
param = getParameter(PARAM_QOS_SSL);
final boolean useSslForQoS = Boolean.parseBoolean(param == null ? "true" : param.trim());
param = getParameter(PARAM_RUN_NDT);
final boolean runNdt = Boolean.parseBoolean(param == null ? "false" : param.trim());
param = getParameter(PARAM_UUID);
if (param != null)
{
uuid = param;
runRMBT = true;
start = true;
}
final Runnable runnable = new Runnable()
{
public void run()
{
try
{
synchronized (RMBTApplet.this)
{
while (!start)
RMBTApplet.this.wait(); // wait for start signal
}
System.out.println("got start signal");
final int port = 443;
final boolean encryption = true;
// Leere GeoInfoS
// ArrayList<String> geoInfo = null;
// uuid fuer tests
if (runRMBT)
{
final JSONObject additionalValues = new JSONObject();
try
{
additionalValues.put("ndt", ndtActivated);
additionalValues.put("plattform", "Applet");
}
catch (JSONException e)
{
e.printStackTrace();
}
client = RMBTClient.getInstance(getParameter("host"), getParameter("path"),
port, encryption, geoInfo, uuid, "DESKTOP", Config.RMBT_CLIENT_NAME,
Config.RMBT_VERSION_NUMBER, null, additionalValues);
final TestResult result = client.runTest();
if (result != null)
{
final JSONObject jsonResult = new JSONObject();
try
{
if (geoInfo != null)
{
final JSONArray itemList = new JSONArray();
final JSONObject jsonItem = new JSONObject();
jsonItem.put("tstamp", geoInfo.get(0));
jsonItem.put("geo_lat", geoInfo.get(1));
jsonItem.put("geo_long", geoInfo.get(2));
jsonItem.put("accuracy", geoInfo.get(3));
jsonItem.put("altitude", geoInfo.get(4));
jsonItem.put("bearing", geoInfo.get(5));
jsonItem.put("speed", geoInfo.get(6));
jsonItem.put("provider", geoInfo.get(7));
itemList.put(jsonItem);
jsonResult.put("geoLocations", itemList);
}
if (zip != null)
jsonResult.put("zip_code", zip);
if (product != null)
{
jsonResult.put("model", product);
jsonResult.put("product", product);
}
jsonResult.put("plattform", "Applet");
jsonResult.put("ndt", ndtActivated);
jsonResult.put("network_type", 98);
}
catch (final JSONException e)
{
e.printStackTrace();
}
client.sendResult(jsonResult);
}
System.out.println("Status: " + client.getStatus());
System.out.println("Checking QoS...");
if (runQoS && client.getStatus() == TestStatus.SPEEDTEST_END)
{
System.out.println("On. Starting QoS...");
try {
client.setStatus(TestStatus.QOS_TEST_RUNNING);
final TestSettings qosTestSettings = new TestSettings(client.getControlConnection().getStartTimeNs());
System.out.println(qosTestSettings);
qosTestSettings.setUseSsl(useSslForQoS);
final QualityOfServiceTest qosTest = new QualityOfServiceTest(client, qosTestSettings);
QoSResultCollector qosResult = qosTest.call();
if (qosResult != null && qosTest.getStatus().equals(QoSTestEnum.QOS_FINISHED)) {
System.out.println("Sending QoS results...");
client.sendQoSResult(qosResult);
}
System.out.println("QoS finished.");
} catch (Exception e) {
e.printStackTrace();
} finally {
client.setStatus(TestStatus.QOS_END);
}
}
else {
System.out.println("Off. Not running QoS.");
client.setStatus(TestStatus.QOS_END);
}
client.shutdown();
}
System.out.println("Status: " + client.getStatus());
System.out.println("Checking NDT...");
if (runNdt && (client.getStatus() == TestStatus.QOS_END || client.getStatus() == TestStatus.SPEEDTEST_END))
{
System.out.println("On. Starting NDT...");
final NDTRunner ndtRunner = new NDTRunner();
ndtRunnerHolder.set(ndtRunner);
ndtRunner.runNDT(NdtTests.NETWORK_WIRED, ndtRunner.new UiServices()
{
@Override
public void sendResults()
{
System.out.println("Sending NDT results...");
final ControlServerConnection csc = new ControlServerConnection();
csc.sendNDTResult(getParameter("host"), getParameter("path"),
port, encryption, uuid, this, client.getTestUuid());
System.out.println("NDT finished.");
}
});
}
else {
System.out.println("Off. Not running NDT.");
}
//set status to end:
if (client.getStatus() != TestStatus.ERROR ) {
client.setStatus(TestStatus.END);
System.out.println("TEST FINISHED. Status: " + client.getStatus());
}
else {
System.out.println("ERROR: " + client.getErrorMsg());
}
}
catch (final InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
};
new Thread(runnable).start();
}
synchronized public void startTest(final String uuid)
{
System.out.println(String.format("starting test. uuid: %s", uuid));
this.uuid = uuid;
start = true;
runRMBT = true;
notify();
}
public IntermediateResult getIntermediateResult()
{
if (client == null)
return null;
return client.getIntermediateResult(null);
}
public NdtStatus getNdtStatus()
{
final NDTRunner ndtRunner = ndtRunnerHolder.get();
if (ndtRunner == null)
return null;
return ndtRunner.getNdtStatus();
}
public float getNdtProgress()
{
final NDTRunner ndtRunner = ndtRunnerHolder.get();
if (ndtRunner == null)
return 0;
return ndtRunner.getNdtProgress();
}
public String getPublicIP()
{
if (client == null)
return null;
return client.getPublicIP();
}
public String getServerName()
{
if (client == null)
return null;
return client.getServerName();
}
public String getProvider()
{
if (client == null)
return null;
return client.getProvider();
}
public String getTestUuid()
{
if (client == null)
return null;
return client.getTestUuid();
}
public void setLocation(final Number posTimestamp, final Number posLat, final Number posLong,
final Number posAccuracy, final Number posAltitude, final Number posHeading, final Number posSpeed)
{
try
{
geoInfo = new ArrayList<String>(Arrays.asList(String.valueOf(posTimestamp), String.valueOf(posLat),
String.valueOf(posLong), String.valueOf(posAccuracy), String.valueOf(posAltitude),
String.valueOf(posHeading), String.valueOf(posSpeed), "Browser"));
}
catch (final Exception e)
{
e.printStackTrace();
}
}
public void setZip(final Integer zip)
{
this.zip = zip;
}
public void setBrowserInfo(final String product)
{
if (product != null && product.length() > 0)
this.product = product;
}
public void setNDTActivated(final boolean ndtActivated)
{
this.ndtActivated = ndtActivated;
}
}
| apache-2.0 |
lei-xia/helix | helix-core/src/test/java/org/apache/helix/integration/rebalancer/WagedRebalancer/TestDelayedWagedRebalanceWithDisabledInstance.java | 3563 | package org.apache.helix.integration.rebalancer.WagedRebalancer;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.HashMap;
import java.util.Map;
import org.apache.helix.TestHelper;
import org.apache.helix.integration.rebalancer.DelayedAutoRebalancer.TestDelayedAutoRebalanceWithDisabledInstance;
import org.apache.helix.model.ExternalView;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* Inherit TestDelayedAutoRebalanceWithDisabledInstance to ensure the test logic is the same.
*/
public class TestDelayedWagedRebalanceWithDisabledInstance extends TestDelayedAutoRebalanceWithDisabledInstance {
// create test DBs, wait it converged and return externalviews
protected Map<String, ExternalView> createTestDBs(long delayTime)
throws InterruptedException {
Map<String, ExternalView> externalViews = new HashMap<>();
int i = 0;
for (String stateModel : TestStateModels) {
String db = "Test-DB-" + TestHelper.getTestMethodName() + i++;
createResourceWithWagedRebalance(CLUSTER_NAME, db, stateModel, PARTITIONS, _replica,
_minActiveReplica);
_testDBs.add(db);
}
Thread.sleep(DEFAULT_REBALANCE_PROCESSING_WAIT_TIME);
Assert.assertTrue(_clusterVerifier.verifyByPolling());
for (String db : _testDBs) {
ExternalView ev =
_gSetupTool.getClusterManagementTool().getResourceExternalView(CLUSTER_NAME, db);
externalViews.put(db, ev);
}
return externalViews;
}
@Test
public void testDelayedPartitionMovement() {
// Waged Rebalancer takes cluster level delay config only. Skip this test.
}
@Test
public void testDisableDelayRebalanceInResource() {
// Waged Rebalancer takes cluster level delay config only. Skip this test.
}
@Test(dependsOnMethods = {"testDelayedPartitionMovement"})
public void testDelayedPartitionMovementWithClusterConfigedDelay()
throws Exception {
super.testDelayedPartitionMovementWithClusterConfigedDelay();
}
@Test(dependsOnMethods = {"testDelayedPartitionMovementWithClusterConfigedDelay"})
public void testMinimalActiveReplicaMaintain()
throws Exception {
super.testMinimalActiveReplicaMaintain();
}
@Test(dependsOnMethods = {"testMinimalActiveReplicaMaintain"})
public void testPartitionMovementAfterDelayTime()
throws Exception {
super.testPartitionMovementAfterDelayTime();
}
@Test(dependsOnMethods = {"testDisableDelayRebalanceInResource"})
public void testDisableDelayRebalanceInCluster()
throws Exception {
super.testDisableDelayRebalanceInCluster();
}
@Test(dependsOnMethods = {"testDisableDelayRebalanceInCluster"})
public void testDisableDelayRebalanceInInstance()
throws Exception {
super.testDisableDelayRebalanceInInstance();
}
}
| apache-2.0 |
baevpetr/pbaev | chapter_001/src/main/java/ru/pbaev/MaxIndexDistance.java | 557 | package ru.pbaev;
/**
* Class MaxIndexDistance, решение задачи части 001, тестовое задание.
* @author pbaev
* @since 02.02.2017
* @version 1
*/
public class MaxIndexDistance {
/** Инициализация хэш-таблицы.
*@param array массив чисел.
*@return максимальная дистанция.
*/
public int maxIndexDistance(int[] array) {
HashMap hm = new HashMap();
for (int i = 0; i < array.length; i++) {
hm.put(array[i], i);
}
return hm.findMaxDistance();
}
} | apache-2.0 |
PillowMan/PIDAexamination | app/src/main/java/com/wp/android/pidaexamination/MediaPlayerTest.java | 1685 | package com.wp.android.pidaexamination;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.widget.TextView;
import java.io.IOException;
/**
* Created by PillowMan on 03.11.2017.
*/
public class MediaPlayerTest extends Activity {
private MediaPlayer mMediaPlayer;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMediaPlayer = new MediaPlayer();
TextView mTextView = new TextView(this);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
AssetManager manager = getAssets();
try {
AssetFileDescriptor descriptor = manager.openFd("music.ogg");
mMediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
mMediaPlayer.prepare();
mMediaPlayer.setLooping(true);
} catch (IOException e) {
e.getMessage();
mMediaPlayer = null;
}
setContentView(mTextView);
}
@Override
protected void onResume() {
super.onResume();
if(mMediaPlayer!=null){
mMediaPlayer.start();
}
}
@Override
protected void onPause() {
super.onPause();
if(mMediaPlayer!=null){
mMediaPlayer.pause();
if(isFinishing()){
mMediaPlayer.stop();
mMediaPlayer.release();
}
}
}
}
| apache-2.0 |
ebondareva/bootique | bootique/src/main/java/io/bootique/help/config/ConfigSectionGenerator.java | 12220 | /*
* Licensed to ObjectStyle LLC under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ObjectStyle LLC licenses
* this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.bootique.help.config;
import io.bootique.help.ConsoleAppender;
import io.bootique.meta.MetadataNode;
import io.bootique.meta.config.ConfigListMetadata;
import io.bootique.meta.config.ConfigMapMetadata;
import io.bootique.meta.config.ConfigMetadataNode;
import io.bootique.meta.config.ConfigMetadataVisitor;
import io.bootique.meta.config.ConfigObjectMetadata;
import io.bootique.meta.config.ConfigValueMetadata;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @since 0.21
*/
class ConfigSectionGenerator implements ConfigMetadataVisitor<Object> {
static final int DEFAULT_OFFSET = DefaultConfigHelpGenerator.DEFAULT_OFFSET;
protected ConsoleAppender out;
public ConfigSectionGenerator(ConsoleAppender out) {
this.out = Objects.requireNonNull(out);
}
@Override
public Object visitObjectMetadata(ConfigObjectMetadata metadata) {
printNode(metadata, false);
List<ConfigObjectMetadata> selfAndSubconfigs = metadata
.getAllSubConfigs()
.map(md -> md.accept(new ConfigMetadataVisitor<ConfigObjectMetadata>() {
@Override
public ConfigObjectMetadata visitObjectMetadata(ConfigObjectMetadata visited) {
// include the root type even if it has no properties.. This ensure its header is printed in
// maps and lists
if (metadata == visited) {
return visited;
}
return visited.isAbstractType() || visited.getProperties().isEmpty() ? null : visited;
}
}))
.filter(md -> md != null)
.collect(Collectors.toList());
if (!selfAndSubconfigs.isEmpty()) {
ConfigObjectMetadata last = selfAndSubconfigs.get(selfAndSubconfigs.size() - 1);
selfAndSubconfigs.forEach(md -> {
printObjectNoSubclasses(md);
if (md != last) {
out.println();
}
});
}
return null;
}
@Override
public Object visitValueMetadata(ConfigValueMetadata metadata) {
printNode(metadata, true);
return null;
}
@Override
public Object visitListMetadata(ConfigListMetadata metadata) {
printNode(metadata, false);
ConfigSectionListGenerator childGenerator = new ConfigSectionListGenerator(out.withOffset(DEFAULT_OFFSET));
childGenerator.printListHeader(metadata);
metadata.getElementType().accept(childGenerator);
return null;
}
@Override
public Object visitMapMetadata(ConfigMapMetadata metadata) {
printNode(metadata, false);
ConfigSectionMapGenerator childGenerator = new ConfigSectionMapGenerator(
metadata.getKeysType(),
out.withOffset(DEFAULT_OFFSET));
childGenerator.printMapHeader(metadata);
metadata.getValuesType().accept(childGenerator);
return null;
}
protected void printValueHeader(ConfigValueMetadata metadata) {
if (metadata.getDescription() != null) {
out.withOffset("# ").foldPrintln(metadata.getDescription());
}
Type valueType = metadata.getType();
if (valueType != null && !isImpliedType(valueType)) {
out.withOffset("# ").foldPrintln("Resolved as '", typeLabel(valueType), "'.");
}
}
protected void printObjectHeader(ConfigObjectMetadata metadata) {
out.println("#");
if (metadata.getTypeLabel() != null) {
out.println("# Type option: ", metadata.getTypeLabel());
}
printValueHeader(metadata);
out.println("#");
}
protected void printMapHeader(ConfigMapMetadata metadata) {
out.println("#");
printValueHeader(metadata);
out.println("#");
}
protected void printListHeader(ConfigListMetadata metadata) {
out.println("#");
printValueHeader(metadata);
out.println("#");
}
protected void printMapHeader(ConfigMetadataNode metadata, boolean padded) {
if (padded) {
out.println("#");
}
String typeLabel = metadata.accept(new ConfigMetadataVisitor<String>() {
@Override
public String visitObjectMetadata(ConfigObjectMetadata metadata) {
return metadata.getTypeLabel();
}
});
if (typeLabel != null) {
out.println("# Type option: ", typeLabel);
}
if (metadata.getDescription() != null) {
out.println("# ", metadata.getDescription());
}
Type valueType = metadata.getType();
if (valueType != null && !isImpliedType(valueType)) {
out.println("# Resolved as '", typeLabel(valueType), "'.");
}
if (padded) {
out.println("#");
}
}
protected void printObjectNoSubclasses(ConfigObjectMetadata metadata) {
ConsoleAppender shifted = out.withOffset(DEFAULT_OFFSET);
ConfigSectionGenerator childGenerator = new ConfigSectionGenerator(shifted);
childGenerator.printObjectHeader(metadata);
boolean willPrintProperties = !metadata.isAbstractType() && !metadata.getProperties().isEmpty();
boolean willPrintType = metadata.getTypeLabel() != null;
if (willPrintProperties || willPrintType) {
shifted.println();
}
if (willPrintType) {
shifted.println("type: '", metadata.getTypeLabel() + "'");
}
if (willPrintProperties) {
metadata.getProperties()
.stream()
.sorted(Comparator.comparing(MetadataNode::getName))
.forEach(p -> {
p.accept(childGenerator);
});
}
}
protected void printNode(ConfigValueMetadata metadata, boolean asValue) {
if (asValue) {
// value header goes on top of property name
printValueHeader(metadata);
String valueLabel = metadata.getType() != null ? sampleValue(metadata.getType()) : "?";
out.println(metadata.getName(), ": ", valueLabel);
} else {
// headers for other types are printed below the property with the object contents
out.println(metadata.getName(), ":");
}
}
protected String sampleValue(Type type) {
// TODO: allow to provide sample values in metadata, so that we can display something useful
String typeName = type.getTypeName();
switch (typeName) {
case "boolean":
case "java.lang.Boolean":
return "<true|false>";
case "int":
case "java.lang.Integer":
return "<int>";
case "byte":
case "java.lang.Byte":
return "<byte>";
case "double":
case "java.lang.Double":
return "<double>";
case "float":
case "java.lang.Float":
return "<float>";
case "short":
case "java.lang.Short":
return "<short>";
case "long":
case "java.lang.Long":
return "<long>";
case "java.lang.String":
return "<string>";
case "io.bootique.resource.ResourceFactory":
return "<resource-uri>";
case "io.bootique.resource.FolderResourceFactory":
return "<folder-resource-uri>";
default:
if (type instanceof Class) {
Class<?> classType = (Class<?>) type;
if (classType.isEnum()) {
StringBuilder out = new StringBuilder("<");
Object[] values = classType.getEnumConstants();
for (int i = 0; i < values.length; i++) {
if (i > 0) {
out.append("|");
}
out.append(values[i]);
}
out.append(">");
return out.toString();
}
}
return "<value>";
}
}
protected boolean isImpliedType(Type type) {
String typeName = type.getTypeName();
switch (typeName) {
case "boolean":
case "java.lang.Boolean":
case "int":
case "java.lang.Integer":
case "byte":
case "java.lang.Byte":
case "double":
case "java.lang.Double":
case "float":
case "java.lang.Float":
case "short":
case "java.lang.Short":
case "long":
case "java.lang.Long":
case "java.lang.String":
case "io.bootique.resource.ResourceFactory":
case "io.bootique.resource.FolderResourceFactory":
return true;
default:
return false;
}
}
protected String typeLabel(Type type) {
String typeName = type.getTypeName();
switch (typeName) {
case "java.lang.Boolean":
return "boolean";
case "java.lang.Integer":
return "int";
case "java.lang.Byte":
return "byte";
case "java.lang.Double":
return "double";
case "java.lang.Float":
return "float";
case "java.lang.Short":
return "short";
case "java.lang.Long":
return "long";
case "java.lang.String":
return "String";
default:
if (type instanceof Class) {
Class<?> classType = (Class<?>) type;
if (Map.class.isAssignableFrom(classType)) {
return "Map";
}
// TODO: decipher collection type... for now hardcoding List type
else if (Collection.class.isAssignableFrom(classType)) {
return "List";
}
} else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
StringBuilder out = new StringBuilder(typeLabel(parameterizedType.getRawType()));
out.append("<");
Type[] args = parameterizedType.getActualTypeArguments();
if (args != null) {
for (int i = 0; i < args.length; i++) {
if (i > 0) {
out.append(", ");
}
out.append(typeLabel(args[i]));
}
}
out.append(">");
return out.toString();
}
return typeName;
}
}
}
| apache-2.0 |
micromagic/eterna | main/src/java/test/self/micromagic/util/PropertiesManagerTest.java | 7985 | /*
* Copyright 2015 xinjunli (micromagic@sina.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 self.micromagic.util;
import java.util.List;
import java.util.Properties;
import junit.framework.TestCase;
import self.micromagic.eterna.digester2.ContainerManager;
import tool.PrivateAccessor;
public class PropertiesManagerTest extends TestCase
{
public void testPropteriesValue()
{
System.out.println(50 * 60 * 100);
int mask = (1 << 18) - 1;
System.out.println(((long) mask));
System.out.println(Long.toHexString(System.currentTimeMillis() & ~( mask)));
PropertiesManager pm = new PropertiesManager("conf/main1.txt", this.getClass().getClassLoader());
assertEquals("z", pm.getProperty("p1"));
assertEquals("y", pm.getProperty("p2"));
assertEquals("sub", pm.getProperty("p3"));
assertEquals("d", pm.getProperty("p4"));
assertEquals("e", pm.getProperty("p5"));
assertEquals("f", pm.getProperty("p6"));
assertEquals("g", pm.getProperty("p7"));
assertEquals("h", pm.getProperty("p8"));
pm.contains("flag", true);
assertEquals("", pm.getProperty("flag"));
System.out.println(pm);
}
public void testPreRead()
throws Exception
{
PropertiesManager pm = new PropertiesManager(
ContainerManager.createResource("cp:/conf/preRead.txt"), null, false);
nowPM = pm;
pm.addMethodPropertyManager("baseName", this.getClass(), "setBaseName");
pm.reload();
assertEquals("test_abc", pm.getResolvedProperty("testName"));
pm = new PropertiesManager(ContainerManager.createResource("cp:/conf/preRead.txt"), null, false);
nowPM = pm;
pm.addMethodPropertyManager("baseName", this.getClass(), "setBaseName");
System.out.println("When pre read, get other property is null.");
pm.reload(true, null, new String[]{"baseName"});
System.out.println("StringAppender:" + StringTool.createStringAppender().getClass());
nowPM = null;
}
public void testParentFirst()
{
ClassLoader loader = this.getClass().getClassLoader();
PropertiesManager pm1 = new PropertiesManager("conf/pFirst1.txt", loader);
assertEquals("1", pm1.getProperty("p5"));
assertEquals("2", pm1.getProperty("p6"));
assertEquals("3", pm1.getProperty("p7"));
PropertiesManager parent = new PropertiesManager("conf/main1.txt", loader);
PropertiesManager pm2 = new PropertiesManager("conf/pFirst1.txt", loader, parent);
assertEquals("e", pm2.getProperty("p5"));
assertEquals("f", pm2.getProperty("p6"));
assertEquals("3", pm2.getProperty("p7"));
}
public void testDynamicRes()
{
PropertiesManager pm = new PropertiesManager(
ContainerManager.createResource("cp:/conf/dResMain.txt"), null, false);
pm.reload();
assertEquals("1", pm.getProperty("testValue"));
assertEquals("a=1.013", pm.getResolvedProperty("dName1"));
assertEquals("a=x", pm.getResolvedProperty("dName2"));
pm.setProperty("value2", "y");
assertEquals("a=y", pm.getResolvedProperty("dName2"));
pm.setProperty("value2", "${dot2}");
assertEquals("a=b", pm.getResolvedProperty("dName2"));
assertEquals("a=${value3}", pm.getResolvedProperty("dName3"));
}
public void testBindDefaultValue()
throws Exception
{
PropertiesManager pm = new PropertiesManager("conf/main1.txt", this.getClass().getClassLoader());
pm.addFieldPropertyManager("notExists", PropertiesManagerTest.class, "t_prop_bindDefault", "001");
assertEquals("001", t_prop_bindDefault);
pm.setProperty("notExists", "002");
assertEquals("002", t_prop_bindDefault);
pm.setProperty("other", "003");
pm.reload();
assertEquals("001", t_prop_bindDefault);
assertNull(pm.getProperty("other"));
}
public static String t_prop_bindDefault;
public void testReload()
throws Exception
{
PropertiesManager pm = new PropertiesManager("conf/main2.txt", this.getClass().getClassLoader());
System.out.println(pm);
pm.addFieldPropertyManager("p5", PropertiesManagerTest.class, "t_prop_reload");
assertEquals("temp", t_prop_reload);
pm.setProperty("p5", "2");
assertEquals("2", t_prop_reload);
pm.setProperty("_child.properties", "cp:/conf/parent1.txt");
pm.reload();
assertEquals("none", t_prop_reload);
System.out.println(pm);
}
public static String t_prop_reload;
public void testSystemDefault()
throws Exception
{
System.setProperty("test.001", "a");
PropertiesManager pm1 = new PropertiesManager("conf/main1.txt", this.getClass().getClassLoader());
assertEquals("ab", pm1.resolveDynamicPropnames("${test.001}b"));
PropertiesManager pm2 = new PropertiesManager("conf/main2.txt", this.getClass().getClassLoader());
assertEquals("${test.001}btest", pm2.resolveDynamicPropnames("${test.001}b${p1}"));
pm1.addFieldPropertyManager("test.001", PropertiesManagerTest.class, "t_prop_sd");
assertEquals("a", t_prop_sd);
System.setProperty("test.001", "c");
assertEquals("a", t_prop_sd);
pm1.setProperty("test.001", "d");
assertEquals("d", t_prop_sd);
Properties d = new Properties();
d.setProperty("test.001", "x");
PropertiesManager.setDefaultProperties(d);
pm1 = new PropertiesManager("conf/main1.txt", this.getClass().getClassLoader());
assertEquals("xb", pm1.resolveDynamicPropnames("${test.001}b"));
pm2 = new PropertiesManager("conf/main2.txt", this.getClass().getClassLoader());
assertEquals("${test.001}btest", pm2.resolveDynamicPropnames("${test.001}b${p1}"));
}
public static String t_prop_sd;
public void testParent()
throws Exception
{
PropertiesManager pm1 = new PropertiesManager("conf/main1.txt", this.getClass().getClassLoader());
PropertiesManager pm2 = new PropertiesManager("conf/main2.txt", this.getClass().getClassLoader(), pm1);
pm1.setProperty("p.test", "a");
pm2.addFieldPropertyManager("p.test", PropertiesManagerTest.class, "t_prop_parent");
assertEquals("a", t_prop_parent);
pm1.setProperty("p.test", "b");
assertEquals("b", t_prop_parent);
pm2.setProperty("p.test", "c");
assertEquals("c", t_prop_parent);
// 由于pm2中已有值, 所以父配置中的修改不会影响当前值
pm1.setProperty("p.test", "d");
assertEquals("c", t_prop_parent);
pm2.removeProperty("p.test");
assertEquals("d", t_prop_parent);
pm1.removeProperty("p.test");
assertNull(t_prop_parent);
t_prop_parent_setted = false;
pm2.addMethodPropertyManager("p.test", PropertiesManagerTest.class, "setPropParent");
pm1.setProperty("p.test", "a");
assertTrue(t_prop_parent_setted);
// 由于父配置中已有a值, 子配置中再设置a值, 这时值无变化,
// 不会触发setPropParent方法
t_prop_parent_setted = false;
pm2.setProperty("p.test", "a");
assertFalse(t_prop_parent_setted);
List plList = (List) PrivateAccessor.get(pm1, "plList");
assertEquals(2, plList.size());
pm2 = null;
System.gc();
Thread.sleep(500);
System.gc();
// 当子配置释放后, 再次触发父配置的事件后, 会将注册的事件删除
pm1.setProperty("p.test", "b");
assertEquals(1, plList.size());
}
public static String t_prop_parent;
public static boolean t_prop_parent_setted;
public static void setPropParent(String v)
{
t_prop_parent_setted = true;
}
static PropertiesManager nowPM;
static void setBaseName(String name)
{
System.out.println("preReadBaseNameTest:" + nowPM.getResolvedProperty("testName"));
}
} | apache-2.0 |
geeksaga/forest | forestHibernate/src/test/java/com/geeksaga/common/crypt/KeyHandleTest.java | 353 | package com.geeksaga.common.crypt;
import java.io.IOException;
import javax.crypto.SecretKey;
import org.junit.Test;
public class KeyHandleTest
{
@Test
public void testDefault() throws IOException, Exception
{
SecretKey secretKey = KeyHandle.createKey();
KeyHandle.writeKey(secretKey, KeyHandle.loadKeyStore());
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/DetachVpnGatewayRequestMarshaller.java | 2129 | /*
* 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.ec2.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;
/**
* DetachVpnGatewayRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DetachVpnGatewayRequestMarshaller implements Marshaller<Request<DetachVpnGatewayRequest>, DetachVpnGatewayRequest> {
public Request<DetachVpnGatewayRequest> marshall(DetachVpnGatewayRequest detachVpnGatewayRequest) {
if (detachVpnGatewayRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
Request<DetachVpnGatewayRequest> request = new DefaultRequest<DetachVpnGatewayRequest>(detachVpnGatewayRequest, "AmazonEC2");
request.addParameter("Action", "DetachVpnGateway");
request.addParameter("Version", "2016-11-15");
request.setHttpMethod(HttpMethodName.POST);
if (detachVpnGatewayRequest.getVpcId() != null) {
request.addParameter("VpcId", StringUtils.fromString(detachVpnGatewayRequest.getVpcId()));
}
if (detachVpnGatewayRequest.getVpnGatewayId() != null) {
request.addParameter("VpnGatewayId", StringUtils.fromString(detachVpnGatewayRequest.getVpnGatewayId()));
}
return request;
}
}
| apache-2.0 |
ljaljushkin/PatternPractise | from_nikita/myproject/src/main/java/Ellipse.java | 458 |
public class Ellipse implements IFigure {
private int x, y, rx, ry;
public Ellipse() {
super();
}
public void init(int x, int y, int rx, int ry) {
this.x = x;
this.y = y;
this.rx = rx;
this.ry = ry;
}
public Ellipse clone()throws CloneNotSupportedException {
return new Ellipse();
}
public void draw(IPainter painter) {
painter.drawEllipse(x, y, rx, ry);
};
}
| apache-2.0 |
reynoldsm88/drools | drools-compiler/src/test/java/org/drools/compiler/integrationtests/session/StatelessSessionTest.java | 12445 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.compiler.integrationtests.session;
import org.drools.compiler.Cheese;
import org.drools.compiler.Cheesery;
import org.drools.compiler.CommonTestMethodBase;
import org.drools.compiler.integrationtests.SerializationHelper;
import org.drools.core.command.impl.ExecutableCommand;
import org.drools.core.command.runtime.BatchExecutionCommandImpl;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.KnowledgeBaseFactory;
import org.junit.Test;
import org.kie.api.KieBase;
import org.kie.api.KieBaseConfiguration;
import org.kie.api.command.Command;
import org.kie.api.definition.KiePackage;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.Channel;
import org.kie.api.runtime.ExecutionResults;
import org.kie.api.runtime.StatelessKieSession;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.command.CommandFactory;
import org.kie.internal.conf.SequentialOption;
import org.kie.internal.io.ResourceFactory;
import org.kie.internal.runtime.StatelessKnowledgeSession;
import org.mockito.Mockito;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
public class StatelessSessionTest extends CommonTestMethodBase {
final List list = new ArrayList();
final Cheesery cheesery = new Cheesery();
@Test
public void testSingleObjectAssert() throws Exception {
final StatelessKieSession session = getSession2( "statelessSessionTest.drl" );
final Cheese stilton = new Cheese( "stilton",
5 );
session.execute( stilton );
assertEquals( "stilton", list.get( 0 ) );
}
@Test
public void testArrayObjectAssert() throws Exception {
final StatelessKieSession session = getSession2( "statelessSessionTest.drl" );
final Cheese stilton = new Cheese( "stilton",
5 );
session.execute( Arrays.asList( new Object[]{stilton} ) );
assertEquals( "stilton",
list.get( 0 ) );
}
@Test
public void testCollectionObjectAssert() throws Exception {
final StatelessKieSession session = getSession2( "statelessSessionTest.drl" );
final Cheese stilton = new Cheese( "stilton",
5 );
final List collection = new ArrayList();
collection.add( stilton );
session.execute( collection );
assertEquals( "stilton",
list.get( 0 ) );
}
@Test
public void testInsertObject() throws Exception {
String str = "";
str += "package org.kie \n";
str += "import org.drools.compiler.Cheese \n";
str += "rule rule1 \n";
str += " when \n";
str += " $c : Cheese() \n";
str += " \n";
str += " then \n";
str += " $c.setPrice( 30 ); \n";
str += "end\n";
Cheese stilton = new Cheese( "stilton", 5 );
final StatelessKieSession ksession = getSession2( ResourceFactory.newByteArrayResource( str.getBytes() ) );
final ExecutableCommand cmd = (ExecutableCommand) CommandFactory.newInsert( stilton, "outStilton" );
final BatchExecutionCommandImpl batch = new BatchExecutionCommandImpl( Arrays.asList( new ExecutableCommand<?>[] { cmd } ) );
final ExecutionResults result = ( ExecutionResults ) ksession.execute( batch );
stilton = ( Cheese ) result.getValue( "outStilton" );
assertEquals( 30,
stilton.getPrice() );
}
@Test
public void testSetGlobal() throws Exception {
String str = "";
str += "package org.kie \n";
str += "import org.drools.compiler.Cheese \n";
str += "global java.util.List list1 \n";
str += "global java.util.List list2 \n";
str += "global java.util.List list3 \n";
str += "rule rule1 \n";
str += " when \n";
str += " $c : Cheese() \n";
str += " \n";
str += " then \n";
str += " $c.setPrice( 30 ); \n";
str += " list1.add( $c ); \n";
str += " list2.add( $c ); \n";
str += " list3.add( $c ); \n";
str += "end\n";
final Cheese stilton = new Cheese( "stilton", 5 );
final List list1 = new ArrayList();
List list2 = new ArrayList();
List list3 = new ArrayList();
final StatelessKieSession ksession = getSession2( ResourceFactory.newByteArrayResource( str.getBytes() ) );
final Command setGlobal1 = CommandFactory.newSetGlobal( "list1", list1 );
final Command setGlobal2 = CommandFactory.newSetGlobal( "list2", list2, true );
final Command setGlobal3 = CommandFactory.newSetGlobal( "list3", list3, "outList3" );
final Command insert = CommandFactory.newInsert( stilton );
final List cmds = new ArrayList();
cmds.add( setGlobal1 );
cmds.add( setGlobal2 );
cmds.add( setGlobal3 );
cmds.add( insert );
final ExecutionResults result = ( ExecutionResults ) ksession.execute( CommandFactory.newBatchExecution( cmds ) );
assertEquals( 30,
stilton.getPrice() );
assertNull( result.getValue( "list1" ) );
list2 = ( List ) result.getValue( "list2" );
assertEquals( 1, list2.size() );
assertSame( stilton, list2.get( 0 ) );
list3 = ( List ) result.getValue( "outList3" );
assertEquals( 1, list3.size() );
assertSame( stilton, list3.get( 0 ) );
}
@Test
public void testQuery() throws Exception {
String str = "";
str += "package org.kie.test \n";
str += "import org.drools.compiler.Cheese \n";
str += "query cheeses \n";
str += " stilton : Cheese(type == 'stilton') \n";
str += " cheddar : Cheese(type == 'cheddar', price == stilton.price) \n";
str += "end\n";
final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( ResourceFactory.newByteArrayResource(str.getBytes()), ResourceType.DRL );
if ( kbuilder.hasErrors() ) {
fail( kbuilder.getErrors().toString() );
}
InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addPackages( kbuilder.getKnowledgePackages() );
kbase = SerializationHelper.serializeObject( kbase );
final StatelessKieSession ksession = kbase.newStatelessKieSession();
final Cheese stilton1 = new Cheese( "stilton", 1);
final Cheese cheddar1 = new Cheese( "cheddar", 1);
final Cheese stilton2 = new Cheese( "stilton", 2);
final Cheese cheddar2 = new Cheese( "cheddar", 2);
final Cheese stilton3 = new Cheese( "stilton", 3);
final Cheese cheddar3 = new Cheese( "cheddar", 3);
final Set set = new HashSet();
List list = new ArrayList();
list.add(stilton1);
list.add(cheddar1);
set.add( list );
list = new ArrayList();
list.add(stilton2);
list.add(cheddar2);
set.add( list );
list = new ArrayList();
list.add(stilton3);
list.add(cheddar3);
set.add( list );
final List<Command> cmds = new ArrayList<Command>();
cmds.add( CommandFactory.newInsert( stilton1 ) );
cmds.add( CommandFactory.newInsert( stilton2 ) );
cmds.add( CommandFactory.newInsert( stilton3 ) );
cmds.add( CommandFactory.newInsert( cheddar1 ) );
cmds.add( CommandFactory.newInsert( cheddar2 ) );
cmds.add( CommandFactory.newInsert( cheddar3 ) );
cmds.add( CommandFactory.newQuery( "cheeses", "cheeses" ) );
final ExecutionResults batchResult = (ExecutionResults) ksession.execute( CommandFactory.newBatchExecution( cmds ) );
final org.kie.api.runtime.rule.QueryResults results = ( org.kie.api.runtime.rule.QueryResults) batchResult.getValue( "cheeses" );
assertEquals( 3, results.size() );
assertEquals( 2, results.getIdentifiers().length );
final Set newSet = new HashSet();
for ( final org.kie.api.runtime.rule.QueryResultsRow result : results ) {
list = new ArrayList();
list.add( result.get( "stilton" ) );
list.add( result.get( "cheddar" ));
newSet.add( list );
}
assertEquals( set, newSet );
}
@Test
public void testNotInStatelessSession() throws Exception {
final KieBaseConfiguration kbc = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
kbc.setOption(SequentialOption.YES);
final KieBase kbase = SerializationHelper.serializeObject(loadKnowledgeBase(kbc, "test_NotInStatelessSession.drl"));
final StatelessKieSession session = kbase.newStatelessKieSession();
final List list = new ArrayList();
session.setGlobal("list", list);
session.execute("not integer");
assertEquals("not integer", list.get(0));
}
@Test
public void testChannels() throws Exception {
String str = "";
str += "package org.kie \n";
str += "import org.drools.compiler.Cheese \n";
str += "rule rule1 \n";
str += " when \n";
str += " $c : Cheese() \n";
str += " \n";
str += " then \n";
str += " channels[\"x\"].send( $c ); \n";
str += "end\n";
final Cheese stilton = new Cheese("stilton", 5);
final Channel channel = Mockito.mock(Channel.class);
final StatelessKieSession ksession = getSession2(ResourceFactory.newByteArrayResource(str.getBytes()));
ksession.registerChannel("x", channel);
assertEquals(1, ksession.getChannels().size());
assertEquals(channel, ksession.getChannels().get("x"));
ksession.execute(stilton);
Mockito.verify(channel).send(stilton);
ksession.unregisterChannel("x");
assertEquals(0, ksession.getChannels().size());
assertNull(ksession.getChannels().get("x"));
}
private StatelessKieSession getSession2(final String fileName) throws Exception {
return getSession2( ResourceFactory.newClassPathResource( fileName, getClass() ) );
}
private StatelessKieSession getSession2(final Resource resource) throws Exception {
final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( resource, ResourceType.DRL );
if (kbuilder.hasErrors() ) {
System.out.println( kbuilder.getErrors() );
}
assertFalse( kbuilder.hasErrors() );
final Collection<KiePackage> pkgs = kbuilder.getKnowledgePackages();
InternalKnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addPackages( pkgs );
kbase = SerializationHelper.serializeObject( kbase );
final StatelessKieSession session = kbase.newStatelessKieSession();
session.setGlobal( "list",
this.list );
session.setGlobal( "cheesery",
this.cheesery );
return session;
}
}
| apache-2.0 |
OSGP/Platform | osgp-adapter-domain-smartmetering/src/main/java/org/opensmartgridplatform/adapter/domain/smartmetering/infra/jms/core/messageprocessors/ActualMeterReadsResponseMessageProcessor.java | 3314 | /**
* Copyright 2015 Smart Society Services B.V.
*
* 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
*/
package org.opensmartgridplatform.adapter.domain.smartmetering.infra.jms.core.messageprocessors;
import org.opensmartgridplatform.adapter.domain.smartmetering.application.services.MonitoringService;
import org.opensmartgridplatform.adapter.domain.smartmetering.infra.jms.core.OsgpCoreResponseMessageProcessor;
import org.opensmartgridplatform.adapter.domain.smartmetering.infra.jms.ws.WebServiceResponseMessageSender;
import org.opensmartgridplatform.dto.valueobjects.smartmetering.MeterReadsGasResponseDto;
import org.opensmartgridplatform.dto.valueobjects.smartmetering.MeterReadsResponseDto;
import org.opensmartgridplatform.shared.exceptionhandling.ComponentType;
import org.opensmartgridplatform.shared.exceptionhandling.OsgpException;
import org.opensmartgridplatform.shared.infra.jms.DeviceMessageMetadata;
import org.opensmartgridplatform.shared.infra.jms.MessageProcessorMap;
import org.opensmartgridplatform.shared.infra.jms.MessageType;
import org.opensmartgridplatform.shared.infra.jms.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class ActualMeterReadsResponseMessageProcessor extends OsgpCoreResponseMessageProcessor {
@Autowired
private MonitoringService monitoringService;
@Autowired
protected ActualMeterReadsResponseMessageProcessor(
WebServiceResponseMessageSender responseMessageSender,
@Qualifier("domainSmartMeteringOsgpCoreResponseMessageProcessorMap") MessageProcessorMap messageProcessorMap) {
super(responseMessageSender, messageProcessorMap, MessageType.REQUEST_ACTUAL_METER_DATA,
ComponentType.DOMAIN_SMART_METERING);
}
@Override
protected boolean hasRegularResponseObject(final ResponseMessage responseMessage) {
final Object dataObject = responseMessage.getDataObject();
return dataObject instanceof MeterReadsResponseDto || dataObject instanceof MeterReadsGasResponseDto;
}
@Override
protected void handleMessage(final DeviceMessageMetadata deviceMessageMetadata,
final ResponseMessage responseMessage, final OsgpException osgpException) {
if (responseMessage.getDataObject() instanceof MeterReadsResponseDto) {
final MeterReadsResponseDto actualMeterReadsDto = (MeterReadsResponseDto) responseMessage.getDataObject();
this.monitoringService.handleActualMeterReadsResponse(deviceMessageMetadata, responseMessage.getResult(),
osgpException, actualMeterReadsDto);
} else if (responseMessage.getDataObject() instanceof MeterReadsGasResponseDto) {
final MeterReadsGasResponseDto meterReadsGas = (MeterReadsGasResponseDto) responseMessage.getDataObject();
this.monitoringService.handleActualMeterReadsResponse(deviceMessageMetadata, responseMessage.getResult(),
osgpException, meterReadsGas);
}
}
}
| apache-2.0 |
AttwellBrian/RxJava | src/main/java/io/reactivex/processors/AsyncProcessor.java | 9739 | /**
* Copyright (c) 2016-present, RxJava 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 io.reactivex.processors;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;
import io.reactivex.annotations.*;
import io.reactivex.internal.subscriptions.DeferredScalarSubscription;
import io.reactivex.plugins.RxJavaPlugins;
import org.reactivestreams.*;
/**
* A Subject that emits the very last value followed by a completion event or the received error to Subscribers.
*
* <p>The implementation of onXXX methods are technically thread-safe but non-serialized calls
* to them may lead to undefined state in the currently subscribed Subscribers.
*
* @param <T> the value type
*/
public final class AsyncProcessor<T> extends FlowableProcessor<T> {
@SuppressWarnings("rawtypes")
static final AsyncSubscription[] EMPTY = new AsyncSubscription[0];
@SuppressWarnings("rawtypes")
static final AsyncSubscription[] TERMINATED = new AsyncSubscription[0];
final AtomicReference<AsyncSubscription<T>[]> subscribers;
/** Write before updating subscribers, read after reading subscribers as TERMINATED. */
Throwable error;
/** Write before updating subscribers, read after reading subscribers as TERMINATED. */
T value;
/**
* Creates a new AsyncProcessor.
* @param <T> the value type to be received and emitted
* @return the new AsyncProcessor instance
*/
@CheckReturnValue
@NonNull
public static <T> AsyncProcessor<T> create() {
return new AsyncProcessor<T>();
}
/**
* Constructs an AsyncProcessor.
* @since 2.0
*/
@SuppressWarnings("unchecked")
AsyncProcessor() {
this.subscribers = new AtomicReference<AsyncSubscription<T>[]>(EMPTY);
}
@Override
public void onSubscribe(Subscription s) {
if (subscribers.get() == TERMINATED) {
s.cancel();
return;
}
// PublishSubject doesn't bother with request coordination.
s.request(Long.MAX_VALUE);
}
@Override
public void onNext(T t) {
if (subscribers.get() == TERMINATED) {
return;
}
if (t == null) {
nullOnNext();
return;
}
value = t;
}
@SuppressWarnings("unchecked")
void nullOnNext() {
value = null;
Throwable ex = new NullPointerException("onNext called with null. Null values are generally not allowed in 2.x operators and sources.");
error = ex;
for (AsyncSubscription<T> as : subscribers.getAndSet(TERMINATED)) {
as.onError(ex);
}
}
@SuppressWarnings("unchecked")
@Override
public void onError(Throwable t) {
if (t == null) {
t = new NullPointerException("onError called with null. Null values are generally not allowed in 2.x operators and sources.");
}
if (subscribers.get() == TERMINATED) {
RxJavaPlugins.onError(t);
return;
}
value = null;
error = t;
for (AsyncSubscription<T> as : subscribers.getAndSet(TERMINATED)) {
as.onError(t);
}
}
@SuppressWarnings("unchecked")
@Override
public void onComplete() {
if (subscribers.get() == TERMINATED) {
return;
}
T v = value;
AsyncSubscription<T>[] array = subscribers.getAndSet(TERMINATED);
if (v == null) {
for (AsyncSubscription<T> as : array) {
as.onComplete();
}
} else {
for (AsyncSubscription<T> as : array) {
as.complete(v);
}
}
}
@Override
public boolean hasSubscribers() {
return subscribers.get().length != 0;
}
@Override
public boolean hasThrowable() {
return subscribers.get() == TERMINATED && error != null;
}
@Override
public boolean hasComplete() {
return subscribers.get() == TERMINATED && error == null;
}
@Override
public Throwable getThrowable() {
return subscribers.get() == TERMINATED ? error : null;
}
@Override
protected void subscribeActual(Subscriber<? super T> s) {
AsyncSubscription<T> as = new AsyncSubscription<T>(s, this);
s.onSubscribe(as);
if (add(as)) {
if (as.isCancelled()) {
remove(as);
}
} else {
Throwable ex = error;
if (ex != null) {
s.onError(ex);
} else {
T v = value;
if (v != null) {
as.complete(v);
} else {
as.onComplete();
}
}
}
}
/**
* Tries to add the given subscriber to the subscribers array atomically
* or returns false if the subject has terminated.
* @param ps the subscriber to add
* @return true if successful, false if the subject has terminated
*/
boolean add(AsyncSubscription<T> ps) {
for (;;) {
AsyncSubscription<T>[] a = subscribers.get();
if (a == TERMINATED) {
return false;
}
int n = a.length;
@SuppressWarnings("unchecked")
AsyncSubscription<T>[] b = new AsyncSubscription[n + 1];
System.arraycopy(a, 0, b, 0, n);
b[n] = ps;
if (subscribers.compareAndSet(a, b)) {
return true;
}
}
}
/**
* Atomically removes the given subscriber if it is subscribed to the subject.
* @param ps the subject to remove
*/
@SuppressWarnings("unchecked")
void remove(AsyncSubscription<T> ps) {
for (;;) {
AsyncSubscription<T>[] a = subscribers.get();
int n = a.length;
if (n == 0) {
return;
}
int j = -1;
for (int i = 0; i < n; i++) {
if (a[i] == ps) {
j = i;
break;
}
}
if (j < 0) {
return;
}
AsyncSubscription<T>[] b;
if (n == 1) {
b = EMPTY;
} else {
b = new AsyncSubscription[n - 1];
System.arraycopy(a, 0, b, 0, j);
System.arraycopy(a, j + 1, b, j, n - j - 1);
}
if (subscribers.compareAndSet(a, b)) {
return;
}
}
}
/**
* Returns true if the subject has any value.
* <p>The method is thread-safe.
* @return true if the subject has any value
*/
public boolean hasValue() {
return subscribers.get() == TERMINATED && value != null;
}
/**
* Returns a single value the Subject currently has or null if no such value exists.
* <p>The method is thread-safe.
* @return a single value the Subject currently has or null if no such value exists
*/
public T getValue() {
return subscribers.get() == TERMINATED ? value : null;
}
/**
* Returns an Object array containing snapshot all values of the Subject.
* <p>The method is thread-safe.
* @return the array containing the snapshot of all values of the Subject
*/
public Object[] getValues() {
T v = getValue();
return v != null ? new Object[] { v } : new Object[0];
}
/**
* Returns a typed array containing a snapshot of all values of the Subject.
* <p>The method follows the conventions of Collection.toArray by setting the array element
* after the last value to null (if the capacity permits).
* <p>The method is thread-safe.
* @param array the target array to copy values into if it fits
* @return the given array if the values fit into it or a new array containing all values
*/
public T[] getValues(T[] array) {
T v = getValue();
if (v == null) {
if (array.length != 0) {
array[0] = null;
}
return array;
}
if (array.length == 0) {
array = Arrays.copyOf(array, 1);
}
array[0] = v;
if (array.length != 1) {
array[1] = null;
}
return array;
}
static final class AsyncSubscription<T> extends DeferredScalarSubscription<T> {
private static final long serialVersionUID = 5629876084736248016L;
final AsyncProcessor<T> parent;
AsyncSubscription(Subscriber<? super T> actual, AsyncProcessor<T> parent) {
super(actual);
this.parent = parent;
}
@Override
public void cancel() {
if (super.tryCancel()) {
parent.remove(this);
}
}
void onComplete() {
if (!isCancelled()) {
actual.onComplete();
}
}
void onError(Throwable t) {
if (isCancelled()) {
RxJavaPlugins.onError(t);
} else {
actual.onError(t);
}
}
}
}
| apache-2.0 |
vespa-engine/vespa | vespajlib/src/test/java/com/yahoo/concurrent/ThreadFactoryFactoryTest.java | 1386 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.concurrent;
import org.junit.Test;
import java.util.concurrent.ThreadFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author baldersheim
*/
public class ThreadFactoryFactoryTest {
static class Runner implements Runnable {
@Override
public void run() {
}
}
@Test
public void requireThatFactoryCreatesCorrectlyNamedThreads() {
Thread thread = ThreadFactoryFactory.getThreadFactory("a").newThread(new Runner());
assertEquals("a-1-thread-1", thread.getName());
thread = ThreadFactoryFactory.getThreadFactory("a").newThread(new Runner());
assertEquals("a-2-thread-1", thread.getName());
thread = ThreadFactoryFactory.getThreadFactory("b").newThread(new Runner());
assertEquals("b-1-thread-1", thread.getName());
ThreadFactory factory = ThreadFactoryFactory.getThreadFactory("a");
thread = factory.newThread(new Runner());
assertEquals("a-3-thread-1", thread.getName());
thread = factory.newThread(new Runner());
assertEquals("a-3-thread-2", thread.getName());
thread = factory.newThread(new Runner());
assertEquals("a-3-thread-3", thread.getName());
}
}
| apache-2.0 |
T5750/maven-archetype-templates | SpringCloud/eureka-ribbon/src/main/java/com/evangel/RibbonApplication.java | 783 | package com.evangel;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class RibbonApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class, args);
}
}
// http://localhost:3333/add
| apache-2.0 |
thilinicooray/carbon-apimgt | components/apimgt/org.wso2.carbon.apimgt.rest.api.publisher/src/gen/java/org/wso2/carbon/apimgt/rest/api/publisher/ApisApi.java | 35207 | package org.wso2.carbon.apimgt.rest.api.publisher;
import org.wso2.carbon.apimgt.rest.api.publisher.dto.*;
import org.wso2.carbon.apimgt.rest.api.publisher.ApisApiService;
import org.wso2.carbon.apimgt.rest.api.publisher.factories.ApisApiServiceFactory;
import io.swagger.annotations.ApiParam;
import org.wso2.carbon.apimgt.rest.api.publisher.dto.ErrorDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.dto.APIListDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.dto.DocumentListDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.dto.DocumentDTO;
import java.io.File;
import org.wso2.carbon.apimgt.rest.api.publisher.dto.FileInfoDTO;
import java.util.List;
import java.io.InputStream;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.apache.cxf.jaxrs.ext.multipart.Multipart;
import javax.ws.rs.core.Response;
import javax.ws.rs.*;
@Path("/apis")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.Api(value = "/apis", description = "the apis API")
public class ApisApi {
private final ApisApiService delegate = ApisApiServiceFactory.getApisApi();
@GET
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Get all APIs\n", notes = "Get a list of available APIs qualifying under a given search condition.\n", response = APIListDTO.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nList of qualifying APIs is returned.\n"),
@io.swagger.annotations.ApiResponse(code = 304, message = "Not Modified.\nEmpty body because the client has already the latest version of the requested resource.\n"),
@io.swagger.annotations.ApiResponse(code = 406, message = "Not Acceptable.\nThe requested media type is not supported\n") })
public Response apisGet(@ApiParam(value = "Maximum size of resource array to return.\n", defaultValue="25") @QueryParam("limit") Integer limit,
@ApiParam(value = "Starting point within the complete list of items qualified.\n", defaultValue="0") @QueryParam("offset") Integer offset,
@ApiParam(value = "**Search condition**.\n\nYou can search in attributes by using an **\"attribute:\"** modifier.\n\nEg. \"provider:wso2\" will match an API if the provider of the API contains \"wso2\".\n\nSupported attribute modifiers are [**version, context, status,\ndescription, subcontext, doc, provider**]\n\nIf no advanced attribute modifier has been specified, search will match the\ngiven query string against API Name.\n") @QueryParam("query") String query,
@ApiParam(value = "Media types acceptable for the response. Default is JSON.\n" , defaultValue="JSON")@HeaderParam("Accept") String accept,
@ApiParam(value = "Validator for conditional requests; based on the ETag of the formerly retrieved\nvariant of the resourec.\n" )@HeaderParam("If-None-Match") String ifNoneMatch)
{
return delegate.apisGet(limit,offset,query,accept,ifNoneMatch);
}
@POST
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Create a new API", notes = "Create a new API\n", response = APIDTO.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 201, message = "Created.\nSuccessful response with the newly created object as entity in the body.\nLocation header contains URL of newly created entity.\n"),
@io.swagger.annotations.ApiResponse(code = 400, message = "Bad Request.\nInvalid request or validation error.\n"),
@io.swagger.annotations.ApiResponse(code = 415, message = "Unsupported Media Type.\nThe entity of the request was in a not supported format.\n") })
public Response apisPost(@ApiParam(value = "API object that needs to be added\n" ,required=true ) APIDTO body,
@ApiParam(value = "Media type of the entity in the body. Default is JSON.\n" ,required=true , defaultValue="JSON")@HeaderParam("Content-Type") String contentType)
{
return delegate.apisPost(body,contentType);
}
@POST
@Path("/change-lifecycle")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Change API Status", notes = "Change the lifecycle of an API\n", response = void.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nLifecycle changed successfully.\n"),
@io.swagger.annotations.ApiResponse(code = 400, message = "Bad Request.\nInvalid request or validation error\n"),
@io.swagger.annotations.ApiResponse(code = 404, message = "Not Found.\nRequested API does not exist.\n"),
@io.swagger.annotations.ApiResponse(code = 412, message = "Precondition Failed.\nThe request has not been performed because one of the preconditions is not met.\n") })
public Response apisChangeLifecyclePost(@ApiParam(value = "The action to demote or promote the state of the API.\n\nSupported actions are [ **Publish, Deploy as a Prototype, Demote to Created, Demote to Prototyped, Block, Deprecate, Re-Publish, Retire **]\n",required=true, allowableValues="{values=[Publish, Deploy as a Prototype, Demote to Created, Demote to Prototyped, Block, Deprecate, Re-Publish, Retire]}") @QueryParam("action") String action,
@ApiParam(value = "**API ID** consisting of the **UUID** of the API.\nThe combination of the provider of the API, name of the API and the version is also accepted as a valid API I.\nShould be formatted as **provider-name-version**.\n",required=true) @QueryParam("apiId") String apiId,
@ApiParam(value = "\nYou can specify additional checklist items by using an **\"attribute:\"** modifier.\n\nEg: \"Deprecate Old Versions:true\" will deprecate older versions of a particular API when it is promoted to\nPublished state from Created state. Multiple checklist items can be given in \"attribute1:true, attribute2:false\"\nformat.\n\nSupported checklist items are as follows.\n1. **Deprecate Old Versions**: Setting this to true will deprecate older versions of a particular API when it is promoted to Published state from Created state.\n2. **Require Re-Subscription**: If you set this to true, users need to re subscribe to the API although they may have subscribed to an older version.\n") @QueryParam("lifecycleChecklist") String lifecycleChecklist,
@ApiParam(value = "Validator for conditional requests; based on ETag.\n" )@HeaderParam("If-Match") String ifMatch,
@ApiParam(value = "Validator for conditional requests; based on Last Modified header.\n" )@HeaderParam("If-Unmodified-Since") String ifUnmodifiedSince)
{
return delegate.apisChangeLifecyclePost(action,apiId,lifecycleChecklist,ifMatch,ifUnmodifiedSince);
}
@POST
@Path("/copy-api")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Copy API", notes = "Create a new API by copying an existing API\n", response = void.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 201, message = "Created.\nSuccessful response with the newly created API as entity in the body. Location header contains URL of newly created API.\n"),
@io.swagger.annotations.ApiResponse(code = 400, message = "Bad Request.\nInvalid request or validation error\n"),
@io.swagger.annotations.ApiResponse(code = 404, message = "Not Found.\nAPI to copy does not exist.\n") })
public Response apisCopyApiPost(@ApiParam(value = "Version of the new API.",required=true) @QueryParam("newVersion") String newVersion,
@ApiParam(value = "**API ID** consisting of the **UUID** of the API.\nThe combination of the provider of the API, name of the API and the version is also accepted as a valid API I.\nShould be formatted as **provider-name-version**.\n",required=true) @QueryParam("apiId") String apiId)
{
return delegate.apisCopyApiPost(newVersion,apiId);
}
@GET
@Path("/{apiId}")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Get API details", notes = "Get details of an API\n", response = APIDTO.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nRequested API is returned\n"),
@io.swagger.annotations.ApiResponse(code = 304, message = "Not Modified.\nEmpty body because the client has already the latest version of the requested resource.\n"),
@io.swagger.annotations.ApiResponse(code = 404, message = "Not Found.\nRequested API does not exist.\n"),
@io.swagger.annotations.ApiResponse(code = 406, message = "Not Acceptable.\nThe requested media type is not supported\n") })
public Response apisApiIdGet(@ApiParam(value = "**API ID** consisting of the **UUID** of the API.\nThe combination of the provider of the API, name of the API and the version is also accepted as a valid API ID.\nShould be formatted as **provider-name-version**.\n",required=true ) @PathParam("apiId") String apiId,
@ApiParam(value = "Media types acceptable for the response. Default is JSON.\n" , defaultValue="JSON")@HeaderParam("Accept") String accept,
@ApiParam(value = "Validator for conditional requests; based on the ETag of the formerly retrieved\nvariant of the resourec.\n" )@HeaderParam("If-None-Match") String ifNoneMatch,
@ApiParam(value = "Validator for conditional requests; based on Last Modified header of the\nformerly retrieved variant of the resource.\n" )@HeaderParam("If-Modified-Since") String ifModifiedSince)
{
return delegate.apisApiIdGet(apiId,accept,ifNoneMatch,ifModifiedSince);
}
@PUT
@Path("/{apiId}")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Update an existing API", notes = "Update an existing API\n", response = APIDTO.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nSuccessful response with updated API object\n"),
@io.swagger.annotations.ApiResponse(code = 400, message = "Bad Request.\nInvalid request or validation error\n"),
@io.swagger.annotations.ApiResponse(code = 403, message = "Forbidden.\nThe request must be conditional but no condition has been specified.\n"),
@io.swagger.annotations.ApiResponse(code = 404, message = "Not Found.\nThe resource to be updated does not exist.\n"),
@io.swagger.annotations.ApiResponse(code = 412, message = "Precondition Failed.\nThe request has not been performed because one of the preconditions is not met.\n") })
public Response apisApiIdPut(@ApiParam(value = "**API ID** consisting of the **UUID** of the API.\nThe combination of the provider of the API, name of the API and the version is also accepted as a valid API ID.\nShould be formatted as **provider-name-version**.\n",required=true ) @PathParam("apiId") String apiId,
@ApiParam(value = "API object that needs to be added\n" ,required=true ) APIDTO body,
@ApiParam(value = "Media type of the entity in the body. Default is JSON.\n" ,required=true , defaultValue="JSON")@HeaderParam("Content-Type") String contentType,
@ApiParam(value = "Validator for conditional requests; based on ETag.\n" )@HeaderParam("If-Match") String ifMatch,
@ApiParam(value = "Validator for conditional requests; based on Last Modified header.\n" )@HeaderParam("If-Unmodified-Since") String ifUnmodifiedSince)
{
return delegate.apisApiIdPut(apiId,body,contentType,ifMatch,ifUnmodifiedSince);
}
@DELETE
@Path("/{apiId}")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Delete API", notes = "Delete an existing API\n", response = void.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nResource successfully deleted.\n"),
@io.swagger.annotations.ApiResponse(code = 403, message = "Forbidden.\nThe request must be conditional but no condition has been specified.\n"),
@io.swagger.annotations.ApiResponse(code = 404, message = "Not Found.\nResource to be deleted does not exist.\n"),
@io.swagger.annotations.ApiResponse(code = 412, message = "Precondition Failed.\nThe request has not been performed because one of the preconditions is not met.\n") })
public Response apisApiIdDelete(@ApiParam(value = "**API ID** consisting of the **UUID** of the API.\nThe combination of the provider of the API, name of the API and the version is also accepted as a valid API ID.\nShould be formatted as **provider-name-version**.\n",required=true ) @PathParam("apiId") String apiId,
@ApiParam(value = "Validator for conditional requests; based on ETag.\n" )@HeaderParam("If-Match") String ifMatch,
@ApiParam(value = "Validator for conditional requests; based on Last Modified header.\n" )@HeaderParam("If-Unmodified-Since") String ifUnmodifiedSince)
{
return delegate.apisApiIdDelete(apiId,ifMatch,ifUnmodifiedSince);
}
@GET
@Path("/{apiId}/documents")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Get API Documents", notes = "Get a list of documents belonging to an API.\n", response = DocumentListDTO.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nDocument list is returned.\n"),
@io.swagger.annotations.ApiResponse(code = 304, message = "Not Modified.\nEmpty body because the client has already the latest version of the requested resource.\n"),
@io.swagger.annotations.ApiResponse(code = 404, message = "Not Found.\nRequested API does not exist.\n"),
@io.swagger.annotations.ApiResponse(code = 406, message = "Not Acceptable.\nThe requested media type is not supported\n") })
public Response apisApiIdDocumentsGet(@ApiParam(value = "**API ID** consisting of the **UUID** of the API.\nThe combination of the provider of the API, name of the API and the version is also accepted as a valid API ID.\nShould be formatted as **provider-name-version**.\n",required=true ) @PathParam("apiId") String apiId,
@ApiParam(value = "Maximum size of resource array to return.\n", defaultValue="25") @QueryParam("limit") Integer limit,
@ApiParam(value = "Starting point within the complete list of items qualified.\n", defaultValue="0") @QueryParam("offset") Integer offset,
@ApiParam(value = "Media types acceptable for the response. Default is JSON.\n" , defaultValue="JSON")@HeaderParam("Accept") String accept,
@ApiParam(value = "Validator for conditional requests; based on the ETag of the formerly retrieved\nvariant of the resourec.\n" )@HeaderParam("If-None-Match") String ifNoneMatch)
{
return delegate.apisApiIdDocumentsGet(apiId,limit,offset,accept,ifNoneMatch);
}
@POST
@Path("/{apiId}/documents")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Add a new document", notes = "Add a new document to an API\n", response = DocumentDTO.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 201, message = "Created.\nSuccessful response with the newly created Document object as entity in the body.\nLocation header contains URL of newly added document.\n"),
@io.swagger.annotations.ApiResponse(code = 400, message = "Bad Request.\nInvalid request or validation error\n"),
@io.swagger.annotations.ApiResponse(code = 415, message = "Unsupported media type.\nThe entity of the request was in a not supported format.\n") })
public Response apisApiIdDocumentsPost(@ApiParam(value = "**API ID** consisting of the **UUID** of the API.\nThe combination of the provider of the API, name of the API and the version is also accepted as a valid API ID.\nShould be formatted as **provider-name-version**.\n",required=true ) @PathParam("apiId") String apiId,
@ApiParam(value = "Document object that needs to be added\n" ,required=true ) DocumentDTO body,
@ApiParam(value = "Media type of the entity in the body. Default is JSON.\n" ,required=true , defaultValue="JSON")@HeaderParam("Content-Type") String contentType)
{
return delegate.apisApiIdDocumentsPost(apiId,body,contentType);
}
@GET
@Path("/{apiId}/documents/{documentId}")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Get an API Document", notes = "Get a particular document associated with an API.\n", response = DocumentDTO.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nDocument returned.\n"),
@io.swagger.annotations.ApiResponse(code = 304, message = "Not Modified.\nEmpty body because the client has already the latest version of the requested resource.\n"),
@io.swagger.annotations.ApiResponse(code = 404, message = "Not Found.\nRequested Document does not exist.\n"),
@io.swagger.annotations.ApiResponse(code = 406, message = "Not Acceptable.\nThe requested media type is not supported\n") })
public Response apisApiIdDocumentsDocumentIdGet(@ApiParam(value = "**API ID** consisting of the **UUID** of the API.\nThe combination of the provider of the API, name of the API and the version is also accepted as a valid API ID.\nShould be formatted as **provider-name-version**.\n",required=true ) @PathParam("apiId") String apiId,
@ApiParam(value = "**Document Identifier**\n",required=true ) @PathParam("documentId") String documentId,
@ApiParam(value = "Media types acceptable for the response. Default is JSON.\n" , defaultValue="JSON")@HeaderParam("Accept") String accept,
@ApiParam(value = "Validator for conditional requests; based on the ETag of the formerly retrieved\nvariant of the resourec.\n" )@HeaderParam("If-None-Match") String ifNoneMatch,
@ApiParam(value = "Validator for conditional requests; based on Last Modified header of the\nformerly retrieved variant of the resource.\n" )@HeaderParam("If-Modified-Since") String ifModifiedSince)
{
return delegate.apisApiIdDocumentsDocumentIdGet(apiId,documentId,accept,ifNoneMatch,ifModifiedSince);
}
@PUT
@Path("/{apiId}/documents/{documentId}")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Update an API Document", notes = "Update document details.\n", response = DocumentDTO.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nDocument updated\n"),
@io.swagger.annotations.ApiResponse(code = 400, message = "Bad Request.\nInvalid request or validation error.\n"),
@io.swagger.annotations.ApiResponse(code = 404, message = "Not Found.\nThe resource to be updated does not exist.\n"),
@io.swagger.annotations.ApiResponse(code = 412, message = "Precondition Failed.\nThe request has not been performed because one of the preconditions is not met.\n") })
public Response apisApiIdDocumentsDocumentIdPut(@ApiParam(value = "**API ID** consisting of the **UUID** of the API.\nThe combination of the provider of the API, name of the API and the version is also accepted as a valid API ID.\nShould be formatted as **provider-name-version**.\n",required=true ) @PathParam("apiId") String apiId,
@ApiParam(value = "**Document Identifier**\n",required=true ) @PathParam("documentId") String documentId,
@ApiParam(value = "Document object that needs to be added\n" ,required=true ) DocumentDTO body,
@ApiParam(value = "Media type of the entity in the body. Default is JSON.\n" ,required=true , defaultValue="JSON")@HeaderParam("Content-Type") String contentType,
@ApiParam(value = "Validator for conditional requests; based on ETag.\n" )@HeaderParam("If-Match") String ifMatch,
@ApiParam(value = "Validator for conditional requests; based on Last Modified header.\n" )@HeaderParam("If-Unmodified-Since") String ifUnmodifiedSince)
{
return delegate.apisApiIdDocumentsDocumentIdPut(apiId,documentId,body,contentType,ifMatch,ifUnmodifiedSince);
}
@DELETE
@Path("/{apiId}/documents/{documentId}")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Delete an API Document", notes = "Delete a document of an API\n", response = void.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nResource successfully deleted.\n"),
@io.swagger.annotations.ApiResponse(code = 404, message = "Not Found.\nResource to be deleted does not exist.\n"),
@io.swagger.annotations.ApiResponse(code = 412, message = "Precondition Failed.\nThe request has not been performed because one of the preconditions is not met.\n") })
public Response apisApiIdDocumentsDocumentIdDelete(@ApiParam(value = "**API ID** consisting of the **UUID** of the API.\nThe combination of the provider of the API, name of the API and the version is also accepted as a valid API ID.\nShould be formatted as **provider-name-version**.\n",required=true ) @PathParam("apiId") String apiId,
@ApiParam(value = "**Document Identifier**\n",required=true ) @PathParam("documentId") String documentId,
@ApiParam(value = "Validator for conditional requests; based on ETag.\n" )@HeaderParam("If-Match") String ifMatch,
@ApiParam(value = "Validator for conditional requests; based on Last Modified header.\n" )@HeaderParam("If-Unmodified-Since") String ifUnmodifiedSince)
{
return delegate.apisApiIdDocumentsDocumentIdDelete(apiId,documentId,ifMatch,ifUnmodifiedSince);
}
@GET
@Path("/{apiId}/documents/{documentId}/content")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Get document content", notes = "Downloads a FILE type document/get the inline content or source url of a certain document.\n", response = void.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nFile or inline content returned.\n"),
@io.swagger.annotations.ApiResponse(code = 303, message = "See Other.\nSource can be retrived from the URL specified at the Location header.\n"),
@io.swagger.annotations.ApiResponse(code = 304, message = "Not Modified.\nEmpty body because the client has already the latest version of the requested resource.\n"),
@io.swagger.annotations.ApiResponse(code = 404, message = "Not Found.\nRequested Document does not exist.\n"),
@io.swagger.annotations.ApiResponse(code = 406, message = "Not Acceptable.\nThe requested media type is not supported\n") })
public Response apisApiIdDocumentsDocumentIdContentGet(@ApiParam(value = "**API ID** consisting of the **UUID** of the API.\nThe combination of the provider of the API, name of the API and the version is also accepted as a valid API ID.\nShould be formatted as **provider-name-version**.\n",required=true ) @PathParam("apiId") String apiId,
@ApiParam(value = "**Document Identifier**\n",required=true ) @PathParam("documentId") String documentId,
@ApiParam(value = "Media types acceptable for the response. Default is JSON.\n" , defaultValue="JSON")@HeaderParam("Accept") String accept,
@ApiParam(value = "Validator for conditional requests; based on the ETag of the formerly retrieved\nvariant of the resourec.\n" )@HeaderParam("If-None-Match") String ifNoneMatch,
@ApiParam(value = "Validator for conditional requests; based on Last Modified header of the\nformerly retrieved variant of the resource.\n" )@HeaderParam("If-Modified-Since") String ifModifiedSince)
{
return delegate.apisApiIdDocumentsDocumentIdContentGet(apiId,documentId,accept,ifNoneMatch,ifModifiedSince);
}
@POST
@Path("/{apiId}/documents/{documentId}/content")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Update API document content.", notes = "Upload a file to a document or add inline content to the document.\n\nDocument's source type should be **FILE** in order to upload a file to the document using **file** parameter.\nDocument's source type should be **INLINE** in order to add inline content to the document using **inlineContent** parameter.\n\nOnly one of **file** or **inlineContent** can be specified at one time.\n", response = DocumentDTO.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nDocument updated\n"),
@io.swagger.annotations.ApiResponse(code = 400, message = "Bad Request.\nInvalid request or validation error.\n"),
@io.swagger.annotations.ApiResponse(code = 404, message = "Not Found.\nThe resource to be updated does not exist.\n"),
@io.swagger.annotations.ApiResponse(code = 412, message = "Precondition Failed.\nThe request has not been performed because one of the preconditions is not met.\n") })
public Response apisApiIdDocumentsDocumentIdContentPost(@ApiParam(value = "**API ID** consisting of the **UUID** of the API.\nThe combination of the provider of the API, name of the API and the version is also accepted as a valid API ID.\nShould be formatted as **provider-name-version**.\n",required=true ) @PathParam("apiId") String apiId,
@ApiParam(value = "**Document Identifier**\n",required=true ) @PathParam("documentId") String documentId,
@ApiParam(value = "Media type of the entity in the body. Default is JSON.\n" ,required=true , defaultValue="JSON")@HeaderParam("Content-Type") String contentType,
@ApiParam(value = "Document to upload") @Multipart(value = "file", required = false) InputStream fileInputStream,
@ApiParam(value = "Document to upload : details") @Multipart(value = "file" , required = false) Attachment fileDetail,
@ApiParam(value = "Inline content of the document" )@Multipart(value = "inlineContent", required = false) String inlineContent,
@ApiParam(value = "Validator for conditional requests; based on ETag.\n" )@HeaderParam("If-Match") String ifMatch,
@ApiParam(value = "Validator for conditional requests; based on Last Modified header.\n" )@HeaderParam("If-Unmodified-Since") String ifUnmodifiedSince)
{
return delegate.apisApiIdDocumentsDocumentIdContentPost(apiId,documentId,contentType,fileInputStream,fileDetail,inlineContent,ifMatch,ifUnmodifiedSince);
}
@GET
@Path("/{apiId}/swagger")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Get API Definition", notes = "Get the swagger of an API\n", response = void.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nRequested swagger document of the API is returned\n"),
@io.swagger.annotations.ApiResponse(code = 304, message = "Not Modified.\nEmpty body because the client has already the latest version of the requested resource.\n"),
@io.swagger.annotations.ApiResponse(code = 404, message = "Not Found.\nRequested API does not exist.\n"),
@io.swagger.annotations.ApiResponse(code = 406, message = "Not Acceptable.\nThe requested media type is not supported\n") })
public Response apisApiIdSwaggerGet(@ApiParam(value = "**API ID** consisting of the **UUID** of the API.\nThe combination of the provider of the API, name of the API and the version is also accepted as a valid API ID.\nShould be formatted as **provider-name-version**.\n",required=true ) @PathParam("apiId") String apiId,
@ApiParam(value = "Media types acceptable for the response. Default is JSON.\n" , defaultValue="JSON")@HeaderParam("Accept") String accept,
@ApiParam(value = "Validator for conditional requests; based on the ETag of the formerly retrieved\nvariant of the resourec.\n" )@HeaderParam("If-None-Match") String ifNoneMatch,
@ApiParam(value = "Validator for conditional requests; based on Last Modified header of the\nformerly retrieved variant of the resource.\n" )@HeaderParam("If-Modified-Since") String ifModifiedSince)
{
return delegate.apisApiIdSwaggerGet(apiId,accept,ifNoneMatch,ifModifiedSince);
}
@PUT
@Path("/{apiId}/swagger")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Update API Definition", notes = "Update an existing swagger definition of an API\n", response = void.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nSuccessful response with updated Swagger definition\n"),
@io.swagger.annotations.ApiResponse(code = 400, message = "Bad Request.\nInvalid request or validation error\n"),
@io.swagger.annotations.ApiResponse(code = 403, message = "Forbidden.\nThe request must be conditional but no condition has been specified.\n"),
@io.swagger.annotations.ApiResponse(code = 404, message = "Not Found.\nThe resource to be updated does not exist.\n"),
@io.swagger.annotations.ApiResponse(code = 412, message = "Precondition Failed.\nThe request has not been performed because one of the preconditions is not met.\n") })
public Response apisApiIdSwaggerPut(@ApiParam(value = "**API ID** consisting of the **UUID** of the API.\nThe combination of the provider of the API, name of the API and the version is also accepted as a valid API ID.\nShould be formatted as **provider-name-version**.\n",required=true ) @PathParam("apiId") String apiId,
@ApiParam(value = "Swagger definition of the API", required=true )@Multipart(value = "apiDefinition") String apiDefinition,
@ApiParam(value = "Media type of the entity in the body. Default is JSON.\n" ,required=true , defaultValue="JSON")@HeaderParam("Content-Type") String contentType,
@ApiParam(value = "Validator for conditional requests; based on ETag.\n" )@HeaderParam("If-Match") String ifMatch,
@ApiParam(value = "Validator for conditional requests; based on Last Modified header.\n" )@HeaderParam("If-Unmodified-Since") String ifUnmodifiedSince)
{
return delegate.apisApiIdSwaggerPut(apiId,apiDefinition,contentType,ifMatch,ifUnmodifiedSince);
}
@GET
@Path("/{apiId}/thumbnail")
@Consumes({ "application/json" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Get the thumbnail image", notes = "Downloads a thumbnail image of an API\n", response = void.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nThumbnail image returned\n"),
@io.swagger.annotations.ApiResponse(code = 304, message = "Not Modified.\nEmpty body because the client has already the latest version of the requested resource.\n"),
@io.swagger.annotations.ApiResponse(code = 404, message = "Not Found.\nRequested Document does not exist.\n"),
@io.swagger.annotations.ApiResponse(code = 406, message = "Not Acceptable.\nThe requested media type is not supported\n") })
public Response apisApiIdThumbnailGet(@ApiParam(value = "**API ID** consisting of the **UUID** of the API.\nThe combination of the provider of the API, name of the API and the version is also accepted as a valid API ID.\nShould be formatted as **provider-name-version**.\n",required=true ) @PathParam("apiId") String apiId,
@ApiParam(value = "Media types acceptable for the response. Default is JSON.\n" , defaultValue="JSON")@HeaderParam("Accept") String accept,
@ApiParam(value = "Validator for conditional requests; based on the ETag of the formerly retrieved\nvariant of the resourec.\n" )@HeaderParam("If-None-Match") String ifNoneMatch,
@ApiParam(value = "Validator for conditional requests; based on Last Modified header of the\nformerly retrieved variant of the resource.\n" )@HeaderParam("If-Modified-Since") String ifModifiedSince)
{
return delegate.apisApiIdThumbnailGet(apiId,accept,ifNoneMatch,ifModifiedSince);
}
@POST
@Path("/{apiId}/thumbnail")
@Consumes({ "multipart/form-data" })
@Produces({ "application/json" })
@io.swagger.annotations.ApiOperation(value = "Upload a thumbnail image", notes = "Upload a thumbnail image to an API.\n", response = FileInfoDTO.class)
@io.swagger.annotations.ApiResponses(value = {
@io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nImage updated\n"),
@io.swagger.annotations.ApiResponse(code = 400, message = "Bad Request.\nInvalid request or validation error.\n"),
@io.swagger.annotations.ApiResponse(code = 404, message = "Not Found.\nThe resource to be updated does not exist.\n"),
@io.swagger.annotations.ApiResponse(code = 412, message = "Precondition Failed.\nThe request has not been performed because one of the preconditions is not met.\n") })
public Response apisApiIdThumbnailPost(@ApiParam(value = "**API ID** consisting of the **UUID** of the API.\nThe combination of the provider of the API, name of the API and the version is also accepted as a valid API ID.\nShould be formatted as **provider-name-version**.\n",required=true ) @PathParam("apiId") String apiId,
@ApiParam(value = "Image to upload") @Multipart(value = "file") InputStream fileInputStream,
@ApiParam(value = "Image to upload : details") @Multipart(value = "file" ) Attachment fileDetail,
@ApiParam(value = "Media type of the entity in the body. Default is JSON.\n" ,required=true , defaultValue="JSON")@HeaderParam("Content-Type") String contentType,
@ApiParam(value = "Validator for conditional requests; based on ETag.\n" )@HeaderParam("If-Match") String ifMatch,
@ApiParam(value = "Validator for conditional requests; based on Last Modified header.\n" )@HeaderParam("If-Unmodified-Since") String ifUnmodifiedSince)
{
return delegate.apisApiIdThumbnailPost(apiId,fileInputStream,fileDetail,contentType,ifMatch,ifUnmodifiedSince);
}
}
| apache-2.0 |
dgmltn/AndieGraph | app/src/main/java/net/supware/tipro/view/RomPreference.java | 683 | package net.supware.tipro.view;
import android.content.Context;
import android.preference.PreferenceCategory;
import android.widget.Checkable;
import net.supware.tipro.R;
public class RomPreference extends RadioButtonPreference {
public static final String TAG = RomPreference.class.getSimpleName();
int mModelResId;
Checkable mRadioView;
public RomPreference(Context context, PreferenceCategory group, int modelResId, String filename) {
super(context, group);
mModelResId = modelResId;
setWidgetLayoutResource(R.layout.preference_widget_radio);
setTitle(context.getString(mModelResId));
setSummary(filename);
setKey("rom_filename");
setValue(filename);
}
}
| apache-2.0 |
jentfoo/aws-sdk-java | aws-java-sdk-workspaces/src/main/java/com/amazonaws/services/workspaces/model/RevokeIpRulesResult.java | 2328 | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.workspaces.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/workspaces-2015-04-08/RevokeIpRules" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class RevokeIpRulesResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof RevokeIpRulesResult == false)
return false;
RevokeIpRulesResult other = (RevokeIpRulesResult) obj;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
return hashCode;
}
@Override
public RevokeIpRulesResult clone() {
try {
return (RevokeIpRulesResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| apache-2.0 |
taochaoqiang/druid | processing/src/main/java/io/druid/query/groupby/epinephelinae/BufferArrayGrouper.java | 9077 | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.druid.query.groupby.epinephelinae;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.logger.Logger;
import io.druid.java.util.common.parsers.CloseableIterator;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.aggregation.BufferAggregator;
import io.druid.query.groupby.epinephelinae.column.GroupByColumnSelectorStrategy;
import io.druid.segment.ColumnSelectorFactory;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.NoSuchElementException;
/**
* A buffer grouper for array-based aggregation. This grouper stores aggregated values in the buffer using the grouping
* key as the index.
* <p>
* The buffer is divided into 2 separate regions, i.e., used flag buffer and value buffer. The used flag buffer is a
* bit set to represent which keys are valid. If a bit of an index is set, that key is valid. Finally, the value
* buffer is used to store aggregated values. The first index is reserved for
* {@link GroupByColumnSelectorStrategy#GROUP_BY_MISSING_VALUE}.
* <p>
* This grouper is available only when the grouping key is a single indexed dimension of a known cardinality because it
* directly uses the dimension value as the index for array access. Since the cardinality for the grouping key across
* different segments cannot be currently retrieved, this grouper can be used only when performing per-segment query
* execution.
*/
public class BufferArrayGrouper implements IntGrouper
{
private static final Logger LOG = new Logger(BufferArrayGrouper.class);
private final Supplier<ByteBuffer> bufferSupplier;
private final BufferAggregator[] aggregators;
private final int[] aggregatorOffsets;
private final int cardinalityWithMissingValue;
private final int recordSize; // size of all aggregated values
private boolean initialized = false;
private ByteBuffer usedFlagBuffer;
private ByteBuffer valBuffer;
static int requiredBufferCapacity(
int cardinality,
AggregatorFactory[] aggregatorFactories
)
{
final int cardinalityWithMissingValue = cardinality + 1;
final int recordSize = Arrays.stream(aggregatorFactories)
.mapToInt(AggregatorFactory::getMaxIntermediateSize)
.sum();
return getUsedFlagBufferCapacity(cardinalityWithMissingValue) + // total used flags size
cardinalityWithMissingValue * recordSize; // total values size
}
/**
* Compute the number of bytes to store all used flag bits.
*/
private static int getUsedFlagBufferCapacity(int cardinalityWithMissingValue)
{
return (cardinalityWithMissingValue + Byte.SIZE - 1) / Byte.SIZE;
}
public BufferArrayGrouper(
// the buffer returned from the below supplier can have dirty bits and should be cleared during initialization
final Supplier<ByteBuffer> bufferSupplier,
final ColumnSelectorFactory columnSelectorFactory,
final AggregatorFactory[] aggregatorFactories,
final int cardinality
)
{
Preconditions.checkNotNull(aggregatorFactories, "aggregatorFactories");
Preconditions.checkArgument(cardinality > 0, "Cardinality must a non-zero positive number");
this.bufferSupplier = Preconditions.checkNotNull(bufferSupplier, "bufferSupplier");
this.aggregators = new BufferAggregator[aggregatorFactories.length];
this.aggregatorOffsets = new int[aggregatorFactories.length];
this.cardinalityWithMissingValue = cardinality + 1;
int offset = 0;
for (int i = 0; i < aggregatorFactories.length; i++) {
aggregators[i] = aggregatorFactories[i].factorizeBuffered(columnSelectorFactory);
aggregatorOffsets[i] = offset;
offset += aggregatorFactories[i].getMaxIntermediateSize();
}
recordSize = offset;
}
@Override
public void init()
{
if (!initialized) {
final ByteBuffer buffer = bufferSupplier.get();
final int usedFlagBufferEnd = getUsedFlagBufferCapacity(cardinalityWithMissingValue);
buffer.position(0);
buffer.limit(usedFlagBufferEnd);
usedFlagBuffer = buffer.slice();
buffer.position(usedFlagBufferEnd);
buffer.limit(buffer.capacity());
valBuffer = buffer.slice();
reset();
initialized = true;
}
}
@Override
public boolean isInitialized()
{
return initialized;
}
@Override
public AggregateResult aggregateKeyHash(int dimIndex)
{
Preconditions.checkArgument(
dimIndex >= 0 && dimIndex < cardinalityWithMissingValue,
"Invalid dimIndex[%s]",
dimIndex
);
final int recordOffset = dimIndex * recordSize;
if (recordOffset + recordSize > valBuffer.capacity()) {
// This error cannot be recoverd, and the query must fail
throw new ISE(
"A record of size [%d] cannot be written to the array buffer at offset[%d] "
+ "because it exceeds the buffer capacity[%d]. Try increasing druid.processing.buffer.sizeBytes",
recordSize,
recordOffset,
valBuffer.capacity()
);
}
if (!isUsedSlot(dimIndex)) {
initializeSlot(dimIndex);
}
for (int i = 0; i < aggregators.length; i++) {
aggregators[i].aggregate(valBuffer, recordOffset + aggregatorOffsets[i]);
}
return AggregateResult.ok();
}
private void initializeSlot(int dimIndex)
{
final int index = dimIndex / Byte.SIZE;
final int extraIndex = dimIndex % Byte.SIZE;
usedFlagBuffer.put(index, (byte) (usedFlagBuffer.get(index) | (1 << extraIndex)));
final int recordOffset = dimIndex * recordSize;
for (int i = 0; i < aggregators.length; i++) {
aggregators[i].init(valBuffer, recordOffset + aggregatorOffsets[i]);
}
}
private boolean isUsedSlot(int dimIndex)
{
final int index = dimIndex / Byte.SIZE;
final int extraIndex = dimIndex % Byte.SIZE;
final int usedFlagByte = 1 << extraIndex;
return (usedFlagBuffer.get(index) & usedFlagByte) != 0;
}
@Override
public void reset()
{
// Clear the entire usedFlagBuffer
final int usedFlagBufferCapacity = usedFlagBuffer.capacity();
// putLong() instead of put() can boost the performance of clearing the buffer
final int n = (usedFlagBufferCapacity / Long.BYTES) * Long.BYTES;
for (int i = 0; i < n; i += Long.BYTES) {
usedFlagBuffer.putLong(i, 0L);
}
for (int i = n; i < usedFlagBufferCapacity; i++) {
usedFlagBuffer.put(i, (byte) 0);
}
}
@Override
public IntGrouperHashFunction hashFunction()
{
return key -> key + 1;
}
@Override
public void close()
{
for (BufferAggregator aggregator : aggregators) {
try {
aggregator.close();
}
catch (Exception e) {
LOG.warn(e, "Could not close aggregator [%s], skipping.", aggregator);
}
}
}
@Override
public CloseableIterator<Entry<Integer>> iterator(boolean sorted)
{
if (sorted) {
throw new UnsupportedOperationException("sorted iterator is not supported yet");
}
return new CloseableIterator<Entry<Integer>>()
{
int cur = -1;
boolean findNext = false;
{
cur = findNext();
}
@Override
public boolean hasNext()
{
if (findNext) {
cur = findNext();
findNext = false;
}
return cur >= 0;
}
private int findNext()
{
for (int i = cur + 1; i < cardinalityWithMissingValue; i++) {
if (isUsedSlot(i)) {
return i;
}
}
return -1;
}
@Override
public Entry<Integer> next()
{
if (cur < 0) {
throw new NoSuchElementException();
}
findNext = true;
final Object[] values = new Object[aggregators.length];
final int recordOffset = cur * recordSize;
for (int i = 0; i < aggregators.length; i++) {
values[i] = aggregators[i].get(valBuffer, recordOffset + aggregatorOffsets[i]);
}
return new Entry<>(cur - 1, values);
}
@Override
public void close()
{
// do nothing
}
};
}
}
| apache-2.0 |
Leaking/GitKnife | src/com/gitknife/library/ByteArrayPool.java | 5394 | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gitknife.library;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
/**
* ByteArrayPool is a source and repository of <code>byte[]</code> objects. Its purpose is to
* supply those buffers to consumers who need to use them for a short period of time and then
* dispose of them. Simply creating and disposing such buffers in the conventional manner can
* considerable heap churn and garbage collection delays on Android, which lacks good management of
* short-lived heap objects. It may be advantageous to trade off some memory in the form of a
* permanently allocated pool of buffers in order to gain heap performance improvements; that is
* what this class does.
* <p>
* A good candidate user for this class is something like an I/O system that uses large temporary
* <code>byte[]</code> buffers to copy data around. In these use cases, often the consumer wants
* the buffer to be a certain minimum size to ensure good performance (e.g. when copying data chunks
* off of a stream), but doesn't mind if the buffer is larger than the minimum. Taking this into
* account and also to maximize the odds of being able to reuse a recycled buffer, this class is
* free to return buffers larger than the requested size. The caller needs to be able to gracefully
* deal with getting buffers any size over the minimum.
* <p>
* If there is not a suitably-sized buffer in its recycling pool when a buffer is requested, this
* class will allocate a new buffer and return it.
* <p>
* This class has no special ownership of buffers it creates; the caller is free to take a buffer
* it receives from this pool, use it permanently, and never return it to the pool; additionally,
* it is not harmful to return to this pool a buffer that was allocated elsewhere, provided there
* are no other lingering references to it.
* <p>
* This class ensures that the total size of the buffers in its recycling pool never exceeds a
* certain byte limit. When a buffer is returned that would cause the pool to exceed the limit,
* least-recently-used buffers are disposed.
*/
public class ByteArrayPool {
/** The buffer pool, arranged both by last use and by buffer size */
private List<byte[]> mBuffersByLastUse = new LinkedList<byte[]>();
private List<byte[]> mBuffersBySize = new ArrayList<byte[]>(64);
/** The total size of the buffers in the pool */
private int mCurrentSize = 0;
/**
* The maximum aggregate size of the buffers in the pool. Old buffers are discarded to stay
* under this limit.
*/
private final int mSizeLimit;
/** Compares buffers by size */
protected static final Comparator<byte[]> BUF_COMPARATOR = new Comparator<byte[]>() {
@Override
public int compare(byte[] lhs, byte[] rhs) {
return lhs.length - rhs.length;
}
};
/**
* @param sizeLimit the maximum size of the pool, in bytes
*/
public ByteArrayPool(int sizeLimit) {
mSizeLimit = sizeLimit;
}
/**
* Returns a buffer from the pool if one is available in the requested size, or allocates a new
* one if a pooled one is not available.
*
* @param len the minimum size, in bytes, of the requested buffer. The returned buffer may be
* larger.
* @return a byte[] buffer is always returned.
*/
public synchronized byte[] getBuf(int len) {
for (int i = 0; i < mBuffersBySize.size(); i++) {
byte[] buf = mBuffersBySize.get(i);
if (buf.length >= len) {
mCurrentSize -= buf.length;
mBuffersBySize.remove(i);
mBuffersByLastUse.remove(buf);
return buf;
}
}
return new byte[len];
}
/**
* Returns a buffer to the pool, throwing away old buffers if the pool would exceed its allotted
* size.
*
* @param buf the buffer to return to the pool.
*/
public synchronized void returnBuf(byte[] buf) {
if (buf == null || buf.length > mSizeLimit) {
return;
}
mBuffersByLastUse.add(buf);
int pos = Collections.binarySearch(mBuffersBySize, buf, BUF_COMPARATOR);
if (pos < 0) {
pos = -pos - 1;
}
mBuffersBySize.add(pos, buf);
mCurrentSize += buf.length;
trim();
}
/**
* Removes buffers from the pool until it is under its size limit.
*/
private synchronized void trim() {
while (mCurrentSize > mSizeLimit) {
byte[] buf = mBuffersByLastUse.remove(0);
mBuffersBySize.remove(buf);
mCurrentSize -= buf.length;
}
}
}
| apache-2.0 |
tesshucom/subsonic-fx-player | subsonic-fx-player-api/src/main/java/com/tesshu/subsonic/client/fx/command/logic/AnalizeArtistLogic.java | 893 | /**
* Copyright © 2017 tesshu.com (webmaster@tesshu.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.tesshu.subsonic.client.fx.command.logic;
import com.tesshu.subsonic.client.fx.command.param.SimpleObjectParam;
import com.tesshu.subsonic.client.model.ArtistID3;
public interface AnalizeArtistLogic extends BrowsingID3Logic<SimpleObjectParam<ArtistID3>> {
}
| apache-2.0 |
spotify/helios | helios-tools/src/main/java/com/spotify/helios/cli/command/JobDeployCommand.java | 4273 | /*-
* -\-\-
* Helios Tools
* --
* Copyright (C) 2016 Spotify AB
* --
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* -/-/-
*/
package com.spotify.helios.cli.command;
import static com.spotify.helios.common.descriptors.Goal.START;
import static com.spotify.helios.common.descriptors.Goal.STOP;
import static net.sourceforge.argparse4j.impl.Arguments.storeTrue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.spotify.helios.client.HeliosClient;
import com.spotify.helios.common.descriptors.Deployment;
import com.spotify.helios.common.descriptors.Job;
import com.spotify.helios.common.descriptors.JobId;
import com.spotify.helios.common.protocol.JobDeployResponse;
import java.io.BufferedReader;
import java.io.PrintStream;
import java.util.List;
import java.util.concurrent.ExecutionException;
import net.sourceforge.argparse4j.inf.Argument;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
public class JobDeployCommand extends WildcardJobCommand {
private final Argument hostsArg;
private final Argument tokenArg;
private final Argument noStartArg;
private final Argument watchArg;
private final Argument intervalArg;
public JobDeployCommand(final Subparser parser) {
super(parser);
parser.help("deploy a job to hosts");
hostsArg = parser.addArgument("hosts")
.nargs("+")
.help("The hosts to deploy the job on.");
tokenArg = parser.addArgument("--token")
.nargs("?")
.setDefault("")
.help("Insecure access token");
noStartArg = parser.addArgument("--no-start")
.action(storeTrue())
.help("Deploy job without starting it.");
watchArg = parser.addArgument("--watch")
.action(storeTrue())
.help("Watch the newly deployed job (like running job watch right after)");
intervalArg = parser.addArgument("--interval")
.setDefault(1)
.help("if --watch is specified, the polling interval, default 1 second");
}
@Override
protected int runWithJob(final Namespace options, final HeliosClient client,
final PrintStream out, final boolean json, final Job job,
final BufferedReader stdin)
throws ExecutionException, InterruptedException {
final JobId jobId = job.getId();
final List<String> hosts = options.getList(hostsArg.getDest());
final Deployment deployment = Deployment.of(jobId,
options.getBoolean(noStartArg.getDest()) ? STOP : START);
if (!json) {
out.printf("Deploying %s on %s%n", deployment, hosts);
}
int code = 0;
final HostResolver resolver = HostResolver.create(client);
final List<String> resolvedHosts = Lists.newArrayList();
for (final String candidateHost : hosts) {
final String host = resolver.resolveName(candidateHost);
resolvedHosts.add(host);
if (!json) {
out.printf("%s: ", host);
}
final String token = options.getString(tokenArg.getDest());
final JobDeployResponse result = client.deploy(deployment, host, token).get();
if (result.getStatus() == JobDeployResponse.Status.OK) {
if (!json) {
out.printf("done%n");
} else {
out.print(result.toJsonString());
}
} else {
if (!json) {
out.printf("failed: %s%n", result);
} else {
out.print(result.toJsonString());
}
code = 1;
}
}
if (code == 0 && options.getBoolean(watchArg.getDest())) {
JobWatchCommand.watchJobsOnHosts(out, true, resolvedHosts, ImmutableList.of(jobId),
options.getInt(intervalArg.getDest()), client);
}
return code;
}
}
| apache-2.0 |
faustineinsun/WiseCrowdRec | deprecated-wisecrowdrec-springmvc/WiseCrowdRec/src/main/java/com/feiyu/springmvc/model/EntityWithSentiment.java | 817 | package com.feiyu.springmvc.model;
/**
* @author feiyu
*/
import java.util.HashMap;
public class EntityWithSentiment {
private HashMap<String, String> entityWithCategory;
private int sentiment;
public EntityWithSentiment() {
}
public void setEntityWithCategory(HashMap<String, String> entityWithCategory) {
this.entityWithCategory = entityWithCategory;
}
public HashMap<String, String> getEntityWithCategory() {
return this.entityWithCategory;
}
public void setSentiment(int sentiment) {
this.sentiment = sentiment;
}
public int getSentiment() {
return this.sentiment;
}
@Override
public String toString() {
return "EntityWithSentiment:{"
+"EntityWithCategory:"+ this.entityWithCategory
+",sentiment:" + this.sentiment
+ "}";
}
}
| apache-2.0 |
gitee2008/glaf | src/main/java/com/glaf/core/access/service/AccessUriService.java | 1945 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.glaf.core.access.service;
import java.util.*;
import org.springframework.transaction.annotation.Transactional;
import com.glaf.core.access.domain.*;
import com.glaf.core.access.query.*;
@Transactional(readOnly = true)
public interface AccessUriService {
@Transactional
void bulkInsert(List<AccessUri> list);
/**
* 根据主键删除记录
*
* @return
*/
@Transactional
void deleteById(Long id);
/**
* 根据查询参数获取记录列表
*
* @return
*/
List<AccessUri> list(AccessUriQuery query);
/**
* 根据查询参数获取记录总数
*
* @return
*/
int getAccessUriCountByQueryCriteria(AccessUriQuery query);
/**
* 根据查询参数获取一页的数据
*
* @return
*/
List<AccessUri> getAccessUrisByQueryCriteria(int start, int pageSize, AccessUriQuery query);
/**
* 根据主键获取一条记录
*
* @return
*/
AccessUri getAccessUri(Long id);
/**
* 根据uri获取一条记录
*
* @return
*/
AccessUri getAccessUriByUri(String uri);
/**
* 保存一条记录
*
* @return
*/
@Transactional
void save(AccessUri accessUri);
}
| apache-2.0 |
vimaier/conqat | org.conqat.engine.resource/src/org/conqat/engine/resource/util/ConQATDirectoryScanner.java | 3081 | /*-------------------------------------------------------------------------+
| |
| Copyright 2005-2011 The ConQAT Project |
| |
| Licensed under the Apache License, Version 2.0 (the "License"); |
| you may not use this file except in compliance with the License. |
| You may obtain a copy of the License at |
| |
| http://www.apache.org/licenses/LICENSE-2.0 |
| |
| Unless required by applicable law or agreed to in writing, software |
| distributed under the License is distributed on an "AS IS" BASIS, |
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| See the License for the specific language governing permissions and |
| limitations under the License. |
+-------------------------------------------------------------------------*/
package org.conqat.engine.resource.util;
import java.io.IOException;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.conqat.engine.core.core.ConQATException;
import org.conqat.lib.commons.filesystem.AntPatternDirectoryScanner;
import org.conqat.lib.commons.filesystem.AntPatternUtils;
/**
* ConQAT engine wrapper class for the {@link AntPatternDirectoryScanner}.
*
* @author $Author: kinnen $
* @version $Rev: 41751 $
* @ConQAT.Rating GREEN Hash: EE51B2936CE80CAD61F11A278DB65C0A
*/
public class ConQATDirectoryScanner {
/** Converts an ANT pattern to a regex pattern. */
public static Pattern convertPattern(String antPattern,
boolean caseSensitive) throws ConQATException {
try {
return AntPatternUtils.convertPattern(antPattern, caseSensitive);
} catch (PatternSyntaxException e) {
throw new ConQATException(e.getMessage(), e);
}
}
/**
* Performs directory scanning.
*
* @param baseDir
* the directory to start scanning in. All file names returned
* will be relative to this file.
* @param caseSensitive
* whether pattern should be applied case sensitive or not.
* @param includePatterns
* the include pattern (use ANT's pattern syntax)
* @param excludePatterns
* the exclude pattern (use ANT's pattern syntax)
* @throws ConQATException
* in case of invalid pattern provided or IO problems.
*/
public static String[] scan(String baseDir, boolean caseSensitive,
String[] includePatterns, String[] excludePatterns)
throws ConQATException {
try {
return AntPatternDirectoryScanner.scan(baseDir, caseSensitive,
includePatterns, excludePatterns);
} catch (IOException e) {
throw new ConQATException(
"Error while scanning: " + e.getMessage(), e);
}
}
} | apache-2.0 |
cocoatomo/asakusafw | hive-project/asakusa-hive-core/src/test/java/com/asakusafw/directio/hive/parquet/mock/WithString.java | 871 | /**
* Copyright 2011-2017 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.directio.hive.parquet.mock;
import com.asakusafw.runtime.value.StringOption;
/**
* Mock data type with string value.
*/
@SuppressWarnings("all")
public class WithString {
public final StringOption value = new StringOption();
}
| apache-2.0 |
OmniKryptec/OmniKryptec-Engine | src/main/java/de/omnikryptec/old/net/AdvancedServerSocket.java | 18348 | /*
* Copyright 2017 - 2019 Roman Borris (pcfreak9000), Paul Hagedorn (Panzer1119)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.omnikryptec.old.net;
import de.omnikryptec.old.util.AdvancedThreadFactory;
import de.omnikryptec.old.util.Util;
import de.omnikryptec.old.util.logger.LogLevel;
import de.omnikryptec.old.util.logger.Logger;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
* AdvancedServerSocket
*
* @author Panzer1119
*/
public abstract class AdvancedServerSocket implements ActionListener, Serializable {
/**
* A reference to this AdvancedServerSocket
*/
public final AdvancedServerSocket ADVANCEDSERVERSOCKET = this;
/**
* java.net.ServerSocket ServerSocket which accepts all Sockets
*/
protected ServerSocket serverSocket = null;
/**
* Port to start on
*/
protected int port = -1;
/**
* List with all accepted AdvancedSockets
*/
protected final ArrayList<AdvancedSocket> socketsAccepted = new ArrayList<>();
/**
* ThreadPool size
*/
protected final int threadPoolSize;
/**
* AdvancedThreadFactory Receiver
*/
private final AdvancedThreadFactory advancedThreadFactoryReceiver = new AdvancedThreadFactory();
/**
* ThreadPool Acceptor
*/
protected ExecutorService executorReceiver = null;
/**
* Acceptor Thread
*/
protected Thread threadAcceptor = null;
/**
* If the AdvancedServerSocket is started
*/
protected boolean started = false;
/**
* If the AdvancedServerSocket is stopped
*/
protected boolean stopped = true;
/**
* Timestamp when the AdvancedServerSocket was started
*/
protected Instant instantStarted = null;
/**
* Timestamp when the AdvancedServerSocket was stopped
*/
protected Instant instantStopped = null;
/**
* Delay time between each new connection check in milliseconds
*/
protected int connectionCheckTimerDelay = Network.CONNECTION_CHECK_TIMER_DELAY_STANDARD;
/**
* Timer which calls the checkConnection every seconds
*/
protected Timer timer = null;
/**
* If the AdvancedServerSocket is checking the connections
*/
protected boolean isCheckingConnections = false;
/**
* Creates an AdvancedServerSocket from a ServerSocket with the standard Server
* ThreadPool size
*
* @param serverSocket ServerSocket
*/
public AdvancedServerSocket(ServerSocket serverSocket) {
this(serverSocket, Network.THREADPOOL_SIZE_SERVER_STANDARD);
}
/**
* Creates an AdvancedServerSocket from a ServerSocket
*
* @param serverSocket ServerSocket
* @param threadPoolSize ThreadPool size
*/
public AdvancedServerSocket(ServerSocket serverSocket, int threadPoolSize) {
this.threadPoolSize = Math.min(threadPoolSize, Network.THREADPOOL_SIZE_SERVER_MAX);
init();
setServerSocket(serverSocket);
}
/**
* Creates an AdvancedServerSocket with the standard Server ThreadPool size
*
* @param port Port
*/
public AdvancedServerSocket(int port) {
this(port, Network.THREADPOOL_SIZE_SERVER_STANDARD);
}
/**
* Creates an AdvancedServerSocket
*
* @param port Port
* @param threadPoolSize ThreadPool size
*/
public AdvancedServerSocket(int port, int threadPoolSize) {
this.threadPoolSize = Math.min(threadPoolSize, Network.THREADPOOL_SIZE_SERVER_MAX);
init();
setPort(port);
}
/**
* Initialize the AdvancedServerSocket
*
* @return A reference to this AdvancedServerSocket
*/
private final AdvancedServerSocket init() {
resetReceiverThread();
return this;
}
/**
* Resets the receiver Thread
*
* @return A reference to this AdvancedServerSocket
*/
private final AdvancedServerSocket resetReceiverThread() {
Util.killThread(threadAcceptor, Network.THREAD_KILL_DELAY_TIME_STANDARD, Network.THREAD_KILL_MAX_TIME_STANDARD);
threadAcceptor = new Thread(() -> {
while (started) {
try {
final Socket socket = serverSocket.accept();
Instant instantNow = Instant.now();
executorReceiver.execute(() -> {
synchronized (socketsAccepted) {
final AdvancedSocket advancedSocket = onConnected(socket, instantNow);
if (advancedSocket != null) {
advancedSocket.setConnectionCheckTimerDelay(-1);
socketsAccepted.add(advancedSocket);
}
}
});
} catch (IOException ex) {
if (Logger.isDebugMode()) {
Logger.log("Server on Port " + port + " stopped!", LogLevel.WARNING);
}
started = false;
} catch (Exception ex) {
if (Logger.isDebugMode()) {
Logger.logErr(String.format("Error while accepting Socket from Port %d: %s", port, ex), ex);
}
}
}
});
return this;
}
/**
* Resets all ExecutorServices
*
* @param immediately If the running Threads should be killed immediately
* @return A reference to this AdvancedServerSocket
*/
private final AdvancedServerSocket resetExecutors(boolean immediately) {
advancedThreadFactoryReceiver.setName("AdvancedServerSocket-Port-" + port + "-Receiver-Thread-%d");
executorReceiver = resetExecutor(executorReceiver, advancedThreadFactoryReceiver, immediately);
return this;
}
/**
* Resets a ThreadPool
*
* @param immediately If the running Threads should be killed immediately
* @return New ThreadPool
*/
private final ExecutorService resetExecutor(ExecutorService executor, ThreadFactory threadFactory,
boolean immediately) {
try {
if (executor != null) {
if (immediately) {
executor.shutdownNow();
} else {
executor.shutdown();
executor.awaitTermination(1, TimeUnit.MINUTES);
}
}
return Executors.newFixedThreadPool(threadPoolSize, threadFactory);
} catch (Exception ex) {
if (Logger.isDebugMode()) {
Logger.logErr("Error while resetting executor: " + ex, ex);
}
return null;
}
}
/**
* Resets the Timer
*
* @param delay Delay
*/
private final void resetTimer(int delay) {
if (timer != null) {
timer.stop();
timer = null;
}
if (timer == null) {
timer = new Timer(delay, this);
}
}
/**
* Starts the AdvancedServerSocket
*
* @return <tt>true</tt> if the ServerSocket was successfully started
*/
public final boolean start() {
return start(false);
}
/**
* Starts the AdvancedServerSocket
*
* @param createNewServerSocket If a new ServerSocket should be created
* @return <tt>true</tt> if the ServerSocket was successfully started
*/
public final boolean start(boolean createNewServerSocket) {
if (started) {
if (Logger.isDebugMode()) {
Logger.log("Can not start a ServerSocket on Port " + port
+ ", because there is already a ServerSocket running!", LogLevel.WARNING);
}
return false;
}
if (!Network.registerTCPPort(port, this)) {
if (Logger.isDebugMode()) {
Logger.log("Can not start a ServerSocket on Port " + port + ", because the Port can not be registered!",
LogLevel.WARNING);
}
return false;
}
try {
resetReceiverThread();
resetExecutors(true);
resetTimer(connectionCheckTimerDelay);
closeSockets();
started = startServerSocket(createNewServerSocket);
if (started) {
if (Logger.isDebugMode()) {
Logger.log("Started successfully Server on Port " + port, LogLevel.FINE);
}
instantStopped = null;
instantStarted = Instant.now();
}
stopped = !started;
if (started) {
threadAcceptor.start();
if (connectionCheckTimerDelay > 0) {
timer.start();
}
}
return started;
} catch (Exception ex) {
if (Logger.isDebugMode()) {
Logger.logErr(String.format("Error while starting Server on Port %d: %s", port, ex), ex);
}
return false;
}
}
/**
* Starts the ServerSocket
*
* @param createNewServerSocket If a new ServerSocket should be created
* @return <tt>true</tt> if the ServerSocket was successfully started
*/
private final boolean startServerSocket(boolean createNewServerSocket) {
try {
if (Logger.isDebugMode()) {
Logger.log("Started ServerSocket on Port " + port, LogLevel.FINE);
}
if (createNewServerSocket || serverSocket == null) {
Network.closeServerSocket(serverSocket);
serverSocket = new ServerSocket(port);
}
return true;
} catch (Exception ex) {
if (Logger.isDebugMode()) {
Logger.logErr(String.format("Error while starting ServerSocket on Port %d: %s", port, ex), ex);
}
return false;
}
}
/**
* Stops immediately the AdvancedServerSocket
*
* @return <tt>true</tt> if the ServerSocket was stopped successfully
*/
public final boolean stop() {
return stop(true);
}
/**
* Stops the AdvancedServerSocket
*
* @param immediately If the ServerSocket should be stopped immediately
* @return <tt>true</tt> if the ServerSocket was stopped successfully
*/
public final boolean stop(boolean immediately) {
if (stopped) {
if (Logger.isDebugMode()) {
Logger.log("Can not stop Server on Port " + port + ", because there is no Server running!",
LogLevel.WARNING);
}
return false;
}
try {
instantStopped = Instant.now();
resetTimer(0);
resetReceiverThread();
resetExecutors(immediately);
closeSockets();
if (Network.closeServerSocket(serverSocket)) {
serverSocket = null;
stopped = true;
}
started = !stopped;
if (stopped) {
Network.unregisterTCPPort(port);
if (Logger.isDebugMode()) {
Logger.log("Stopped successfully Server on Port " + port, LogLevel.FINE);
}
}
return stopped;
} catch (Exception ex) {
if (Logger.isDebugMode()) {
Logger.logErr(String.format("Error while stopping Server on Port %d: %s", port, ex), ex);
}
return false;
}
}
/**
* Checks all connections to the accepted Sockets
*
* @return A reference to thos AdvancedServerSocket
*/
protected final AdvancedServerSocket checkConnections() {
isCheckingConnections = true;
synchronized (socketsAccepted) {
final Iterator<AdvancedSocket> i = socketsAccepted.iterator();
while (i.hasNext()) {
final AdvancedSocket socket = i.next();
final Instant instantNow = Instant.now();
if (!socket.checkConnection()) {
final boolean delete = onDisconnected(socket, instantNow);
socket.disconnect(true);
if (delete) {
i.remove();
}
}
}
}
isCheckingConnections = false;
return this;
}
/**
* Closes all accepted sockets
*
* @return A reference to this AdvancedServerSocket
*/
private final AdvancedServerSocket closeSockets() {
synchronized (socketsAccepted) {
socketsAccepted.parallelStream().filter(Objects::nonNull).forEach((socket) -> socket.disconnect(true));
socketsAccepted.clear();
}
return this;
}
/**
* Broadcasts a Message to all connected AdvancedSockets
*
* @param message Message to broadcast
* @return A reference to this AdvancedServerSocket
*/
public final AdvancedServerSocket broadcast(Object message) {
return broadcast(message, false);
}
/**
* Broadcast a Message to all given AdvancedSockets
*
* @param message Message to broadcast
* @param whitelist If the list is a white or a blacklist
* @param sockets AdvancedSockets that are allowed/denied to receive the
* message
* @return A reference to this AdvancedServerSocket
*/
public final AdvancedServerSocket broadcast(Object message, boolean whitelist, AdvancedSocket... sockets) {
if (sockets == null || sockets.length == 0) {
socketsAccepted.parallelStream().filter(Objects::nonNull).forEach((socket) -> socket.send(message));
} else {
socketsAccepted.parallelStream().filter((socket) -> {
if (socket == null) {
return false;
}
for (AdvancedSocket s : sockets) {
if (socket == s) {
return whitelist;
}
}
return !whitelist;
}).forEach((socket) -> socket.send(message));
}
return this;
}
/**
* Processes Inputs from sockets
*
* @param object Input
* @param timestamp Timestamp
*/
public abstract void processInput(Object object, AdvancedSocket socket, Instant timestamp);
/**
* Called when a connection from a socket was successfully accepted
*
* @param timestamp Timestamp
*/
public AdvancedSocket onConnected(Socket socket, Instant timestamp) {
final AdvancedSocket advancedSocket = new AdvancedSocket(socket, threadPoolSize) {
@Override
public void processInput(Object object, Instant timestamp) {
ADVANCEDSERVERSOCKET.processInput(object, this, timestamp);
}
@Override
public void onConnected(Instant timestamp) {
// Nothing
}
@Override
public void onDisconnected(Instant timestamp) {
// Nothing
}
};
advancedSocket.setFromServerSocket(true);
advancedSocket.connect(false);
return advancedSocket;
}
/**
* Called when a connection from a socket was disconnected
*
* @param timestamp Timestamp
* @return <tt>true</tt> if disconnected AdvancedSocket should be deleted from
* the ArrayList
*/
public abstract boolean onDisconnected(AdvancedSocket socket, Instant timestamp);
/**
* Returns the Port
*
* @return Port
*/
public final int getPort() {
return port;
}
/**
* Sets the Port
*
* @param port Port to connect to
* @return A reference to this AdvancedServerSocket
*/
public final AdvancedServerSocket setPort(int port) {
if (!Network.checkTCPPort(port)) {
this.port = Network.PORT_STANDARD;
return this;
}
this.port = port;
return this;
}
/**
* Sets the ServerSocket
*
* @param serverSocket ServerSocket
* @return A reference to this AdvancedServerSocket
*/
public final AdvancedServerSocket setServerSocket(ServerSocket serverSocket) {
if (serverSocket != null) {
this.serverSocket = serverSocket;
setPort(serverSocket.getLocalPort());
}
return this;
}
/**
* Returns the ThreadPool size
*
* @return ThreadPool size
*/
public final int getThreadPoolSize() {
return threadPoolSize;
}
/**
* Returns if the AdvancedServerSocket is started
*
* @return <tt>true</tt> if the AdvancedServerSocket is started
*/
public final boolean isStarted() {
return started;
}
/**
* Returns if the AdvancedServerSocket is stopped
*
* @return <tt>true</tt> if the AdvancedServerSocket is stopped
*/
public final boolean isStopped() {
return stopped;
}
/**
* Returns the Timestamp when the ServerSocket was started or null
*
* @return Timestamp of starting
*/
public final Instant getInstantStarted() {
return instantStarted;
}
/**
* Returns the Timestamp when the ServerSocket was stopped or null
*
* @return Timestamp of stopping
*/
public final Instant getInstantStopped() {
return instantStopped;
}
/**
* Returns the Duration how long the ServerSocket is/was running
*
* @return Duration of the running time
*/
public final Duration getRunningDuration() {
if (instantStarted != null) {
if (instantStopped != null) {
return Duration.between(instantStarted, instantStopped);
} else {
return Duration.between(instantStarted, Instant.now());
}
} else {
return Duration.ZERO;
}
}
/**
* Returns the delay time between each new connection check in milliseconds
*
* @return Delay time between each new connection check in milliseconds
*/
public final int getConnectionCheckTimerDelay() {
return connectionCheckTimerDelay;
}
/**
* Sets the delay time between each new connection check in milliseconds
*
* @param connectionCheckTimerDelay Delay time between each new connection check
* in milliseconds
* @return A reference to this AdvancedServerSocket
*/
public final AdvancedServerSocket setConnectionCheckTimerDelay(int connectionCheckTimerDelay) {
this.connectionCheckTimerDelay = connectionCheckTimerDelay;
return this;
}
/**
* Waits until the socketsAccepted ArrayList can be used
*
* @return A reference to this AdvancedServerSocket
*/
public final AdvancedServerSocket waitForSocketsAccepted() {
while (isCheckingConnections) {
try {
Thread.sleep(1);
} catch (Exception ex) {
}
}
return this;
}
@Override
public final void actionPerformed(ActionEvent e) {
if (e.getSource() == timer) {
checkConnections();
}
}
@Override
public String toString() {
return String.format("%s on Port %d, Running time: %ds, Accepted AdvancedSockets: %d, Started: %b, Stopped: %b",
getClass().getSimpleName(), port, getRunningDuration().getSeconds(), socketsAccepted.size(), started,
stopped);
}
}
| apache-2.0 |
google/graphicsfuzz | reducer/src/test/java/com/graphicsfuzz/reducer/reductionopportunities/UnwrapReductionOpportunitiesTest.java | 11212 | /*
* Copyright 2018 The GraphicsFuzz Project Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.graphicsfuzz.reducer.reductionopportunities;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.graphicsfuzz.common.ast.TranslationUnit;
import com.graphicsfuzz.common.glslversion.ShadingLanguageVersion;
import com.graphicsfuzz.common.tool.PrettyPrinterVisitor;
import com.graphicsfuzz.common.util.CompareAsts;
import com.graphicsfuzz.common.util.IRandom;
import com.graphicsfuzz.common.util.IdGenerator;
import com.graphicsfuzz.common.util.ParseHelper;
import com.graphicsfuzz.common.util.RandomWrapper;
import com.graphicsfuzz.common.util.SameValueRandom;
import com.graphicsfuzz.common.util.ShaderJobFileOperations;
import com.graphicsfuzz.util.Constants;
import java.util.List;
import org.junit.Test;
public class UnwrapReductionOpportunitiesTest {
private final ShaderJobFileOperations fileOps = new ShaderJobFileOperations();
@Test
public void testBlock1() throws Exception {
final String program = "int x; void main() { { x = 2; } }";
final TranslationUnit tu = ParseHelper.parse(program);
List<UnwrapReductionOpportunity> ops = UnwrapReductionOpportunities
.findOpportunities(MakeShaderJobFromFragmentShader.make(tu),
new ReducerContext(false, true,
ShadingLanguageVersion.GLSL_440,
new SameValueRandom(false, 0, 0L), new IdGenerator()));
assertEquals(1, ops.size());
}
@Test
public void testEmptyBlock() throws Exception {
final String program = "void main() { { } }";
final TranslationUnit tu = ParseHelper.parse(program);
List<UnwrapReductionOpportunity> ops = UnwrapReductionOpportunities
.findOpportunities(MakeShaderJobFromFragmentShader.make(tu),
new ReducerContext(false,
true, ShadingLanguageVersion.GLSL_440, new SameValueRandom(false, 0, 0L),
new IdGenerator()));
// No opportunities because the inner block is empty. Another reduction pass may be able to
// delete it, but it cannot be unwrapped.
assertEquals(0, ops.size());
}
@Test
public void testNestedEmptyBlocks() throws Exception {
final String program = "void main() { { { } } }";
final TranslationUnit tu = ParseHelper.parse(program);
List<UnwrapReductionOpportunity> ops = UnwrapReductionOpportunities
.findOpportunities(MakeShaderJobFromFragmentShader.make(tu),
new ReducerContext(false, true,
ShadingLanguageVersion.GLSL_440,
new SameValueRandom(false, 0, 0L),
new IdGenerator()));
assertEquals(1, ops.size());
}
@Test
public void testUnwrapWithDeclNoClash() throws Exception {
final String program = "void main() { int x; { int y; } }";
final String expected = "void main() { int x; int y; }";
final TranslationUnit tu = ParseHelper.parse(program);
List<UnwrapReductionOpportunity> ops = UnwrapReductionOpportunities
.findOpportunities(MakeShaderJobFromFragmentShader.make(tu),
new ReducerContext(false, true,
ShadingLanguageVersion.GLSL_440,
new SameValueRandom(false, 0, 0L), new IdGenerator()));
assertEquals(1, ops.size());
ops.get(0).applyReduction();
CompareAsts.assertEqualAsts(expected, tu);
}
@Test
public void testNoUnwrapWithDeclClash() throws Exception {
final String program = "void main() { int x; { { int x; } x = 2; } }";
final String expected = "void main() { int x; { int x; } x = 2; }";
final TranslationUnit tu = ParseHelper.parse(program);
List<UnwrapReductionOpportunity> ops = UnwrapReductionOpportunities
.findOpportunities(MakeShaderJobFromFragmentShader.make(tu),
new ReducerContext(false, true,
ShadingLanguageVersion.GLSL_440,
new SameValueRandom(false, 0, 0L),
new IdGenerator()));
// The inner block cannot be unwrapped as it would change which variable 'x = 2' refers to.
assertEquals(1, ops.size());
}
@Test
public void testNoUnwrapWithDeclClash2() throws Exception {
final String program = "void main() { { int x; } float x; }";
final TranslationUnit tu = ParseHelper.parse(program);
List<UnwrapReductionOpportunity> ops = UnwrapReductionOpportunities
.findOpportunities(MakeShaderJobFromFragmentShader.make(tu),
new ReducerContext(false,
true, ShadingLanguageVersion.GLSL_440, new SameValueRandom(false, 0, 0L),
new IdGenerator()));
assertEquals(0, ops.size());
}
@Test
public void testOneUnwrapDisablesAnother() throws Exception {
final String program = "void main() { { int x; } { float x; } }";
final TranslationUnit tu = ParseHelper.parse(program);
List<UnwrapReductionOpportunity> ops = UnwrapReductionOpportunities
.findOpportunities(MakeShaderJobFromFragmentShader.make(tu),
new ReducerContext(false,
true, ShadingLanguageVersion.GLSL_440, new SameValueRandom(false, 0, 0L),
new IdGenerator()));
assertEquals(2, ops.size());
assertTrue(ops.get(0).preconditionHolds());
assertTrue(ops.get(1).preconditionHolds());
ops.get(0).applyReduction();
assertFalse(ops.get(1).preconditionHolds());
}
@Test
public void misc() throws Exception {
final String shader = "void main()\n"
+ "{\n"
+ " float x;\n"
+ " for(\n"
+ " int i = 0;\n"
+ " _GLF_IDENTITY(i, i) < 10;\n"
+ " i ++\n"
+ " )\n"
+ " {\n"
+ " {\n"
+ " if(_GLF_DEAD(false))\n"
+ " {\n"
+ " }\n"
+ " x = 1.0;\n"
+ " }\n"
+ " }\n"
+ "}\n";
TranslationUnit tu = ParseHelper.parse(shader);
final String expectedStmt = "x = 1.0;";
assertTrue(PrettyPrinterVisitor.prettyPrintAsString(tu).contains(expectedStmt));
IRandom generator = new RandomWrapper(1);
List<UnwrapReductionOpportunity> ops = UnwrapReductionOpportunities
.findOpportunities(MakeShaderJobFromFragmentShader.make(tu),
new ReducerContext(false, true, ShadingLanguageVersion.ESSL_100, generator,
new IdGenerator()));
assertEquals(1, ops.size());
ops.get(0).applyReduction();
assertTrue(PrettyPrinterVisitor.prettyPrintAsString(tu).contains(expectedStmt));
}
@Test
public void testDoubleRemoval() throws Exception {
final String shader = "void main() { if (" + Constants.GLF_DEAD + "(false)) { { { } } } }";
final String expected = "void main() { }";
final TranslationUnit tu = ParseHelper.parse(shader);
final IRandom generator = new RandomWrapper(0);
List<StmtReductionOpportunity> stmtOps = StmtReductionOpportunities
.findOpportunities(MakeShaderJobFromFragmentShader.make(tu),
new ReducerContext(false, true,
ShadingLanguageVersion.ESSL_100, generator,
new IdGenerator()));
List<UnwrapReductionOpportunity> unwrapOps = UnwrapReductionOpportunities
.findOpportunities(MakeShaderJobFromFragmentShader.make(tu),
new ReducerContext(false, true,
ShadingLanguageVersion.ESSL_100, generator,
new IdGenerator()));
assertFalse(stmtOps.isEmpty());
assertFalse(unwrapOps.isEmpty());
stmtOps.forEach(StmtReductionOpportunity::applyReduction);
assertEquals(PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(expected)),
PrettyPrinterVisitor.prettyPrintAsString(tu));
// These should now be disabled so should do nothing.
unwrapOps.forEach(UnwrapReductionOpportunity::applyReduction);
assertEquals(PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(expected)),
PrettyPrinterVisitor.prettyPrintAsString(tu));
}
@Test
public void unwrapFor() throws Exception {
final String shader = "void main() {"
+ " int a;"
+ " for(_injected_loop_counter_0 = 0;"
+ " " + Constants.GLF_WRAPPED_LOOP + "(_injected_loop_counter_0 < 1);"
+ " _injected_loop_counter_0++) {"
+ " int a;"
+ " }"
+ "}";
final String expected = "void main() {"
+ " int a;"
+ " {"
+ " int a;"
+ " }"
+ "}";
final TranslationUnit tu = ParseHelper.parse(shader);
final ShadingLanguageVersion version = ShadingLanguageVersion.ESSL_100;
final RandomWrapper generator = new RandomWrapper(0);
final IdGenerator idGenerator = new IdGenerator();
List<UnwrapReductionOpportunity> ops = UnwrapReductionOpportunities
.findOpportunities(MakeShaderJobFromFragmentShader.make(tu),
new ReducerContext(false, true, version,
generator, idGenerator));
assertEquals(1, ops.size());
ops.get(0).applyReduction();
List<? extends IReductionOpportunity> remainingOps = VariableDeclReductionOpportunities
.findOpportunities(MakeShaderJobFromFragmentShader.make(tu),
new ReducerContext(false, true, version, generator, idGenerator));
assertEquals(PrettyPrinterVisitor.prettyPrintAsString(tu),
PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(expected)));
assertEquals(2, remainingOps.size());
remainingOps.get(0).applyReduction();
remainingOps.get(1).applyReduction();
final String expected2 = "void main() {"
+ " int ;"
+ " {"
+ " int ;"
+ " }"
+ "}";
assertEquals(PrettyPrinterVisitor.prettyPrintAsString(tu),
PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(expected2)));
remainingOps =
StmtReductionOpportunities.findOpportunities(MakeShaderJobFromFragmentShader.make(tu),
new ReducerContext(false, true, version, generator, idGenerator));
assertEquals(3, remainingOps.size());
remainingOps.get(0).applyReduction();
remainingOps.get(1).applyReduction();
remainingOps.get(2).applyReduction();
final String expected3 = "void main() {"
+ "}";
assertEquals(PrettyPrinterVisitor.prettyPrintAsString(tu),
PrettyPrinterVisitor.prettyPrintAsString(ParseHelper.parse(expected3)));
remainingOps = ReductionOpportunities.getReductionOpportunities(
MakeShaderJobFromFragmentShader.make(tu),
new ReducerContext(false, true, version, generator, idGenerator), fileOps);
assertEquals(0, remainingOps.size());
}
}
| apache-2.0 |
medcl/elasticsearch-analysis-mmseg | src/main/java/com/chenlb/mmseg4j/analysis/TokenUtils.java | 2710 | package com.chenlb.mmseg4j.analysis;
import java.io.IOException;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.*;
/**
* lucene 3.0 从 TokenStream 得到 Token 比较麻烦。
*
* @author chenlb 2010-10-7下午10:07:10
*/
public class TokenUtils {
private TokenUtils() {
throw new AssertionError("Must not instantiate this class");
}
/**
* @param input
* @param reusableToken is null well new one auto.
* @return null - if not next token or input is null.
* @throws IOException
*/
public static PackedTokenAttributeImpl nextToken(TokenStream input, PackedTokenAttributeImpl reusableToken) throws IOException {
if(input == null) {
return null;
}
if(!input.incrementToken()) {
return null;
}
CharTermAttribute termAtt = input.getAttribute(CharTermAttribute.class);
OffsetAttribute offsetAtt = input.getAttribute(OffsetAttribute.class);
TypeAttribute typeAtt = input.getAttribute(TypeAttribute.class);
if(reusableToken == null) {
reusableToken = new PackedTokenAttributeImpl();
}
reusableToken.clear();
if(termAtt != null) {
//lucene 3.0
//reusableToken.setTermBuffer(termAtt.termBuffer(), 0, termAtt.termLength());
//lucene 3.1
reusableToken.copyBuffer(termAtt.buffer(), 0, termAtt.length());
}
if(offsetAtt != null) {
//lucene 3.1
//reusableToken.setStartOffset(offsetAtt.startOffset());
//reusableToken.setEndOffset(offsetAtt.endOffset());
//lucene 4.0
reusableToken.setOffset(offsetAtt.startOffset(), offsetAtt.endOffset());
}
if(typeAtt != null) {
reusableToken.setType(typeAtt.type());
}
return reusableToken;
}
public static PackedTokenAttributeImpl subToken(PackedTokenAttributeImpl oriToken, int termBufferOffset, int termBufferLength) {
//CharTermAttributeImpl termImpl = new CharTermAttributeImpl();
//termImpl.copyBuffer(oriToken.buffer(), termBufferOffset, termBufferLength);
//new Token(oriToken.buffer(), termBufferOffset, termBufferLength,
// oriToken.startOffset()+termBufferOffset, oriToken.startOffset()+termBufferOffset+termBufferLength);
//Token token = new Token(termImpl, oriToken.startOffset()+termBufferOffset, oriToken.startOffset()+termBufferOffset+termBufferLength);
PackedTokenAttributeImpl token = new PackedTokenAttributeImpl();
token.copyBuffer(oriToken.buffer(), termBufferOffset, termBufferLength);
token.setOffset(oriToken.startOffset()+termBufferOffset, oriToken.startOffset()+termBufferOffset+termBufferLength);
token.setType(oriToken.type());
return token;
}
} | apache-2.0 |