repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
hengyicai/OnlineAggregationUCAS | network/shuffle/src/test/java/org/apache/spark/network/shuffle/TestShuffleDataContext.java | 3794 | /*
* 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.spark.network.shuffle;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import com.google.common.io.Files;
import org.apache.spark.network.shuffle.protocol.ExecutorShuffleInfo;
/**
* Manages some sort- and hash-based shuffle data, including the creation
* and cleanup of directories that can be read by the {@link ExternalShuffleBlockManager}.
*/
public class TestShuffleDataContext {
public final String[] localDirs;
public final int subDirsPerLocalDir;
public TestShuffleDataContext(int numLocalDirs, int subDirsPerLocalDir) {
this.localDirs = new String[numLocalDirs];
this.subDirsPerLocalDir = subDirsPerLocalDir;
}
public void create() {
for (int i = 0; i < localDirs.length; i ++) {
localDirs[i] = Files.createTempDir().getAbsolutePath();
for (int p = 0; p < subDirsPerLocalDir; p ++) {
new File(localDirs[i], String.format("%02x", p)).mkdirs();
}
}
}
public void cleanup() {
for (String localDir : localDirs) {
deleteRecursively(new File(localDir));
}
}
/** Creates reducer blocks in a sort-based data format within our local dirs. */
public void insertSortShuffleData(int shuffleId, int mapId, byte[][] blocks) throws IOException {
String blockId = "shuffle_" + shuffleId + "_" + mapId + "_0";
OutputStream dataStream = new FileOutputStream(
ExternalShuffleBlockManager.getFile(localDirs, subDirsPerLocalDir, blockId + ".data"));
DataOutputStream indexStream = new DataOutputStream(new FileOutputStream(
ExternalShuffleBlockManager.getFile(localDirs, subDirsPerLocalDir, blockId + ".index")));
long offset = 0;
indexStream.writeLong(offset);
for (byte[] block : blocks) {
offset += block.length;
dataStream.write(block);
indexStream.writeLong(offset);
}
dataStream.close();
indexStream.close();
}
/** Creates reducer blocks in a hash-based data format within our local dirs. */
public void insertHashShuffleData(int shuffleId, int mapId, byte[][] blocks) throws IOException {
for (int i = 0; i < blocks.length; i ++) {
String blockId = "shuffle_" + shuffleId + "_" + mapId + "_" + i;
Files.write(blocks[i],
ExternalShuffleBlockManager.getFile(localDirs, subDirsPerLocalDir, blockId));
}
}
/**
* Creates an ExecutorShuffleInfo object based on the given shuffle manager which targets this
* context's directories.
*/
public ExecutorShuffleInfo createExecutorInfo(String shuffleManager) {
return new ExecutorShuffleInfo(localDirs, subDirsPerLocalDir, shuffleManager);
}
private static void deleteRecursively(File f) {
assert f != null;
if (f.isDirectory()) {
File[] children = f.listFiles();
if (children != null) {
for (File child : children) {
deleteRecursively(child);
}
}
}
f.delete();
}
}
| apache-2.0 |
TUBAME/migration-tool | src/tubame.wsearch/src/tubame/wsearch/models/WSearchCsvEnum.java | 2181 | /*
* WSearchCsvEnum.java
* Created on 2013/06/28
*
* Copyright (C) 2011-2013 Nippon Telegraph and Telephone 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 tubame.wsearch.models;
/**
* An enumeration that defines the item in the search results file.<br/>
*/
public enum WSearchCsvEnum {
/**
* Result
*/
TOKEN_INDEX_STATUS(0),
/**
* Category
*/
TOKEN_INDEX_CATEGORY(1),
/**
* Package
*/
TOKEN_INDEX_PACKAGE(2),
/**
* Porting the original library
*/
TOKEN_INDEX_SRC_LIBRARY(3),
/**
* Porting library
*/
TOKEN_INDEX_DEST_LIBRARY(4),
/**
* Class
*/
TOKEN_INDEX_CLAZZ(5),
/**
* Porting the original file
*/
TOKEN_INDEX_FILES(6),
/**
* Search corresponding line
*/
TOKEN_INDEX_HIT_LINE(7),
/**
* Result detail
*/
TOKEN_INDEX_DETAIL(8),
/**
* Remarks
*/
TOKEN_INDEX_NOTE(9);
/**
* CSV column Index value
*/
private int index;
/**
* The maximum number of CSV delimiter
*/
public static final int CSV_COLUMN_NUM = 8;
/**
* Constructor.<br/>
* Do not do anything.<br/>
*
* @param index
* CSV column Index value
*/
private WSearchCsvEnum(int index) {
this.index = index;
}
/**
* Get the index.<br/>
*
* @return index
*/
public int getIndex() {
return index;
}
/**
* Set the index.<br/>
*
* @param index
* index
*/
public void setIndex(int index) {
this.index = index;
}
} | apache-2.0 |
0359xiaodong/YiBo | YiBoLibrary/src/com/cattong/sns/impl/renren/RenRenStatusAdapter.java | 2034 | package com.cattong.sns.impl.renren;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.cattong.commons.LibException;
import com.cattong.commons.LibResultCode;
import com.cattong.commons.ServiceProvider;
import com.cattong.commons.util.ParseUtil;
import com.cattong.commons.util.StringUtil;
import com.cattong.sns.entity.Status;
public class RenRenStatusAdapter {
public static Status createStatus(String jsonString) throws LibException {
try {
JSONObject json = new JSONObject(jsonString);
return createStatus(json);
} catch (JSONException e) {
throw new LibException(LibResultCode.JSON_PARSE_ERROR, e);
}
}
public static List<Status> createStatusList(String jsonString)
throws LibException {
try {
if (StringUtil.isEquals("{}", jsonString)
|| StringUtil.isEquals("[]", jsonString)) {
return new ArrayList<Status>(0);
}
JSONArray jsonArray = new JSONArray(jsonString);
int length = jsonArray.length();
List<Status> statuses = new ArrayList<Status>(length);
for (int i = 0; i < length; i++) {
statuses.add(createStatus(jsonArray.getJSONObject(i)));
}
return statuses;
} catch (JSONException e) {
throw new LibException(LibResultCode.JSON_PARSE_ERROR, e);
}
}
public static Status createStatus(JSONObject json) throws LibException {
if (json == null) {
return null;
}
try {
Status status = new Status();
status.setId(ParseUtil.getRawString("status_id", json));
status.setText(ParseUtil.getRawString("message", json));
status.setUpdatedTime(ParseUtil.getDate("time", json, "yyyy-MM-dd hh:mm:ss"));
status.setCommentsCount(ParseUtil.getInt("comment_count", json));
status.setServiceProvider(ServiceProvider.RenRen);
return status;
} catch (ParseException e) {
throw new LibException(LibResultCode.DATE_PARSE_ERROR, e);
}
}
}
| apache-2.0 |
kares/killbill | payment/src/main/java/org/killbill/billing/payment/invoice/PaymentTagHandler.java | 4302 | /*
* Copyright 2010-2013 Ning, Inc.
*
* Ning 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.killbill.billing.payment.invoice;
import java.util.UUID;
import org.killbill.billing.ObjectType;
import org.killbill.billing.account.api.Account;
import org.killbill.billing.account.api.AccountApiException;
import org.killbill.billing.account.api.AccountInternalApi;
import org.killbill.billing.callcontext.InternalCallContext;
import org.killbill.billing.events.ControlTagDeletionInternalEvent;
import org.killbill.billing.osgi.api.OSGIServiceRegistration;
import org.killbill.billing.payment.core.PaymentProcessor;
import org.killbill.billing.routing.plugin.api.PaymentRoutingPluginApi;
import org.killbill.billing.util.callcontext.CallOrigin;
import org.killbill.billing.util.callcontext.InternalCallContextFactory;
import org.killbill.billing.util.callcontext.UserType;
import org.killbill.billing.util.tag.ControlTagType;
import org.killbill.clock.Clock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
public class PaymentTagHandler {
private static final Logger log = LoggerFactory.getLogger(PaymentTagHandler.class);
private final Clock clock;
private final AccountInternalApi accountApi;
private final PaymentProcessor paymentProcessor;
private final InternalCallContextFactory internalCallContextFactory;
private final OSGIServiceRegistration<PaymentRoutingPluginApi> paymentControlPluginRegistry;
private final PaymentRoutingPluginApi invoicePaymentControlPlugin;
@Inject
public PaymentTagHandler(final Clock clock,
final AccountInternalApi accountApi,
final PaymentProcessor paymentProcessor,
final OSGIServiceRegistration<PaymentRoutingPluginApi> paymentControlPluginRegistry,
final InternalCallContextFactory internalCallContextFactory) {
this.clock = clock;
this.accountApi = accountApi;
this.paymentProcessor = paymentProcessor;
this.paymentControlPluginRegistry = paymentControlPluginRegistry;
this.invoicePaymentControlPlugin = paymentControlPluginRegistry.getServiceForName(InvoicePaymentRoutingPluginApi.PLUGIN_NAME);
this.internalCallContextFactory = internalCallContextFactory;
}
@Subscribe
public void process_AUTO_PAY_OFF_removal(final ControlTagDeletionInternalEvent event) {
if (event.getTagDefinition().getName().equals(ControlTagType.AUTO_PAY_OFF.toString()) && event.getObjectType() == ObjectType.ACCOUNT) {
final UUID accountId = event.getObjectId();
processUnpaid_AUTO_PAY_OFF_payments(accountId, event.getSearchKey1(), event.getSearchKey2(), event.getUserToken());
}
}
private void processUnpaid_AUTO_PAY_OFF_payments(final UUID accountId, final Long accountRecordId, final Long tenantRecordId, final UUID userToken) {
try {
final InternalCallContext internalCallContext = internalCallContextFactory.createInternalCallContext(tenantRecordId, accountRecordId,
"PaymentRequestProcessor", CallOrigin.INTERNAL, UserType.SYSTEM, userToken);
final Account account = accountApi.getAccountById(accountId, internalCallContext);
((InvoicePaymentRoutingPluginApi) invoicePaymentControlPlugin).process_AUTO_PAY_OFF_removal(account, internalCallContext);
} catch (AccountApiException e) {
log.warn(String.format("Failed to process process removal AUTO_PAY_OFF for account %s", accountId), e);
}
}
}
| apache-2.0 |
raphaelning/resteasy-client-android | jaxrs/examples/oauth1-examples/oauth/src/main/java/org/jboss/resteasy/examples/oauth/OAuthApplication.java | 697 | package org.jboss.resteasy.examples.oauth;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision$
*/
public class OAuthApplication extends Application
{
HashSet<Object> singletons = new HashSet<Object>();
public OAuthApplication()
{
singletons.add(new ConsumerResource());
singletons.add(new ServiceProviderResource());
}
@Override
public Set<Class<?>> getClasses()
{
HashSet<Class<?>> set = new HashSet<Class<?>>();
return set;
}
@Override
public Set<Object> getSingletons()
{
return singletons;
}
}
| apache-2.0 |
metinkale38/prayer-times-android | features/times/src/main/java/com/metinkale/prayer/times/gson/BooleanSerializer.java | 1540 | /*
* Copyright (c) 2013-2019 Metin Kale
*
* 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.metinkale.prayer.times.gson;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
public class BooleanSerializer implements JsonSerializer<Boolean>, JsonDeserializer<Boolean> {
@Nullable
@Override
public JsonElement serialize(Boolean arg0, Type arg1, JsonSerializationContext arg2) {
return arg0 ? new JsonPrimitive(1) : new JsonPrimitive(0);
}
@NonNull
@Override
public Boolean deserialize(@NonNull JsonElement arg0, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
return arg0.getAsInt() == 1;
}
} | apache-2.0 |
radicalbit/ambari | ambari-shell/ambari-groovy-shell/src/test/java/org/apache/ambari/shell/commands/ConfigCommandsTest.java | 3539 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ambari.shell.commands;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.ambari.groovy.client.AmbariClient;
import org.apache.ambari.shell.completion.ConfigType;
import org.apache.ambari.shell.model.AmbariContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class ConfigCommandsTest {
private static final String CORE_SITE = "core-site";
@InjectMocks
private ConfigCommands configCommands;
@Mock
private AmbariClient client;
@Mock
private AmbariContext context;
@Test
public void testShowConfig() {
ConfigType configType = mock(ConfigType.class);
Map<String, Map<String, String>> mockResult = mock(Map.class);
when(configType.getName()).thenReturn(CORE_SITE);
when(client.getServiceConfigMap(anyString())).thenReturn(mockResult);
when(mockResult.get(CORE_SITE)).thenReturn(new HashMap<String, String>());
configCommands.showConfig(configType);
verify(client).getServiceConfigMap(CORE_SITE);
}
@Test
public void testSetConfigForFile() throws IOException {
ConfigType configType = mock(ConfigType.class);
File file = new File("src/test/resources/core-site.xml");
when(configType.getName()).thenReturn(CORE_SITE);
configCommands.setConfig(configType, "", file);
Map<String, String> config = new HashMap<String, String>();
config.put("fs.trash.interval", "350");
config.put("ipc.client.connection.maxidletime", "30000");
verify(client).modifyConfiguration(CORE_SITE, config);
}
@Test
public void testModifyConfig() throws IOException {
ConfigType configType = mock(ConfigType.class);
Map<String, Map<String, String>> mockResult = mock(Map.class);
Map<String, String> config = new HashMap<String, String>();
config.put("fs.trash.interval", "350");
config.put("ipc.client.connection.maxidletime", "30000");
when(configType.getName()).thenReturn(CORE_SITE);
when(mockResult.get(CORE_SITE)).thenReturn(config);
when(client.getServiceConfigMap(CORE_SITE)).thenReturn(mockResult);
configCommands.modifyConfig(configType, "fs.trash.interval", "510");
Map<String, String> config2 = new HashMap<String, String>();
config2.put("fs.trash.interval", "510");
config2.put("ipc.client.connection.maxidletime", "30000");
verify(client).modifyConfiguration(CORE_SITE, config2);
}
}
| apache-2.0 |
tgwizard/sls | app/src/main/java/com/adam/aslfms/util/enums/AdvancedOptions.java | 4334 | /**
* This file is part of Simple Scrobbler.
* <p>
* https://github.com/simple-last-fm-scrobbler/sls
* <p>
* Copyright 2011 Simple Scrobbler Team
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adam.aslfms.util.enums;
import android.content.Context;
import android.util.Log;
import com.adam.aslfms.R;
import java.util.HashMap;
import java.util.Map;
public enum AdvancedOptions {
// the values below for SAME will be ignored
SAME_AS_BATTERY(
"ao_same_as_battery", true, true, true, AdvancedOptionsWhen.AFTER_1, true, NetworkOptions.ANY, true,
R.string.advanced_options_type_same_as_battery_name),
STANDARD(
"ao_standard", true, true, true, AdvancedOptionsWhen.AFTER_1, true, NetworkOptions.ANY, true,
R.string.advanced_options_type_standard_name),
// not available for plugged in
BATTERY_SAVING(
"ao_battery", true, true, false, AdvancedOptionsWhen.AFTER_10, true, NetworkOptions.ANY, false,
R.string.advanced_options_type_battery_name),
// the values below for CUSTOM will be ignored
CUSTOM(
"ao_custom", true, true, true, AdvancedOptionsWhen.AFTER_1, true, NetworkOptions.ANY, true,
R.string.advanced_options_type_custom_name);
private final String settingsVal;
private final boolean enableActiveApp;
private final boolean enableScrobbling;
private final boolean enableNp;
private final AdvancedOptionsWhen when;
private final boolean alsoOnComplete;
private final NetworkOptions networkOptions;
private final boolean roaming;
private final int nameRID;
AdvancedOptions(String settingsVal, boolean enableActiveApp, boolean enableScrobbling, boolean enableNp, AdvancedOptionsWhen when,
boolean alsoOnComplete, NetworkOptions networkOptions, boolean roaming, int nameRID) {
this.settingsVal = settingsVal;
this.enableActiveApp = enableActiveApp;
this.enableScrobbling = enableScrobbling;
this.enableNp = enableNp;
this.when = when;
this.alsoOnComplete = alsoOnComplete;
this.networkOptions = networkOptions;
this.roaming = roaming;
this.nameRID = nameRID;
}
// these methods are intentionally package-private, they are only used
// by AppSettings
public String getSettingsVal() {
return settingsVal;
}
public boolean isActiveAppEnabled() {
return enableActiveApp;
}
public boolean isScrobblingEnabled() {
return enableScrobbling;
}
public boolean isNpEnabled() {
return enableNp;
}
public AdvancedOptionsWhen getWhen() {
return when;
}
public boolean getAlsoOnComplete() {
return alsoOnComplete;
}
public NetworkOptions getNetworkOptions() {
return networkOptions;
}
public boolean getRoaming() {
return roaming;
}
public String getName(Context ctx) {
return ctx.getString(nameRID);
}
private static final String TAG = "SLSAdvancedOptions";
private static Map<String, AdvancedOptions> mSAOMap;
static {
AdvancedOptions[] aos = AdvancedOptions.values();
mSAOMap = new HashMap<String, AdvancedOptions>(aos.length);
for (AdvancedOptions ao : aos)
mSAOMap.put(ao.getSettingsVal(), ao);
}
public static AdvancedOptions fromSettingsVal(String s) {
AdvancedOptions ao = mSAOMap.get(s);
if (ao == null) {
Log.e(TAG, "got null advanced option from settings, defaulting to standard");
ao = AdvancedOptions.STANDARD;
}
return ao;
}
} | apache-2.0 |
streamsets/datacollector | container/src/main/java/com/streamsets/datacollector/aster/EntitlementSyncTask.java | 1139 | /*
* Copyright 2020 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.datacollector.aster;
import com.streamsets.datacollector.task.Task;
import com.streamsets.lib.security.http.aster.AsterServiceHook;
/**
* Synchronizes entitlements with Aster.
*
* To trigger a synchronization immediately, call {@link #run()}.
*/
public interface EntitlementSyncTask extends Task, AsterServiceHook {
/**
* Immediately get the latest entitlement, and block until this task is complete.
*
* @return true if entitlement was changed, false otherwise
*/
boolean syncEntitlement();
}
| apache-2.0 |
IHTSDO/snow-owl | net4j/com.b2international.snowowl.eventbus/src/com/b2international/snowowl/internal/eventbus/net4j/HandlerChangeIndication.java | 2079 | /*
* Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.internal.eventbus.net4j;
import java.util.Set;
import org.eclipse.net4j.signal.IndicationWithResponse;
import org.eclipse.net4j.util.io.ExtendedDataInputStream;
import org.eclipse.net4j.util.io.ExtendedDataOutputStream;
import com.b2international.snowowl.eventbus.net4j.EventBusConstants;
/**
* @since 3.1
*/
public class HandlerChangeIndication extends IndicationWithResponse {
public HandlerChangeIndication(EventBusProtocol protocol, short signalID) {
super(protocol, signalID);
}
@Override
protected void indicating(ExtendedDataInputStream in) throws Exception {
final Object set = in.readObject();
if (set instanceof Set) {
if (getID() == EventBusConstants.HANDLER_UNREGISTRATION) {
getProtocol().unregisterAddressBook((Set<String>)set);
} else {
getProtocol().registerAddressBook((Set<String>)set);
}
}
}
@Override
protected void responding(ExtendedDataOutputStream out) throws Exception {
switch (getID()) {
case EventBusConstants.HANDLER_INIT: {
out.writeObject(getProtocol().getInfraStructure().getAddressBook());
break;
}
case EventBusConstants.HANDLER_REGISTRATION:
case EventBusConstants.HANDLER_UNREGISTRATION:
out.writeBoolean(true);
break;
default:
throw new IllegalArgumentException("Unknown signalID: " + getID());
}
}
@Override
public EventBusProtocol getProtocol() {
return (EventBusProtocol) super.getProtocol();
}
} | apache-2.0 |
jwren/intellij-community | java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/qualifyMethodCall/beforeNonStaticMethodFromNonStaticContext2.java | 214 | // "Qualify the call with 'A.B.this'" "true"
class A {
static class B {
class C {
String name(String key) {
return name(<caret>);
}
}
String name() {
return "";
}
}
}
| apache-2.0 |
apache/tomcat | java/org/apache/catalina/filters/SessionInitializerFilter.java | 2509 | /*
* 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.catalina.filters;
import java.io.IOException;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
/**
* A {@link jakarta.servlet.Filter} that initializes the {@link HttpSession} for
* the {@link HttpServletRequest} by calling its getSession() method.
* <p>
* This is required for some operations with WebSocket requests, where it is
* too late to initialize the HttpSession object, and the current Java WebSocket
* specification does not provide a way to do so.
*/
public class SessionInitializerFilter implements Filter {
/**
* Calls {@link HttpServletRequest}'s getSession() to initialize the
* HttpSession and continues processing the chain.
*
* @param request The request to process
* @param response The response associated with the request
* @param chain Provides access to the next filter in the chain for this
* filter to pass the request and response to for further
* processing
* @throws IOException if an I/O error occurs during this filter's
* processing of the request
* @throws ServletException if the processing fails for any other reason
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
((HttpServletRequest)request).getSession();
chain.doFilter(request, response);
}
}
| apache-2.0 |
jbeecham/ovirt-engine | frontend/webadmin/modules/gwt-common/src/main/java/org/ovirt/engine/ui/common/widget/UiCommandButton.java | 1364 | package org.ovirt.engine.ui.common.widget;
import org.ovirt.engine.ui.common.widget.dialog.SimpleDialogButton;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.ButtonBase;
import com.google.gwt.user.client.ui.Widget;
public class UiCommandButton extends AbstractUiCommandButton {
interface WidgetUiBinder extends UiBinder<Widget, UiCommandButton> {
WidgetUiBinder uiBinder = GWT.create(WidgetUiBinder.class);
}
@UiField
SimpleDialogButton button;
public UiCommandButton() {
initWidget(WidgetUiBinder.uiBinder.createAndBindUi(this));
}
public UiCommandButton(String label) {
this(label, null);
}
public UiCommandButton(ImageResource image) {
this("", image); //$NON-NLS-1$
}
public UiCommandButton(String label, ImageResource image) {
this();
setLabel(label);
setImage(image);
}
@Override
protected ButtonBase getButtonWidget() {
return button;
}
public void setImage(ImageResource image) {
button.setImage(image);
}
public void setCustomContentStyle(String customStyle) {
button.setCustomContentStyle(customStyle);
}
}
| apache-2.0 |
lordjone/libgdx | backends/gdx-backend-jglfw/src/com/badlogic/gdx/backends/jglfw/JglfwInput.java | 22979 | /*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.gdx.backends.jglfw;
import static com.badlogic.jglfw.Glfw.*;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.OverlayLayout;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.InputProcessorQueue;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.jglfw.GlfwCallbackAdapter;
/** An implementation of the {@link Input} interface hooking GLFW panel for input.
* @author mzechner
* @author Nathan Sweet */
public class JglfwInput implements Input {
final JglfwApplication app;
final InputProcessorQueue processorQueue;
InputProcessor processor;
int pressedKeys = 0;
boolean justTouched;
int deltaX, deltaY;
long currentEventTime;
public JglfwInput (final JglfwApplication app, boolean queueEvents) {
this.app = app;
InputProcessor inputProcessor = new InputProcessor() {
private int mouseX, mouseY;
public boolean keyDown (int keycode) {
pressedKeys++;
app.graphics.requestRendering();
return processor != null ? processor.keyDown(keycode) : false;
}
public boolean keyUp (int keycode) {
pressedKeys--;
app.graphics.requestRendering();
return processor != null ? processor.keyUp(keycode) : false;
}
public boolean keyTyped (char character) {
app.graphics.requestRendering();
return processor != null ? processor.keyTyped(character) : false;
}
public boolean touchDown (int screenX, int screenY, int pointer, int button) {
justTouched = true;
app.graphics.requestRendering();
return processor != null ? processor.touchDown(screenX, screenY, pointer, button) : false;
}
public boolean touchUp (int screenX, int screenY, int pointer, int button) {
app.graphics.requestRendering();
return processor != null ? processor.touchUp(screenX, screenY, pointer, button) : false;
}
public boolean touchDragged (int screenX, int screenY, int pointer) {
deltaX = screenX - mouseX;
deltaY = screenY - mouseY;
mouseX = screenX;
mouseY = screenY;
app.graphics.requestRendering();
return processor != null ? processor.touchDragged(mouseX, mouseY, 0) : false;
}
public boolean mouseMoved (int screenX, int screenY) {
deltaX = screenX - mouseX;
deltaY = screenY - mouseX;
mouseX = screenX;
mouseY = screenY;
app.graphics.requestRendering();
return processor != null ? processor.mouseMoved(mouseX, mouseY) : false;
}
public boolean scrolled (int amount) {
app.graphics.requestRendering();
return processor != null ? processor.scrolled(amount) : false;
}
};
if (queueEvents)
inputProcessor = processorQueue = new InputProcessorQueue(inputProcessor);
else
processorQueue = null;
app.getCallbacks().add(new GlfwInputProcessor(inputProcessor));
}
public void update () {
justTouched = false;
if (processorQueue != null)
processorQueue.drain(); // Main loop is handled elsewhere and events are queued.
else {
currentEventTime = System.nanoTime();
glfwPollEvents(); // Use GLFW main loop to process events.
}
}
public float getAccelerometerX () {
return 0;
}
public float getAccelerometerY () {
return 0;
}
public float getAccelerometerZ () {
return 0;
}
public int getX () {
return glfwGetCursorPosX(app.graphics.window);
}
public int getX (int pointer) {
return pointer > 0 ? 0 : getX();
}
public int getY () {
return glfwGetCursorPosY(app.graphics.window);
}
public int getY (int pointer) {
return pointer > 0 ? 0 : getY();
}
public int getDeltaX () {
return deltaX;
}
public int getDeltaX (int pointer) {
return pointer > 0 ? 0 : deltaX;
}
public int getDeltaY () {
return deltaY;
}
public int getDeltaY (int pointer) {
return pointer > 0 ? 0 : deltaY;
}
public boolean isTouched () {
return glfwGetMouseButton(app.graphics.window, 0) || glfwGetMouseButton(app.graphics.window, 1)
|| glfwGetMouseButton(app.graphics.window, 2);
}
public boolean isTouched (int pointer) {
return pointer > 0 ? false : isTouched();
}
public boolean justTouched () {
return justTouched;
}
public boolean isButtonPressed (int button) {
return glfwGetMouseButton(app.graphics.window, button);
}
public boolean isKeyPressed (int key) {
if (key == Input.Keys.ANY_KEY) return pressedKeys > 0;
if (key == Input.Keys.SYM)
return glfwGetKey(app.graphics.window, GLFW_KEY_LEFT_SUPER) || glfwGetKey(app.graphics.window, GLFW_KEY_RIGHT_SUPER);
return glfwGetKey(app.graphics.window, getJglfwKeyCode(key));
}
public void setOnscreenKeyboardVisible (boolean visible) {
}
public void vibrate (int milliseconds) {
}
public void vibrate (long[] pattern, int repeat) {
}
public void cancelVibrate () {
}
public float getAzimuth () {
return 0;
}
public float getPitch () {
return 0;
}
public float getRoll () {
return 0;
}
public void getRotationMatrix (float[] matrix) {
}
public long getCurrentEventTime () {
return processorQueue != null ? processorQueue.getCurrentEventTime() : currentEventTime;
}
public void setCatchBackKey (boolean catchBack) {
}
public void setCatchMenuKey (boolean catchMenu) {
}
public void setInputProcessor (InputProcessor processor) {
this.processor = processor;
}
public InputProcessor getInputProcessor () {
return processor;
}
public boolean isPeripheralAvailable (Peripheral peripheral) {
return peripheral == Peripheral.HardwareKeyboard;
}
public int getRotation () {
return 0;
}
public Orientation getNativeOrientation () {
return Orientation.Landscape;
}
public void setCursorCatched (boolean captured) {
glfwSetInputMode(app.graphics.window, GLFW_CURSOR_MODE, captured ? GLFW_CURSOR_CAPTURED : GLFW_CURSOR_NORMAL);
}
public boolean isCursorCatched () {
return glfwGetInputMode(app.graphics.window, GLFW_CURSOR_MODE) == GLFW_CURSOR_CAPTURED;
}
public void setCursorPosition (int x, int y) {
glfwSetCursorPos(app.graphics.window, x, y);
}
@Override
public void setCursorImage (Pixmap pixmap, int xHotspot, int yHotspot) {
}
public void getTextInput (final TextInputListener listener, final String title, final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run () {
final String output = JOptionPane.showInputDialog(null, title, text);
app.postRunnable(new Runnable() {
public void run () {
if (output != null)
listener.input(output);
else
listener.canceled();
}
});
}
});
}
public void getPlaceholderTextInput (final TextInputListener listener, final String title, final String placeholder) {
SwingUtilities.invokeLater(new Runnable() {
public void run () {
JPanel panel = new JPanel(new FlowLayout());
JPanel textPanel = new JPanel() {
public boolean isOptimizedDrawingEnabled () {
return false;
};
};
textPanel.setLayout(new OverlayLayout(textPanel));
panel.add(textPanel);
final JTextField textField = new JTextField(20);
textField.setAlignmentX(0.0f);
textPanel.add(textField);
final JLabel placeholderLabel = new JLabel(placeholder);
placeholderLabel.setForeground(Color.GRAY);
placeholderLabel.setAlignmentX(0.0f);
textPanel.add(placeholderLabel, 0);
textField.getDocument().addDocumentListener(new DocumentListener() {
public void removeUpdate (DocumentEvent event) {
this.updated();
}
public void insertUpdate (DocumentEvent event) {
this.updated();
}
public void changedUpdate (DocumentEvent event) {
this.updated();
}
private void updated () {
placeholderLabel.setVisible(textField.getText().length() == 0);
}
});
JOptionPane pane = new JOptionPane(panel, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, null,
null);
pane.setComponentOrientation(JOptionPane.getRootFrame().getComponentOrientation());
pane.selectInitialValue();
placeholderLabel.setBorder(new EmptyBorder(textField.getBorder().getBorderInsets(textField)));
JDialog dialog = pane.createDialog(null, title);
dialog.addWindowFocusListener(new WindowFocusListener() {
public void windowLostFocus (WindowEvent arg0) {
}
public void windowGainedFocus (WindowEvent arg0) {
textField.requestFocusInWindow();
}
});
dialog.setVisible(true);
dialog.dispose();
Object selectedValue = pane.getValue();
if (selectedValue != null && (selectedValue instanceof Integer) && (Integer)selectedValue == JOptionPane.OK_OPTION)
listener.input(textField.getText());
else
listener.canceled();
}
});
}
static char characterForKeyCode (int key) {
// Map certain key codes to character codes.
switch (key) {
case Keys.BACKSPACE:
return 8;
case Keys.TAB:
return '\t';
case Keys.FORWARD_DEL:
return 127;
}
return 0;
}
static public int getGdxKeyCode (int lwjglKeyCode) {
switch (lwjglKeyCode) {
case GLFW_KEY_SPACE:
return Input.Keys.SPACE;
case GLFW_KEY_APOSTROPHE:
return Input.Keys.APOSTROPHE;
case GLFW_KEY_COMMA:
return Input.Keys.COMMA;
case GLFW_KEY_MINUS:
return Input.Keys.MINUS;
case GLFW_KEY_PERIOD:
return Input.Keys.PERIOD;
case GLFW_KEY_SLASH:
return Input.Keys.SLASH;
case GLFW_KEY_0:
return Input.Keys.NUM_0;
case GLFW_KEY_1:
return Input.Keys.NUM_1;
case GLFW_KEY_2:
return Input.Keys.NUM_2;
case GLFW_KEY_3:
return Input.Keys.NUM_3;
case GLFW_KEY_4:
return Input.Keys.NUM_4;
case GLFW_KEY_5:
return Input.Keys.NUM_5;
case GLFW_KEY_6:
return Input.Keys.NUM_6;
case GLFW_KEY_7:
return Input.Keys.NUM_7;
case GLFW_KEY_8:
return Input.Keys.NUM_8;
case GLFW_KEY_9:
return Input.Keys.NUM_9;
case GLFW_KEY_SEMICOLON:
return Input.Keys.SEMICOLON;
case GLFW_KEY_EQUAL:
return Input.Keys.EQUALS;
case GLFW_KEY_A:
return Input.Keys.A;
case GLFW_KEY_B:
return Input.Keys.B;
case GLFW_KEY_C:
return Input.Keys.C;
case GLFW_KEY_D:
return Input.Keys.D;
case GLFW_KEY_E:
return Input.Keys.E;
case GLFW_KEY_F:
return Input.Keys.F;
case GLFW_KEY_G:
return Input.Keys.G;
case GLFW_KEY_H:
return Input.Keys.H;
case GLFW_KEY_I:
return Input.Keys.I;
case GLFW_KEY_J:
return Input.Keys.J;
case GLFW_KEY_K:
return Input.Keys.K;
case GLFW_KEY_L:
return Input.Keys.L;
case GLFW_KEY_M:
return Input.Keys.M;
case GLFW_KEY_N:
return Input.Keys.N;
case GLFW_KEY_O:
return Input.Keys.O;
case GLFW_KEY_P:
return Input.Keys.P;
case GLFW_KEY_Q:
return Input.Keys.Q;
case GLFW_KEY_R:
return Input.Keys.R;
case GLFW_KEY_S:
return Input.Keys.S;
case GLFW_KEY_T:
return Input.Keys.T;
case GLFW_KEY_U:
return Input.Keys.U;
case GLFW_KEY_V:
return Input.Keys.V;
case GLFW_KEY_W:
return Input.Keys.W;
case GLFW_KEY_X:
return Input.Keys.X;
case GLFW_KEY_Y:
return Input.Keys.Y;
case GLFW_KEY_Z:
return Input.Keys.Z;
case GLFW_KEY_LEFT_BRACKET:
return Input.Keys.LEFT_BRACKET;
case GLFW_KEY_BACKSLASH:
return Input.Keys.BACKSLASH;
case GLFW_KEY_RIGHT_BRACKET:
return Input.Keys.RIGHT_BRACKET;
case GLFW_KEY_GRAVE_ACCENT:
return Input.Keys.GRAVE;
case GLFW_KEY_WORLD_1:
case GLFW_KEY_WORLD_2:
return Input.Keys.UNKNOWN;
case GLFW_KEY_ESCAPE:
return Input.Keys.ESCAPE;
case GLFW_KEY_ENTER:
return Input.Keys.ENTER;
case GLFW_KEY_TAB:
return Input.Keys.TAB;
case GLFW_KEY_BACKSPACE:
return Input.Keys.BACKSPACE;
case GLFW_KEY_INSERT:
return Input.Keys.INSERT;
case GLFW_KEY_DELETE:
return Input.Keys.FORWARD_DEL;
case GLFW_KEY_RIGHT:
return Input.Keys.RIGHT;
case GLFW_KEY_LEFT:
return Input.Keys.LEFT;
case GLFW_KEY_DOWN:
return Input.Keys.DOWN;
case GLFW_KEY_UP:
return Input.Keys.UP;
case GLFW_KEY_PAGE_UP:
return Input.Keys.PAGE_UP;
case GLFW_KEY_PAGE_DOWN:
return Input.Keys.PAGE_DOWN;
case GLFW_KEY_HOME:
return Input.Keys.HOME;
case GLFW_KEY_END:
return Input.Keys.END;
case GLFW_KEY_CAPS_LOCK:
case GLFW_KEY_SCROLL_LOCK:
case GLFW_KEY_NUM_LOCK:
case GLFW_KEY_PRINT_SCREEN:
case GLFW_KEY_PAUSE:
return Input.Keys.UNKNOWN;
case GLFW_KEY_F1:
return Input.Keys.F1;
case GLFW_KEY_F2:
return Input.Keys.F2;
case GLFW_KEY_F3:
return Input.Keys.F3;
case GLFW_KEY_F4:
return Input.Keys.F4;
case GLFW_KEY_F5:
return Input.Keys.F5;
case GLFW_KEY_F6:
return Input.Keys.F6;
case GLFW_KEY_F7:
return Input.Keys.F7;
case GLFW_KEY_F8:
return Input.Keys.F8;
case GLFW_KEY_F9:
return Input.Keys.F9;
case GLFW_KEY_F10:
return Input.Keys.F10;
case GLFW_KEY_F11:
return Input.Keys.F11;
case GLFW_KEY_F12:
return Input.Keys.F12;
case GLFW_KEY_F13:
case GLFW_KEY_F14:
case GLFW_KEY_F15:
case GLFW_KEY_F16:
case GLFW_KEY_F17:
case GLFW_KEY_F18:
case GLFW_KEY_F19:
case GLFW_KEY_F20:
case GLFW_KEY_F21:
case GLFW_KEY_F22:
case GLFW_KEY_F23:
case GLFW_KEY_F24:
case GLFW_KEY_F25:
return Input.Keys.UNKNOWN;
case GLFW_KEY_KP_0:
return Input.Keys.NUMPAD_0;
case GLFW_KEY_KP_1:
return Input.Keys.NUMPAD_1;
case GLFW_KEY_KP_2:
return Input.Keys.NUMPAD_2;
case GLFW_KEY_KP_3:
return Input.Keys.NUMPAD_3;
case GLFW_KEY_KP_4:
return Input.Keys.NUMPAD_4;
case GLFW_KEY_KP_5:
return Input.Keys.NUMPAD_5;
case GLFW_KEY_KP_6:
return Input.Keys.NUMPAD_6;
case GLFW_KEY_KP_7:
return Input.Keys.NUMPAD_7;
case GLFW_KEY_KP_8:
return Input.Keys.NUMPAD_8;
case GLFW_KEY_KP_9:
return Input.Keys.NUMPAD_9;
case GLFW_KEY_KP_DECIMAL:
return Input.Keys.PERIOD;
case GLFW_KEY_KP_DIVIDE:
return Input.Keys.SLASH;
case GLFW_KEY_KP_MULTIPLY:
return Input.Keys.STAR;
case GLFW_KEY_KP_SUBTRACT:
return Input.Keys.MINUS;
case GLFW_KEY_KP_ADD:
return Input.Keys.PLUS;
case GLFW_KEY_KP_ENTER:
return Input.Keys.ENTER;
case GLFW_KEY_KP_EQUAL:
return Input.Keys.EQUALS;
case GLFW_KEY_LEFT_SHIFT:
return Input.Keys.SHIFT_LEFT;
case GLFW_KEY_LEFT_CONTROL:
return Input.Keys.CONTROL_LEFT;
case GLFW_KEY_LEFT_ALT:
return Input.Keys.ALT_LEFT;
case GLFW_KEY_LEFT_SUPER:
return Input.Keys.SYM;
case GLFW_KEY_RIGHT_SHIFT:
return Input.Keys.SHIFT_RIGHT;
case GLFW_KEY_RIGHT_CONTROL:
return Input.Keys.CONTROL_RIGHT;
case GLFW_KEY_RIGHT_ALT:
return Input.Keys.ALT_RIGHT;
case GLFW_KEY_RIGHT_SUPER:
return Input.Keys.SYM;
case GLFW_KEY_MENU:
return Input.Keys.MENU;
default:
return Input.Keys.UNKNOWN;
}
}
static public int getJglfwKeyCode (int gdxKeyCode) {
switch (gdxKeyCode) {
case Input.Keys.SPACE:
return GLFW_KEY_SPACE;
case Input.Keys.APOSTROPHE:
return GLFW_KEY_APOSTROPHE;
case Input.Keys.COMMA:
return GLFW_KEY_COMMA;
case Input.Keys.PERIOD:
return GLFW_KEY_PERIOD;
case Input.Keys.NUM_0:
return GLFW_KEY_0;
case Input.Keys.NUM_1:
return GLFW_KEY_1;
case Input.Keys.NUM_2:
return GLFW_KEY_2;
case Input.Keys.NUM_3:
return GLFW_KEY_3;
case Input.Keys.NUM_4:
return GLFW_KEY_4;
case Input.Keys.NUM_5:
return GLFW_KEY_5;
case Input.Keys.NUM_6:
return GLFW_KEY_6;
case Input.Keys.NUM_7:
return GLFW_KEY_7;
case Input.Keys.NUM_8:
return GLFW_KEY_8;
case Input.Keys.NUM_9:
return GLFW_KEY_9;
case Input.Keys.SEMICOLON:
return GLFW_KEY_SEMICOLON;
case Input.Keys.EQUALS:
return GLFW_KEY_EQUAL;
case Input.Keys.A:
return GLFW_KEY_A;
case Input.Keys.B:
return GLFW_KEY_B;
case Input.Keys.C:
return GLFW_KEY_C;
case Input.Keys.D:
return GLFW_KEY_D;
case Input.Keys.E:
return GLFW_KEY_E;
case Input.Keys.F:
return GLFW_KEY_F;
case Input.Keys.G:
return GLFW_KEY_G;
case Input.Keys.H:
return GLFW_KEY_H;
case Input.Keys.I:
return GLFW_KEY_I;
case Input.Keys.J:
return GLFW_KEY_J;
case Input.Keys.K:
return GLFW_KEY_K;
case Input.Keys.L:
return GLFW_KEY_L;
case Input.Keys.M:
return GLFW_KEY_M;
case Input.Keys.N:
return GLFW_KEY_N;
case Input.Keys.O:
return GLFW_KEY_O;
case Input.Keys.P:
return GLFW_KEY_P;
case Input.Keys.Q:
return GLFW_KEY_Q;
case Input.Keys.R:
return GLFW_KEY_R;
case Input.Keys.S:
return GLFW_KEY_S;
case Input.Keys.T:
return GLFW_KEY_T;
case Input.Keys.U:
return GLFW_KEY_U;
case Input.Keys.V:
return GLFW_KEY_V;
case Input.Keys.W:
return GLFW_KEY_W;
case Input.Keys.X:
return GLFW_KEY_X;
case Input.Keys.Y:
return GLFW_KEY_Y;
case Input.Keys.Z:
return GLFW_KEY_Z;
case Input.Keys.LEFT_BRACKET:
return GLFW_KEY_LEFT_BRACKET;
case Input.Keys.BACKSLASH:
return GLFW_KEY_BACKSLASH;
case Input.Keys.RIGHT_BRACKET:
return GLFW_KEY_RIGHT_BRACKET;
case Input.Keys.GRAVE:
return GLFW_KEY_GRAVE_ACCENT;
case Input.Keys.ESCAPE:
return GLFW_KEY_ESCAPE;
case Input.Keys.ENTER:
return GLFW_KEY_ENTER;
case Input.Keys.TAB:
return GLFW_KEY_TAB;
case Input.Keys.BACKSPACE:
return GLFW_KEY_BACKSPACE;
case Input.Keys.INSERT:
return GLFW_KEY_INSERT;
case Input.Keys.FORWARD_DEL:
return GLFW_KEY_DELETE;
case Input.Keys.RIGHT:
return GLFW_KEY_RIGHT;
case Input.Keys.LEFT:
return GLFW_KEY_LEFT;
case Input.Keys.DOWN:
return GLFW_KEY_DOWN;
case Input.Keys.UP:
return GLFW_KEY_UP;
case Input.Keys.PAGE_UP:
return GLFW_KEY_PAGE_UP;
case Input.Keys.PAGE_DOWN:
return GLFW_KEY_PAGE_DOWN;
case Input.Keys.HOME:
return GLFW_KEY_HOME;
case Input.Keys.END:
return GLFW_KEY_END;
case Input.Keys.F1:
return GLFW_KEY_F1;
case Input.Keys.F2:
return GLFW_KEY_F2;
case Input.Keys.F3:
return GLFW_KEY_F3;
case Input.Keys.F4:
return GLFW_KEY_F4;
case Input.Keys.F5:
return GLFW_KEY_F5;
case Input.Keys.F6:
return GLFW_KEY_F6;
case Input.Keys.F7:
return GLFW_KEY_F7;
case Input.Keys.F8:
return GLFW_KEY_F8;
case Input.Keys.F9:
return GLFW_KEY_F9;
case Input.Keys.F10:
return GLFW_KEY_F10;
case Input.Keys.F11:
return GLFW_KEY_F11;
case Input.Keys.F12:
return GLFW_KEY_F12;
case Input.Keys.NUMPAD_0:
return GLFW_KEY_KP_0;
case Input.Keys.NUMPAD_1:
return GLFW_KEY_KP_1;
case Input.Keys.NUMPAD_2:
return GLFW_KEY_KP_2;
case Input.Keys.NUMPAD_3:
return GLFW_KEY_KP_3;
case Input.Keys.NUMPAD_4:
return GLFW_KEY_KP_4;
case Input.Keys.NUMPAD_5:
return GLFW_KEY_KP_5;
case Input.Keys.NUMPAD_6:
return GLFW_KEY_KP_6;
case Input.Keys.NUMPAD_7:
return GLFW_KEY_KP_7;
case Input.Keys.NUMPAD_8:
return GLFW_KEY_KP_8;
case Input.Keys.NUMPAD_9:
return GLFW_KEY_KP_9;
case Input.Keys.SLASH:
return GLFW_KEY_KP_DIVIDE;
case Input.Keys.STAR:
return GLFW_KEY_KP_MULTIPLY;
case Input.Keys.MINUS:
return GLFW_KEY_KP_SUBTRACT;
case Input.Keys.PLUS:
return GLFW_KEY_KP_ADD;
case Input.Keys.SHIFT_LEFT:
return GLFW_KEY_LEFT_SHIFT;
case Input.Keys.CONTROL_LEFT:
return GLFW_KEY_LEFT_CONTROL;
case Input.Keys.ALT_LEFT:
return GLFW_KEY_LEFT_ALT;
case Input.Keys.SYM:
return GLFW_KEY_LEFT_SUPER;
case Input.Keys.SHIFT_RIGHT:
return GLFW_KEY_RIGHT_SHIFT;
case Input.Keys.CONTROL_RIGHT:
return GLFW_KEY_RIGHT_CONTROL;
case Input.Keys.ALT_RIGHT:
return GLFW_KEY_RIGHT_ALT;
case Input.Keys.MENU:
return GLFW_KEY_MENU;
default:
return 0;
}
}
/** Receives GLFW input and calls InputProcessor methods.
* @author Nathan Sweet */
static class GlfwInputProcessor extends GlfwCallbackAdapter {
private int mouseX, mouseY, mousePressed;
private char lastCharacter;
private InputProcessor processor;
public GlfwInputProcessor (InputProcessor processor) {
if (processor == null) throw new IllegalArgumentException("processor cannot be null.");
this.processor = processor;
}
public void key (long window, int key, int action) {
switch (action) {
case GLFW_PRESS:
key = getGdxKeyCode(key);
processor.keyDown(key);
lastCharacter = 0;
char character = characterForKeyCode(key);
if (character != 0) character(window, character);
break;
case GLFW_RELEASE:
processor.keyUp(getGdxKeyCode(key));
break;
case GLFW_REPEAT:
if (lastCharacter != 0) processor.keyTyped(lastCharacter);
break;
}
}
public void character (long window, char character) {
lastCharacter = character;
processor.keyTyped(character);
}
public void scroll (long window, double scrollX, double scrollY) {
processor.scrolled((int)-Math.signum(scrollY));
}
public void mouseButton (long window, int button, boolean pressed) {
if (pressed) {
mousePressed++;
processor.touchDown(mouseX, mouseY, 0, button);
} else {
mousePressed = Math.max(0, mousePressed - 1);
processor.touchUp(mouseX, mouseY, 0, button);
}
}
public void cursorPos (long window, int x, int y) {
mouseX = x;
mouseY = y;
if (mousePressed > 0)
processor.touchDragged(x, y, 0);
else
processor.mouseMoved(x, y);
}
}
}
| apache-2.0 |
tabish121/proton4j | protonj2/src/main/java/org/apache/qpid/protonj2/codec/EncoderState.java | 1858 | /*
* 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.qpid.protonj2.codec;
import org.apache.qpid.protonj2.buffer.ProtonBuffer;
/**
* Retains Encoder state information either between calls or across encode iterations.
*/
public interface EncoderState {
/**
* @return the Encoder instance that create this state object.
*/
Encoder getEncoder();
/**
* Resets any intermediate state back to default values.
*
* @return this {@link EncoderState} instance.
*/
EncoderState reset();
/**
* Encodes the given sequence of characters in UTF8 to the given buffer.
*
* @param buffer
* A ProtonBuffer where the UTF-8 encoded bytes should be written.
* @param sequence
* A {@link CharSequence} representing the UTF-8 bytes to encode
*
* @return a reference to the encoding buffer for chaining
*
* @throws EncodeException if an error occurs while encoding the {@link CharSequence}
*/
ProtonBuffer encodeUTF8(ProtonBuffer buffer, CharSequence sequence) throws EncodeException;
}
| apache-2.0 |
alexander94dmitriev/PortlandStateJavaSummer2017 | airline/src/main/java/edu/pdx/cs410J/dmitriev/TextParser.java | 5551 | package edu.pdx.cs410J.dmitriev;
import edu.pdx.cs410J.AirlineParser;
import edu.pdx.cs410J.ParserException;
import javax.imageio.IIOException;
import java.io.*;
/**
* TextParser get the name of the file along with the name of the Airline being read.
* It supposed to correctly read the data about the Airline on a specific file along with the flights.
* It should also check that flights data is correct by using the same method that were used to check
* program line arguments.
* If the file does not exist, the class should create it with an empty Airline being added
* It also handles IO and Parser exceptions
*/
public class TextParser implements AirlineParser<Airline> {
private String fileName;
private String airlineToRead;
/**
* Constructor for TextParser
* @param newName
* the name of the file being read/ created with empty Airline
* @param newAirlineToRead
* the name of Airline to read/ add to an empty file
*/
TextParser(String newName, String newAirlineToRead)
{
this.fileName = newName;
this.airlineToRead = newAirlineToRead;
}
/**
* call the readFile() method which will give the complete Airline object.
* The method catches IOException and then throws ParserException with an
* error message, if anything wrong with IO
* @return
* the airline with a given name and/or flights
* @throws ParserException
*/
@Override
public Airline parse() throws ParserException {
//Read text file to object Airline
Airline airline = null;
try {
if(checkFileExistence())
airline = readFile();
else airline = createNewFile();
}
catch (IOException e)
{
throw new ParserException("Error while parsing the Airline: "+ e.getMessage());
}
return airline;
}
/**
* Check that the file exists
* @return
* true if exists, false otherwise
*/
private boolean checkFileExistence()
{
File f = new File(fileName);
if (f.exists())
return true;
else return false;
}
/**
* Create a new file with an Airline added
* @return
* an airline being added
* @throws IOException
* if IO error found
*/
private Airline createNewFile() throws IOException {
Writer writer = new BufferedWriter(new FileWriter(new File(fileName)));
writer.write(airlineToRead+"\n");
Airline airline = new Airline(airlineToRead);
writer.close();
return airline;
}
/**
* read the file with given name, create Airline object and add all of the
* Flight objects found in file
* @return
* Airline with flights from file
* @throws IOException
* IF anny IO/Parsing error found
*/
private Airline readFile() throws IOException {
Airline returnAirline = null;
boolean resultCheck;
//File f = new File("src\\main\\java\\edu\\pdx\\cs410J\\dmitriev\\"+fileName+".txt");
File f = new File(fileName);
if (!f.exists())
{
throw new IOException("File not found");
}
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = "";
String fileAirlineName = b.readLine();
if(!airlineToRead.equals(fileAirlineName))
{
b.close();
System.gc();
throw new IOException("The name of the airline you looking for does not match the airline found in the file");
}
Airline airline = new Airline(fileAirlineName);
while ((readLine = b.readLine()) != null) {
String[] split = readLine.split(";|\n");
resultCheck = checkFlightArguments(split);
if(!resultCheck)
{
b.close();
System.gc();
throw new IOException("Unable to parse one of the flights, malformated data");
}
Flight newFlight = new Flight(split[0], split[1], split[2], split[3], split[4], split[5], split[6], split[7], split[8]);
airline.addFlight(newFlight);
readLine = null;
}
b.close();
System.gc();
returnAirline = airline;
return returnAirline;
}
/**
* Use ArgumentChecker methods to make sure flights data is formatted correctly.
* Jsut as with program line arguments
* @param array
* a list of flight data
* @return
* true if passes. False if fails.
*/
private boolean checkFlightArguments(String[] array)
{
if (!ArgumentChecker.checkFlightNumber(array[0]) ||
!ArgumentChecker.checkSrc(array[1]) ||
!ArgumentChecker.checkDate(array[2]) ||
!ArgumentChecker.checkTime(array[3]) ||
!ArgumentChecker.check_am_pm(array[4]) ||
!ArgumentChecker.checkDest(array[5]) ||
!ArgumentChecker.checkDate(array[6]) ||
!ArgumentChecker.checkTime(array[7]) ||
!ArgumentChecker.check_am_pm(array[8]) ||
!ArgumentChecker.checkNoOtherArgs(array,0)) {
return false;
} else return true;
}
}
| apache-2.0 |
arquillian/arquillian-extension-persistence | int-tests/src/test/java/org/jboss/arquillian/integration/persistence/datasource/postgresql/PostgreSqlDataSourceExtension.java | 1398 | /*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.arquillian.integration.persistence.datasource.postgresql;
import org.jboss.arquillian.container.test.spi.client.deployment.AuxiliaryArchiveAppender;
import org.jboss.arquillian.core.spi.LoadableExtension;
public class PostgreSqlDataSourceExtension implements LoadableExtension {
@Override
public void register(ExtensionBuilder builder) {
builder.service(AuxiliaryArchiveAppender.class, PostgreSqlDataSourceArchiveCreator.class);
builder.service(AuxiliaryArchiveAppender.class, PostgreSqlDriverArchiveAppender.class);
}
}
| apache-2.0 |
kierarad/gocd | server/src/main/java/com/thoughtworks/go/server/newsecurity/controllers/AuthenticationController.java | 9321 | /*
* Copyright 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thoughtworks.go.server.newsecurity.controllers;
import com.thoughtworks.go.server.newsecurity.models.AccessToken;
import com.thoughtworks.go.server.newsecurity.models.AuthenticationToken;
import com.thoughtworks.go.server.newsecurity.models.UsernamePassword;
import com.thoughtworks.go.server.newsecurity.providers.PasswordBasedPluginAuthenticationProvider;
import com.thoughtworks.go.server.newsecurity.providers.WebBasedPluginAuthenticationProvider;
import com.thoughtworks.go.server.newsecurity.utils.SessionUtils;
import com.thoughtworks.go.server.service.SecurityService;
import com.thoughtworks.go.util.Clock;
import com.thoughtworks.go.util.SystemEnvironment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.view.RedirectView;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import static com.thoughtworks.go.server.newsecurity.utils.SessionUtils.isAnonymousAuthenticationToken;
@Controller
public class AuthenticationController {
public static final String BAD_CREDENTIALS_MSG = "Invalid credentials. Either your username and password are incorrect, or there is a problem with your browser cookies. Please check with your administrator.";
private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationController.class);
private static final RedirectView REDIRECT_TO_LOGIN_PAGE = new RedirectView("/auth/login", true);
private static final String UNKNOWN_ERROR_WHILE_AUTHENTICATION = "There was an unknown error authenticating you. Please try again after some time, and contact the administrator if the problem persists.";
private final SecurityService securityService;
private final SystemEnvironment systemEnvironment;
private final Clock clock;
private final PasswordBasedPluginAuthenticationProvider passwordBasedPluginAuthenticationProvider;
private final WebBasedPluginAuthenticationProvider webBasedPluginAuthenticationProvider;
@Autowired
public AuthenticationController(SecurityService securityService,
SystemEnvironment systemEnvironment,
Clock clock,
PasswordBasedPluginAuthenticationProvider passwordBasedPluginAuthenticationProvider,
WebBasedPluginAuthenticationProvider webBasedPluginAuthenticationProvider) {
this.securityService = securityService;
this.systemEnvironment = systemEnvironment;
this.clock = clock;
this.passwordBasedPluginAuthenticationProvider = passwordBasedPluginAuthenticationProvider;
this.webBasedPluginAuthenticationProvider = webBasedPluginAuthenticationProvider;
}
@RequestMapping(value = "/auth/security_check", method = RequestMethod.POST)
public RedirectView performLogin(@RequestParam("j_username") String username,
@RequestParam("j_password") String password,
HttpServletRequest request) {
if (securityIsDisabledOrAlreadyLoggedIn(request)) {
return new RedirectView("/pipelines", true);
}
LOGGER.debug("Requesting authentication for form auth.");
try {
SavedRequest savedRequest = SessionUtils.savedRequest(request);
final AuthenticationToken<UsernamePassword> authenticationToken = passwordBasedPluginAuthenticationProvider.authenticate(new UsernamePassword(username, password), null);
if (authenticationToken == null) {
return badAuthentication(request, BAD_CREDENTIALS_MSG);
} else {
SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request);
}
String redirectUrl = savedRequest == null ? "/go/pipelines" : savedRequest.getRedirectUrl();
return new RedirectView(redirectUrl, false);
} catch (AuthenticationException e) {
LOGGER.error("Failed to authenticate user: {} ", username, e);
return badAuthentication(request, e.getMessage());
} catch (Exception e) {
return unknownAuthenticationError(request);
}
}
@RequestMapping(value = "/plugin/{pluginId}/login", method = RequestMethod.GET)
public RedirectView redirectToThirdPartyLoginPage(@PathVariable("pluginId") String pluginId,
HttpServletRequest request) {
if (securityIsDisabledOrAlreadyLoggedIn(request)) {
return new RedirectView("/pipelines", true);
}
final StringBuffer requestURL = request.getRequestURL();
requestURL.setLength(requestURL.length() - request.getRequestURI().length());
return new RedirectView(webBasedPluginAuthenticationProvider.getAuthorizationServerUrl(pluginId, requestURL.toString()), false);
}
@RequestMapping(value = "/plugin/{pluginId}/authenticate")
public RedirectView authenticateWithWebBasedPlugin(@PathVariable("pluginId") String pluginId,
HttpServletRequest request) {
if (securityIsDisabledOrAlreadyLoggedIn(request)) {
return new RedirectView("/pipelines", true);
}
LOGGER.debug("Requesting authentication for form auth.");
SavedRequest savedRequest = SessionUtils.savedRequest(request);
try {
final AccessToken accessToken = webBasedPluginAuthenticationProvider.fetchAccessToken(pluginId, getRequestHeaders(request), getParameterMap(request));
AuthenticationToken<AccessToken> authenticationToken = webBasedPluginAuthenticationProvider.authenticate(accessToken, pluginId);
if (authenticationToken == null) {
return unknownAuthenticationError(request);
}
SessionUtils.setAuthenticationTokenAfterRecreatingSession(authenticationToken, request);
} catch (AuthenticationException e) {
LOGGER.error("Failed to authenticate user.", e);
return badAuthentication(request, e.getMessage());
} catch (Exception e) {
return unknownAuthenticationError(request);
}
SessionUtils.removeAuthenticationError(request);
String redirectUrl = savedRequest == null ? "/go/pipelines" : savedRequest.getRedirectUrl();
return new RedirectView(redirectUrl, false);
}
private boolean securityIsDisabledOrAlreadyLoggedIn(HttpServletRequest request) {
return !securityService.isSecurityEnabled() || (!isAnonymousAuthenticationToken(request) && SessionUtils.isAuthenticated(request, clock, systemEnvironment));
}
private RedirectView badAuthentication(HttpServletRequest request, String message) {
SessionUtils.setAuthenticationError(message, request);
return REDIRECT_TO_LOGIN_PAGE;
}
private RedirectView unknownAuthenticationError(HttpServletRequest request) {
return badAuthentication(request, UNKNOWN_ERROR_WHILE_AUTHENTICATION);
}
private HashMap<String, String> getRequestHeaders(HttpServletRequest request) {
HashMap<String, String> headers = new HashMap<>();
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String header = (String) headerNames.nextElement();
String value = request.getHeader(header);
headers.put(header, value);
}
return headers;
}
private Map<String, String> getParameterMap(HttpServletRequest request) {
Map<String, String[]> springParameterMap = request.getParameterMap();
Map<String, String> pluginParameterMap = new HashMap<>();
for (String parameterName : springParameterMap.keySet()) {
String[] values = springParameterMap.get(parameterName);
if (values != null && values.length > 0) {
pluginParameterMap.put(parameterName, values[0]);
} else {
pluginParameterMap.put(parameterName, null);
}
}
return pluginParameterMap;
}
}
| apache-2.0 |
krishanthasamaraweera/product-cep | modules/integration/tests-integration/tests/src/test/java/org/wso2/carbon/integration/test/processflow/PassThroughWithWso2Event.java | 7896 | /*
* Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.integration.test.processflow;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.event.stream.manager.stub.types.EventStreamAttributeDto;
import org.wso2.carbon.integration.common.utils.LoginLogoutClient;
import org.wso2.carbon.integration.test.client.StatPublisherAgent;
import org.wso2.carbon.integration.test.client.TestAgentServer;
import org.wso2.cep.integration.common.utils.CEPIntegrationTest;
import org.wso2.cep.integration.common.utils.ConfigurationUtil;
import java.rmi.RemoteException;
/**
* Sample 0001 - Simple Pass-through with WSO2Event
*/
public class PassThroughWithWso2Event extends CEPIntegrationTest {
private static final Log log = LogFactory.getLog(PassThroughWithWso2Event.class);
private static final String INPUT_STREAM_NAME = "org.wso2.sample.service.data";
private static final String OUTPUT_STREAM_NAME = "org.wso2.sample.service.response.time";
private static final String STREAM_VERSION = "1.0.0";
@BeforeClass(alwaysRun = true)
public void init() throws Exception {
super.init(TestUserMode.SUPER_TENANT_ADMIN);
String loggedInSessionCookie = new LoginLogoutClient(cepServer).login();
eventBuilderAdminServiceClient = configurationUtil.getEventBuilderAdminServiceClient(backendURL, loggedInSessionCookie);
eventFormatterAdminServiceClient = configurationUtil.getEventFormatterAdminServiceClient(backendURL, loggedInSessionCookie);
eventProcessorAdminServiceClient = configurationUtil.getEventProcessorAdminServiceClient(backendURL, loggedInSessionCookie);
inputEventAdaptorManagerAdminServiceClient = configurationUtil.getInputEventAdaptorManagerAdminServiceClient(backendURL, loggedInSessionCookie);
outputEventAdaptorManagerAdminServiceClient = configurationUtil.getOutputEventAdaptorManagerAdminServiceClient(backendURL, loggedInSessionCookie);
eventStreamManagerAdminServiceClient = configurationUtil.getEventStreamManagerAdminServiceClient(backendURL, loggedInSessionCookie);
}
@Test(groups = {"wso2.cep"}, description = "This is a test by Sajith")
public void sampleTest() throws Exception {
final int messageCount = 5;
// Adding input event adaptor
configurationUtil.addWso2EventInputEventAdaptor("WSO2EventAdaptor");
// Adding output wso2 event adaptor
configurationUtil.addThriftOutputEventAdaptor();
// Adding stream definition
addStreamDefinition(INPUT_STREAM_NAME, STREAM_VERSION, "Statistics", "Service Statistics", false);
addStreamDefinition(OUTPUT_STREAM_NAME, STREAM_VERSION, "Filtered Statistics", "Filtered Service Statistics", true);
// Adding event builder
String eventBuilderConfigPath = getTestArtifactLocation() + "/artifacts/CEP/ebconfigs/ServiceStats.xml";
String eventBuilderConfig = getArtifactConfigurationFromClasspath(eventBuilderConfigPath);
eventBuilderAdminServiceClient.addEventBuilderConfiguration(eventBuilderConfig);
// Adding event formatter
String eventFormatterConfigPath = getTestArtifactLocation() + "/artifacts/CEP/ebconfigs/StatResponseTime.xml";
String eventFormatterConfig = getArtifactConfigurationFromClasspath(eventFormatterConfigPath);
eventFormatterAdminServiceClient.addEventFormatterConfiguration(eventFormatterConfig);
// The data-bridge receiver
TestAgentServer agentServer = new TestAgentServer();
Thread agentServerThread = new Thread(agentServer);
agentServerThread.start();
// Let the server start
Thread.sleep(1000);
StatPublisherAgent.start(messageCount);
//wait while all stats are published
Thread.sleep(10000);
try {
Assert.assertEquals(agentServer.getMsgCount(), messageCount, "Incorrect number of messages consumed!");
eventFormatterAdminServiceClient.removeActiveEventFormatterConfiguration("StatsResponseTime");
eventBuilderAdminServiceClient.removeActiveEventBuilderConfiguration("ServiceStats");
inputEventAdaptorManagerAdminServiceClient.removeActiveInputEventAdaptorConfiguration("WSO2EventAdaptor");
configurationUtil.removeThriftOutputEventAdaptor();
Thread.sleep(2000);
} catch (Throwable e) {
log.error("Exception thrown: " + e.getMessage(), e);
Assert.fail("Exception: " + e.getMessage());
} finally {
agentServer.stop();
}
}
private void addStreamDefinition(String streamName, String version, String description, String nickName, boolean isOutput) throws RemoteException {
EventStreamAttributeDto[] metaData;
EventStreamAttributeDto[] payloadData;
final String metaPrefix = (isOutput) ? "meta_" : "";
EventStreamAttributeDto requestUrl = ConfigurationUtil.createEventStreamAttributeDto(metaPrefix + "request_url", "string");
EventStreamAttributeDto remoteAddress = ConfigurationUtil.createEventStreamAttributeDto(metaPrefix + "remote_address", "string");
EventStreamAttributeDto contentType = ConfigurationUtil.createEventStreamAttributeDto(metaPrefix + "content_type", "string");
EventStreamAttributeDto userAgent = ConfigurationUtil.createEventStreamAttributeDto(metaPrefix + "user_agent", "string");
EventStreamAttributeDto host = ConfigurationUtil.createEventStreamAttributeDto(metaPrefix + "host", "string");
EventStreamAttributeDto referer = ConfigurationUtil.createEventStreamAttributeDto(metaPrefix + "referer", "string");
metaData = new EventStreamAttributeDto[]{requestUrl, remoteAddress, contentType, userAgent, host, referer};
EventStreamAttributeDto serviceName = ConfigurationUtil.createEventStreamAttributeDto("service_name", "string");
EventStreamAttributeDto operationName = ConfigurationUtil.createEventStreamAttributeDto("operation_name", "string");
EventStreamAttributeDto timestamp = ConfigurationUtil.createEventStreamAttributeDto("timestamp", "long");
EventStreamAttributeDto responseTime = ConfigurationUtil.createEventStreamAttributeDto("response_time", "long");
EventStreamAttributeDto requestCount = ConfigurationUtil.createEventStreamAttributeDto("request_count", "int");
EventStreamAttributeDto responseCount = ConfigurationUtil.createEventStreamAttributeDto("response_count", "int");
EventStreamAttributeDto faultCount = ConfigurationUtil.createEventStreamAttributeDto("fault_count", "int");
payloadData = new EventStreamAttributeDto[]{serviceName, operationName, timestamp, responseTime, requestCount, responseCount, faultCount};
eventStreamManagerAdminServiceClient.addEventStream(streamName, version, metaData, null, payloadData, description, nickName);
}
@AfterClass(alwaysRun = true)
public void destroy() throws Exception {
super.cleanup();
}
}
| apache-2.0 |
LucidDB/luciddb | farrago/src/org/eigenbase/test/EigenbaseTestCase.java | 8833 | /*
// Licensed to DynamoBI Corporation (DynamoBI) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. DynamoBI 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.eigenbase.test;
import java.util.*;
import java.util.regex.*;
import junit.framework.*;
import org.eigenbase.runtime.*;
public abstract class EigenbaseTestCase
extends TestCase
{
//~ Static fields/initializers ---------------------------------------------
protected static final String nl = System.getProperty("line.separator");
protected static final String [] emptyStringArray = new String[0];
//~ Constructors -----------------------------------------------------------
protected EigenbaseTestCase(String s)
throws Exception
{
super(s);
}
//~ Methods ----------------------------------------------------------------
protected static void assertEqualsDeep(
Object o,
Object o2)
{
if ((o instanceof Object []) && (o2 instanceof Object [])) {
Object [] a = (Object []) o;
Object [] a2 = (Object []) o2;
assertEquals(a.length, a2.length);
for (int i = 0; i < a.length; i++) {
assertEqualsDeep(a[i], a2[i]);
}
return;
}
if ((o != null)
&& (o2 != null)
&& o.getClass().isArray()
&& (o.getClass() == o2.getClass()))
{
boolean eq;
if (o instanceof boolean []) {
eq = Arrays.equals((boolean []) o, (boolean []) o2);
} else if (o instanceof byte []) {
eq = Arrays.equals((byte []) o, (byte []) o2);
} else if (o instanceof char []) {
eq = Arrays.equals((char []) o, (char []) o2);
} else if (o instanceof short []) {
eq = Arrays.equals((short []) o, (short []) o2);
} else if (o instanceof int []) {
eq = Arrays.equals((int []) o, (int []) o2);
} else if (o instanceof long []) {
eq = Arrays.equals((long []) o, (long []) o2);
} else if (o instanceof float []) {
eq = Arrays.equals((float []) o, (float []) o2);
} else if (o instanceof double []) {
eq = Arrays.equals((double []) o, (double []) o2);
} else {
eq = false;
}
if (!eq) {
fail("arrays not equal");
}
} else {
// will handle the case 'o instanceof int[]' ok, because
// shallow comparison is ok for ints
assertEquals(o, o2);
}
}
/**
* Fails if <code>throwable</code> is null, or if its message does not
* contain the string <code>pattern</code>.
*/
protected void assertThrowableContains(
Throwable throwable,
String pattern)
{
if (throwable == null) {
fail(
"expected exception containing pattern <" + pattern
+ "> but got none");
}
String message = throwable.getMessage();
if ((message == null) || (message.indexOf(pattern) < 0)) {
fail(
"expected pattern <" + pattern + "> in exception <"
+ throwable + ">");
}
}
/**
* Returns an iterator over the elements of an array.
*/
public static Iterator makeIterator(Object [] a)
{
return Arrays.asList(a).iterator();
}
/**
* Returns a TupleIter over the elements of an array.
*/
public static TupleIter makeTupleIter(final Object [] a)
{
return new AbstractTupleIter() {
private List data = Arrays.asList(a);
private Iterator iter = data.iterator();
public Object fetchNext()
{
if (iter.hasNext()) {
return iter.next();
}
return NoDataReason.END_OF_DATA;
}
public void restart()
{
iter = data.iterator();
}
public void closeAllocation()
{
iter = null;
data = null;
}
};
}
/**
* Converts an iterator to a list.
*/
protected static List toList(Iterator iterator)
{
ArrayList list = new ArrayList();
while (iterator.hasNext()) {
list.add(iterator.next());
}
return list;
}
/**
* Converts a TupleIter to a list.
*/
protected static List toList(TupleIter tupleIter)
{
ArrayList list = new ArrayList();
while (true) {
Object o = tupleIter.fetchNext();
if (o == TupleIter.NoDataReason.END_OF_DATA) {
return list;
} else if (o == TupleIter.NoDataReason.UNDERFLOW) {
// Busy loops.
continue;
}
list.add(o);
}
}
/**
* Converts an enumeration to a list.
*/
protected static List toList(Enumeration enumeration)
{
ArrayList list = new ArrayList();
while (enumeration.hasMoreElements()) {
list.add(enumeration.nextElement());
}
return list;
}
/**
* Checks that an iterator returns the same objects as the contents of an
* array.
*/
protected void assertEquals(
Iterator iterator,
Object [] a)
{
ArrayList list = new ArrayList();
while (iterator.hasNext()) {
list.add(iterator.next());
}
assertEquals(list, a);
}
/**
* Checks that a TupleIter returns the same objects as the contents of an
* array.
*/
protected void assertEquals(
TupleIter iterator,
Object [] a)
{
ArrayList list = new ArrayList();
while (true) {
Object next = iterator.fetchNext();
if (next == TupleIter.NoDataReason.END_OF_DATA) {
break;
}
list.add(next);
}
assertEquals(list, a);
}
/**
* Checks that a list has the same contents as an array.
*/
protected void assertEquals(
List list,
Object [] a)
{
Object [] b = list.toArray();
assertEquals(a, b);
}
/**
* Checks that two arrays are equal.
*/
protected void assertEquals(
Object [] expected,
Object [] actual)
{
assertTrue(expected.length == actual.length);
for (int i = 0; i < expected.length; i++) {
assertEquals(expected[i], actual[i]);
}
}
protected void assertEquals(
Object [] expected,
Object actual)
{
if (actual instanceof Object []) {
assertEquals(expected, (Object []) actual);
} else {
// They're different. Let assertEquals(Object,Object) give the
// error.
assertEquals((Object) expected, actual);
}
}
/**
* Copies all of the tests in a suite whose names match a given pattern.
*/
public static TestSuite copySuite(
TestSuite suite,
Pattern testPattern)
{
TestSuite newSuite = new TestSuite();
Enumeration tests = suite.tests();
while (tests.hasMoreElements()) {
Test test = (Test) tests.nextElement();
if (test instanceof TestCase) {
TestCase testCase = (TestCase) test;
final String testName = testCase.getName();
if (testPattern.matcher(testName).matches()) {
newSuite.addTest(test);
}
} else if (test instanceof TestSuite) {
TestSuite subSuite = copySuite((TestSuite) test, testPattern);
if (subSuite.countTestCases() > 0) {
newSuite.addTest(subSuite);
}
} else {
// some other kind of test
newSuite.addTest(test);
}
}
return newSuite;
}
}
// End EigenbaseTestCase.java
| apache-2.0 |
apache/geronimo | plugins/pluto/geronimo-pluto/src/main/java/org/apache/geronimo/pluto/PortalStartupListener.java | 8945 | /*
* 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.geronimo.pluto;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.pluto.container.PortletContainer;
import org.apache.pluto.container.PortletContainerException;
import org.apache.pluto.driver.AttributeKeys;
import org.apache.pluto.driver.config.AdminConfiguration;
import org.apache.pluto.driver.config.DriverConfiguration;
import org.apache.pluto.driver.config.DriverConfigurationException;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Listener used to start up / shut down the Pluto Portal Driver upon startup /
* showdown of the servlet context in which it resides.
* <p/>
* Startup Includes:
* <ol>
* <li>Instantiation of the DriverConfiguration</li>
* <li>Registration of the DriverConfiguration</li>
* <li>Instantiation of the PortalContext</li>
* <li>Registration of the PortalContext</li>
* <li>Instantiation of the ContainerServices</li>
* <li>Registration of the ContainerServices</li>
* </ol>
*
* @version $Revision$ $Date$
* @since Sep 22, 2004
*/
public class PortalStartupListener implements ServletContextListener {
/**
* Internal logger.
*/
private static final Logger LOG = LoggerFactory.getLogger(
PortalStartupListener.class);
/**
* The KEY with which the container is bound to the context.
*/
private static final String CONTAINER_KEY = AttributeKeys.PORTLET_CONTAINER;
/**
* The KEY with which the driver configuration is bound to the context.
*/
private static final String DRIVER_CONFIG_KEY = AttributeKeys.DRIVER_CONFIG;
/**
* The KEY with which the admin configuration is bound to the context.
*/
private static final String ADMIN_CONFIG_KEY = AttributeKeys.DRIVER_ADMIN_CONFIG;
// ServletContextListener Impl ---------------------------------------------
/**
* Receives the startup notification and subsequently starts up the portal
* driver. The following are done in this order:
* <ol>
* <li>Retrieve the ResourceConfig File</li>
* <li>Parse the ResourceConfig File into ResourceConfig Objects</li>
* <li>Create a Portal Context</li>
* <li>Create the ContainerServices implementation</li>
* <li>Create the Portlet Container</li>
* <li>Initialize the Container</li>
* <li>Bind the configuration to the ServletContext</li>
* <li>Bind the container to the ServletContext</li>
* <ol>
*
* @param event the servlet context event.
*/
public void contextInitialized(ServletContextEvent event) {
LOG.info("Starting up Pluto Portal Driver. . .");
final ServletContext servletContext = event.getServletContext();
BundleContext bundleContext = (BundleContext) servletContext.getAttribute("osgi-bundlecontext");
LOG.debug(" [1a] Loading DriverConfiguration. . . ");
ServiceReference serviceReference = bundleContext.getServiceReference(DriverConfiguration.class.getName());
DriverConfiguration driverConfiguration = (DriverConfiguration) bundleContext.getService(serviceReference);
// driverConfiguration.init(new ResourceSource() {
// public InputStream getResourceAsStream(String resourceName) {
// return servletContext.getResourceAsStream(resourceName);
// }
// });
LOG.debug(" [1b] Registering DriverConfiguration. . .");
servletContext.setAttribute(DRIVER_CONFIG_KEY, driverConfiguration);
LOG.debug(" [2a] Loading Optional AdminConfiguration. . .");
serviceReference = bundleContext.getServiceReference(AdminConfiguration.class.getName());
AdminConfiguration adminConfiguration = (AdminConfiguration) bundleContext.getService(serviceReference);
if (adminConfiguration != null) {
LOG.debug(" [2b] Registering Optional AdminConfiguration");
servletContext.setAttribute(ADMIN_CONFIG_KEY, adminConfiguration);
} else {
LOG.info("Optional AdminConfiguration not found. Ignoring.");
}
// Retrieve the driver configuration from servlet context.
DriverConfiguration driverConfig = (DriverConfiguration)
servletContext.getAttribute(DRIVER_CONFIG_KEY);
LOG.info("Initializing Portlet Container. . .");
// Create portlet container.
LOG.debug(" [1] Creating portlet container...");
serviceReference = bundleContext.getServiceReference(PortletContainer.class.getName());
PortletContainer container = (PortletContainer) bundleContext.getService(serviceReference);
// Save portlet container to the servlet context scope.
servletContext.setAttribute(CONTAINER_KEY, container);
LOG.info("Pluto portlet container started.");
LOG.info("********** Pluto Portal Driver Started **********\n\n");
}
/**
* Receive notification that the context is being shut down and subsequently
* destroy the container.
*
* @param event the destrubtion event.
*/
public void contextDestroyed(ServletContextEvent event) {
ServletContext servletContext = event.getServletContext();
if (LOG.isInfoEnabled()) {
LOG.info("Shutting down Pluto Portal Driver...");
}
destroyContainer(servletContext);
destroyAdminConfiguration(servletContext);
destroyDriverConfiguration(servletContext);
if (LOG.isInfoEnabled()) {
LOG.info("********** Pluto Portal Driver Shut Down **********\n\n");
}
}
// Private Destruction Methods ---------------------------------------------
/**
* Destroyes the portlet container and removes it from servlet context.
*
* @param servletContext the servlet context.
*/
private void destroyContainer(ServletContext servletContext) {
if (LOG.isInfoEnabled()) {
LOG.info("Shutting down Pluto Portal Driver...");
}
PortletContainer container = (PortletContainer)
servletContext.getAttribute(CONTAINER_KEY);
if (container != null) {
servletContext.removeAttribute(CONTAINER_KEY);
}
}
/**
* Destroyes the portal driver config and removes it from servlet context.
*
* @param servletContext the servlet context.
*/
private void destroyDriverConfiguration(ServletContext servletContext) {
DriverConfiguration driverConfig = (DriverConfiguration)
servletContext.getAttribute(DRIVER_CONFIG_KEY);
if (driverConfig != null) {
// try {
// driverConfig.destroy();
// if (LOG.isInfoEnabled()) {
// LOG.info("Pluto Portal Driver Config destroyed.");
// }
// } catch (DriverConfigurationException ex) {
// LOG.error("Unable to destroy portal driver config: "
// + ex.getMessage(), ex);
// } finally {
servletContext.removeAttribute(DRIVER_CONFIG_KEY);
// }
}
}
/**
* Destroyes the portal admin config and removes it from servlet context.
*
* @param servletContext the servlet context.
*/
private void destroyAdminConfiguration(ServletContext servletContext) {
AdminConfiguration adminConfig = (AdminConfiguration)
servletContext.getAttribute(ADMIN_CONFIG_KEY);
if (adminConfig != null) {
// try {
// adminConfig.destroy();
// if (LOG.isInfoEnabled()) {
// LOG.info("Pluto Portal Admin Config destroyed.");
// }
// } catch (DriverConfigurationException ex) {
// LOG.error("Unable to destroy portal admin config: "
// + ex.getMessage(), ex);
// } finally {
servletContext.removeAttribute(ADMIN_CONFIG_KEY);
// }
}
}
}
| apache-2.0 |
wso2/carbon-metrics | components/org.wso2.carbon.metrics.core/src/test/java/org/wso2/carbon/metrics/core/MetricsMXBeanTest.java | 6480 | /*
* Copyright 2016 WSO2 Inc. (http://wso2.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.metrics.core;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.wso2.carbon.metrics.core.config.model.CsvReporterConfig;
import org.wso2.carbon.metrics.core.jmx.MetricsMXBean;
import org.wso2.carbon.metrics.core.reporter.ReporterBuildException;
import org.wso2.carbon.metrics.core.utils.Utils;
import java.io.File;
import javax.management.JMX;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
/**
* Test cases for {@link MetricsMXBean}.
*/
public class MetricsMXBeanTest extends BaseReporterTest {
private static final Logger logger = LoggerFactory.getLogger(MetricManagementServiceTest.class);
private static final String MBEAN_NAME = "org.wso2.carbon:type=MetricsTest";
private MetricsMXBean metricsMXBean;
@BeforeClass
private void createMXBeanProxy() {
ObjectName n;
try {
n = new ObjectName(MBEAN_NAME);
metricsMXBean = JMX.newMXBeanProxy(mBeanServer, n, MetricsMXBean.class);
} catch (MalformedObjectNameException e) {
Assert.fail(e.getMessage());
}
}
@BeforeMethod
private void setRootLevel() {
if (logger.isInfoEnabled()) {
logger.info("Resetting Root Level to {}", Level.INFO);
}
metricsMXBean.setRootLevel(Level.INFO.name());
}
@Test
public void testEnableDisable() {
Assert.assertTrue(metricsMXBean.isEnabled(), "Metric Service should be enabled");
Meter meter = metricService.meter(MetricService.name(this.getClass(), "test-enabled"), Level.INFO);
meter.mark();
Assert.assertEquals(meter.getCount(), 1);
metricsMXBean.disable();
Assert.assertFalse(metricsMXBean.isEnabled(), "Metric Service should be disabled");
meter.mark();
Assert.assertEquals(meter.getCount(), 1);
metricsMXBean.enable();
meter.mark();
Assert.assertEquals(meter.getCount(), 2);
}
@Test
public void testMetricSetLevel() {
String name = MetricService.name(this.getClass(), "test-metric-level");
Meter meter = metricService.meter(name, Level.INFO);
Assert.assertNull(metricsMXBean.getMetricLevel(name), "There should be no configured level");
meter.mark();
Assert.assertEquals(meter.getCount(), 1);
metricsMXBean.setMetricLevel(name, Level.INFO.name());
Assert.assertEquals(metricsMXBean.getMetricLevel(name), Level.INFO.name(), "Configured level should be INFO");
meter.mark();
Assert.assertEquals(meter.getCount(), 2);
metricsMXBean.setMetricLevel(name, Level.OFF.name());
Assert.assertEquals(metricsMXBean.getMetricLevel(name), Level.OFF.name(), "Configured level should be OFF");
meter.mark();
Assert.assertEquals(meter.getCount(), 2);
}
@Test
public void testMetricServiceLevels() {
Meter meter = metricService.meter(MetricService.name(this.getClass(), "test-levels"), Level.INFO);
meter.mark();
Assert.assertEquals(meter.getCount(), 1);
metricsMXBean.setRootLevel(Level.TRACE.name());
Assert.assertEquals(metricsMXBean.getRootLevel(), Level.TRACE.name());
meter.mark();
Assert.assertEquals(meter.getCount(), 2);
metricsMXBean.setRootLevel(Level.OFF.name());
Assert.assertEquals(metricsMXBean.getRootLevel(), Level.OFF.name());
meter.mark();
Assert.assertEquals(meter.getCount(), 2);
}
@Test
public void testMetricsCount() {
Assert.assertTrue(metricsMXBean.getMetricsCount() > 0);
Assert.assertTrue(metricsMXBean.getEnabledMetricsCount() > 0);
Assert.assertTrue(metricsMXBean.getEnabledMetricsCount() <= metricsMXBean.getMetricsCount());
Assert.assertTrue(metricsMXBean.getMetricCollectionsCount() >= 0);
}
@Test
public void testDefaultSource() {
Assert.assertEquals(metricsMXBean.getDefaultSource(), Utils.getDefaultSource());
}
@Test
public void testReporterJMXOperations() throws ReporterBuildException {
CsvReporterConfig csvReporterConfig = new CsvReporterConfig();
csvReporterConfig.setName("CSV");
csvReporterConfig.setEnabled(true);
csvReporterConfig.setLocation("target/metrics");
csvReporterConfig.setPollingPeriod(600);
metricManagementService.addReporter(csvReporterConfig);
// Test start/stop reporters
metricsMXBean.startReporters();
Assert.assertTrue(metricsMXBean.isReporterRunning("CSV"));
metricsMXBean.stopReporters();
Assert.assertFalse(metricsMXBean.isReporterRunning("CSV"));
metricsMXBean.startReporter("CSV");
Assert.assertTrue(metricsMXBean.isReporterRunning("CSV"));
String meterName1 = MetricService.name(this.getClass(), "test-jmx-report-meter1");
Meter meter1 = metricService.meter(meterName1, Level.INFO);
meter1.mark();
Assert.assertEquals(meter1.getCount(), 1);
metricsMXBean.report("CSV");
Assert.assertTrue(new File("target/metrics", meterName1 + ".csv").exists(), "Meter CSV file should be created");
String meterName2 = MetricService.name(this.getClass(), "test-jmx-report-meter2");
Meter meter2 = metricService.meter(meterName2, Level.INFO);
meter2.mark();
Assert.assertEquals(meter2.getCount(), 1);
metricsMXBean.report();
Assert.assertTrue(new File("target/metrics", meterName2 + ".csv").exists(), "Meter CSV file should be created");
metricsMXBean.stopReporter("CSV");
Assert.assertFalse(metricsMXBean.isReporterRunning("CSV"));
}
}
| apache-2.0 |
WebbWangPrivate/JavaSystem | FundSystem/src/com/fjnu/fund/domain/Fund.java | 1040 | /**
*
*/
package com.fjnu.fund.domain;
/**
* @author Administrator
*
*/
public class Fund {
private Integer fundNo;
private String fundName;
private Float fundPrice;
private String fundDes;
private String fundStatus;
private String fundDate;
public Integer getFundNo() {
return fundNo;
}
public void setFundNo(Integer fundNo) {
this.fundNo = fundNo;
}
public String getFundName() {
return fundName;
}
public void setFundName(String fundName) {
this.fundName = fundName;
}
public Float getFundPrice() {
return fundPrice;
}
public void setFundPrice(Float fundPrice) {
this.fundPrice = fundPrice;
}
public String getFundDes() {
return fundDes;
}
public void setFundDes(String fundDes) {
this.fundDes = fundDes;
}
public String getFundDate() {
return fundDate;
}
public void setFundDate(String fundDate) {
this.fundDate = fundDate;
}
public String getFundStatus() {
return fundStatus;
}
public void setFundStatus(String fundStatus) {
this.fundStatus = fundStatus;
}
}
| apache-2.0 |
GenericBreakGlass/GenericBreakGlass-XACML | src/eu.aniketos.securebpmn.xacml.support/src/main/java/eu/aniketos/securebpmn/xacml/support/AttributeResolver.java | 3664 | /* Copyright 2012-2015 SAP SE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package eu.aniketos.securebpmn.xacml.support;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
import org.apache.log4j.Logger;
import eu.aniketos.securebpmn.xacml.support.finder.IPDPStateEvaluationContext;
import com.sun.xacml.Constants;
import com.sun.xacml.EvaluationCtx;
import com.sun.xacml.attr.AttributeValue;
import com.sun.xacml.attr.BagAttribute;
import com.sun.xacml.attr.IntegerAttribute;
import com.sun.xacml.attr.StringAttribute;
import com.sun.xacml.attr.TypeIdentifierConstants;
import com.sun.xacml.cond.EvaluationResult;
public class AttributeResolver {
private static final Logger logger = Logger.getLogger(AttributeResolver.class);
public static long getPDPStatePolicyVersion(EvaluationCtx ctx) {
EvaluationResult evalResult = ctx.getAttribute(IPDPStateEvaluationContext.PDPSTATE_CATEGORY,
IPDPStateEvaluationContext.PDPSTATE_ATTRIBUTETYPE,
IPDPStateEvaluationContext.PDPSTATE_URI,
IPDPStateEvaluationContext.PDPSTATE_ISSUER);
if ( ((BagAttribute) evalResult.getAttributeValue()).size() > 1 ) {
logger.error("Did not retreive a bag with one (" +((BagAttribute) evalResult.getAttributeValue()).size() +
") entry after attribute search for current svn policy version number; " +
"PDP Dtate requires exactly one attribute to be defined");
return -1;
} else if ( ((BagAttribute) evalResult.getAttributeValue()).size() == 1 ) {
IntegerAttribute attrVal = (IntegerAttribute) ((BagAttribute) evalResult.getAttributeValue()).iterator().next();
if ( logger.isDebugEnabled() && ctx instanceof EvaluationIdContext)
logger.debug("Request " + ((EvaluationIdContext) ctx).getCurrentEvaluationId() + " is executed under policy " + attrVal.getValue());
return attrVal.getValue();
} else {
logger.debug("Could not resolve current policy version");
return -1;
}
}
public static final URI ACTIVEPOLICY_CATEGORY = Constants.ENVIRONMENT_CAT;
public static final URI ACTIVEPOLICY_ATTRIBUTETYPE = TypeIdentifierConstants.STRING_URI;
public static final String ACTIVEPOLICY = "urn:activePolicies";
public static final URI ACTIVEPOLICY_URI = URI.create(ACTIVEPOLICY);
public static final URI ACTIVEPOLICY_ISSUER = null;
public static Set<String> getActivePolicies(EvaluationCtx ctx) {
EvaluationResult evalResult = ctx.getAttribute(ACTIVEPOLICY_CATEGORY,
ACTIVEPOLICY_ATTRIBUTETYPE,
ACTIVEPOLICY_URI,
ACTIVEPOLICY_ISSUER);
Set<String> policies = new HashSet<String>();
for (AttributeValue value : ((BagAttribute) evalResult.getAttributeValue()).iterable()) {
policies.add( ((StringAttribute)value).getValue());
}
return policies;
}
}
| apache-2.0 |
dinkelaker/hbs4ode | bpel-runtime/src/main/java/org/apache/ode/bpel/memdao/BpelDAOConnectionImpl.java | 14032 | /*
* 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.ode.bpel.memdao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ode.bpel.common.BpelEventFilter;
import org.apache.ode.bpel.common.Filter;
import org.apache.ode.bpel.common.InstanceFilter;
import org.apache.ode.bpel.common.ProcessFilter;
import org.apache.ode.bpel.dao.BpelDAOConnection;
import org.apache.ode.bpel.dao.MessageExchangeDAO;
import org.apache.ode.bpel.dao.ProcessDAO;
import org.apache.ode.bpel.dao.ProcessInstanceDAO;
import org.apache.ode.bpel.dao.ScopeDAO;
import org.apache.ode.bpel.evt.BpelEvent;
import org.apache.ode.bpel.iapi.Scheduler;
import org.apache.ode.utils.ISO8601DateParser;
import org.apache.ode.utils.stl.CollectionsX;
import org.apache.ode.utils.stl.UnaryFunction;
import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.ConcurrentHashMap;
/**
* A very simple, in-memory implementation of the {@link BpelDAOConnection} interface.
*/
class BpelDAOConnectionImpl implements BpelDAOConnection {
private static final Log __log = LogFactory.getLog(BpelDAOConnectionImpl.class);
private Scheduler _scheduler;
private Map<QName, ProcessDaoImpl> _store;
private List<BpelEvent> _events = new LinkedList<BpelEvent>();
long _mexTtl;
private static Map<String,MessageExchangeDAO> _mexStore = Collections.synchronizedMap(new HashMap<String,MessageExchangeDAO>());
protected static Map<String, Long> _mexAge = new ConcurrentHashMap<String, Long>();
private static AtomicLong counter = new AtomicLong(Long.MAX_VALUE / 2);
private static volatile long _lastRemoval = 0;
BpelDAOConnectionImpl(Map<QName, ProcessDaoImpl> store, Scheduler scheduler, long mexTtl) {
_store = store;
_scheduler = scheduler;
_mexTtl = mexTtl;
}
public ProcessDAO getProcess(QName processId) {
return _store.get(processId);
}
public ProcessDAO createProcess(QName pid, QName type, String guid, long version) {
ProcessDaoImpl process = new ProcessDaoImpl(this,_store,pid,type, guid,version);
_store.put(pid,process);
return process;
}
public ProcessInstanceDAO getInstance(Long iid) {
for (ProcessDaoImpl proc : _store.values()) {
ProcessInstanceDAO instance = proc._instances.get(iid);
if (instance != null)
return instance;
}
return null;
}
public Collection<ProcessInstanceDAO> instanceQuery(InstanceFilter filter) {
if(filter.getLimit()==0) {
return Collections.EMPTY_LIST;
}
List<ProcessInstanceDAO> matched = new ArrayList<ProcessInstanceDAO>();
// Selecting
selectionCompleted:
for (ProcessDaoImpl proc : _store.values()) {
boolean pmatch = true;
if (filter.getNameFilter() != null
&& !equalsOrWildcardMatch(filter.getNameFilter(), proc.getProcessId().getLocalPart()))
pmatch = false;
if (filter.getNamespaceFilter() != null
&& !equalsOrWildcardMatch(filter.getNamespaceFilter(), proc.getProcessId().getNamespaceURI()))
pmatch = false;
if (pmatch) {
for (ProcessInstanceDAO inst : proc._instances.values()) {
boolean match = true;
if (filter.getStatusFilter() != null) {
boolean statusMatch = false;
for (Short status : filter.convertFilterState()) {
if (inst.getState() == status.byteValue()) statusMatch = true;
}
if (!statusMatch) match = false;
}
if (filter.getStartedDateFilter() != null
&& !dateMatch(filter.getStartedDateFilter(), inst.getCreateTime(), filter))
match = false;
if (filter.getLastActiveDateFilter() != null
&& !dateMatch(filter.getLastActiveDateFilter(), inst.getLastActiveTime(), filter))
match = false;
// if (filter.getPropertyValuesFilter() != null) {
// for (Map.Entry propEntry : filter.getPropertyValuesFilter().entrySet()) {
// boolean entryMatched = false;
// for (ProcessPropertyDAO prop : proc.getProperties()) {
// if (prop.getName().equals(propEntry.getKey())
// && (propEntry.getValue().equals(prop.getMixedContent())
// || propEntry.getValue().equals(prop.getSimpleContent()))) {
// entryMatched = true;
// }
// }
// if (!entryMatched) {
// match = false;
// }
// }
// }
if (match) {
matched.add(inst);
if(matched.size()==filter.getLimit()) {
break selectionCompleted;
}
}
}
}
}
// And ordering
if (filter.getOrders() != null) {
final List<String> orders = filter.getOrders();
Collections.sort(matched, new Comparator<ProcessInstanceDAO>() {
public int compare(ProcessInstanceDAO o1, ProcessInstanceDAO o2) {
for (String orderKey: orders) {
int result = compareInstanceUsingKey(orderKey, o1, o2);
if (result != 0) return result;
}
return 0;
}
});
}
return matched;
}
/**
* Close this DAO connection.
*/
public void close() {
}
public Collection<ProcessDAO> processQuery(ProcessFilter filter) {
throw new UnsupportedOperationException("Can't query process configuration using a transient DAO.");
}
public MessageExchangeDAO createMessageExchange(char dir) {
final String id = Long.toString(counter.getAndIncrement());
MessageExchangeDAO mex = new MessageExchangeDAOImpl(dir,id);
long now = System.currentTimeMillis();
_mexStore.put(id,mex);
_mexAge.put(id, now);
if (now > _lastRemoval + (_mexTtl / 10)) {
_lastRemoval = now;
Object[] oldMexs = _mexAge.keySet().toArray();
for (int i=oldMexs.length-1; i>0; i--) {
String oldMex = (String) oldMexs[i];
Long age = _mexAge.get(oldMex);
if (age != null && now-age > _mexTtl) {
removeMessageExchange(oldMex);
_mexAge.remove(oldMex);
}
}
}
// Removing right away on rollback
onRollback(new Runnable() {
public void run() {
removeMessageExchange(id);
_mexAge.remove(id);
}
});
return mex;
}
public MessageExchangeDAO getMessageExchange(String mexid) {
return _mexStore.get(mexid);
}
private int compareInstanceUsingKey(String key, ProcessInstanceDAO instanceDAO1, ProcessInstanceDAO instanceDAO2) {
String s1 = null;
String s2 = null;
boolean ascending = true;
String orderKey = key;
if (key.startsWith("+") || key.startsWith("-")) {
orderKey = key.substring(1, key.length());
if (key.startsWith("-")) ascending = false;
}
ProcessDAO process1 = getProcess(instanceDAO1.getProcess().getProcessId());
ProcessDAO process2 = getProcess(instanceDAO2.getProcess().getProcessId());
if ("pid".equals(orderKey)) {
s1 = process1.getProcessId().toString();
s2 = process2.getProcessId().toString();
} else if ("name".equals(orderKey)) {
s1 = process1.getProcessId().getLocalPart();
s2 = process2.getProcessId().getLocalPart();
} else if ("namespace".equals(orderKey)) {
s1 = process1.getProcessId().getNamespaceURI();
s2 = process2.getProcessId().getNamespaceURI();
} else if ("version".equals(orderKey)) {
s1 = ""+process1.getVersion();
s2 = ""+process2.getVersion();
} else if ("status".equals(orderKey)) {
s1 = ""+instanceDAO1.getState();
s2 = ""+instanceDAO2.getState();
} else if ("started".equals(orderKey)) {
s1 = ISO8601DateParser.format(instanceDAO1.getCreateTime());
s2 = ISO8601DateParser.format(instanceDAO2.getCreateTime());
} else if ("last-active".equals(orderKey)) {
s1 = ISO8601DateParser.format(instanceDAO1.getLastActiveTime());
s2 = ISO8601DateParser.format(instanceDAO2.getLastActiveTime());
}
if (ascending) return s1.compareTo(s2);
else return s2.compareTo(s1);
}
private boolean equalsOrWildcardMatch(String s1, String s2) {
if (s1 == null || s2 == null) return false;
if (s1.equals(s2)) return true;
if (s1.endsWith("*")) {
if (s2.startsWith(s1.substring(0, s1.length() - 1))) return true;
}
if (s2.endsWith("*")) {
if (s1.startsWith(s2.substring(0, s2.length() - 1))) return true;
}
return false;
}
public boolean dateMatch(List<String> dateFilters, Date instanceDate, InstanceFilter filter) {
boolean match = true;
for (String ddf : dateFilters) {
String isoDate = ISO8601DateParser.format(instanceDate);
String critDate = Filter.getDateWithoutOp(ddf);
if (ddf.startsWith("=")) {
if (!isoDate.startsWith(critDate)) match = false;
} else if (ddf.startsWith("<=")) {
if (!isoDate.startsWith(critDate) && isoDate.compareTo(critDate) > 0) match = false;
} else if (ddf.startsWith(">=")) {
if (!isoDate.startsWith(critDate) && isoDate.compareTo(critDate) < 0) match = false;
} else if (ddf.startsWith("<")) {
if (isoDate.compareTo(critDate) > 0) match = false;
} else if (ddf.startsWith(">")) {
if (isoDate.compareTo(critDate) < 0) match = false;
}
}
return match;
}
public ScopeDAO getScope(Long siidl) {
for (ProcessDaoImpl process : _store.values()) {
for (ProcessInstanceDAO instance : process._instances.values()) {
if (instance.getScope(siidl) != null) return instance.getScope(siidl);
}
}
return null;
}
public void insertBpelEvent(BpelEvent event, ProcessDAO processConfiguration, ProcessInstanceDAO instance) {
_events.add(event);
}
public List<Date> bpelEventTimelineQuery(InstanceFilter ifilter, BpelEventFilter efilter) {
// TODO : Provide more correct implementation:
ArrayList<Date> dates = new ArrayList<Date>();
CollectionsX.transform(dates, _events, new UnaryFunction<BpelEvent,Date>() {
public Date apply(BpelEvent x) {
return x.getTimestamp();
}
});
return dates;
}
public List<BpelEvent> bpelEventQuery(InstanceFilter ifilter, BpelEventFilter efilter) {
// TODO : Provide a more correct (filtering) implementation:
return _events;
}
/**
* @see org.apache.ode.bpel.dao.BpelDAOConnection#instanceQuery(String)
*/
public Collection<ProcessInstanceDAO> instanceQuery(String expression) {
//TODO
throw new UnsupportedOperationException();
}
static void removeMessageExchange(String mexId) {
// Cleaning up mex
if (__log.isDebugEnabled()) __log.debug("Removing mex " + mexId + " from memory store.");
MessageExchangeDAO mex = _mexStore.remove(mexId);
if (mex == null)
__log.warn("Couldn't find mex " + mexId + " for cleanup.");
_mexAge.remove(mexId);
}
public void defer(final Runnable runnable) {
_scheduler.registerSynchronizer(new Scheduler.Synchronizer() {
public void afterCompletion(boolean success) {
}
public void beforeCompletion() {
runnable.run();
}
});
}
public void onRollback(final Runnable runnable) {
_scheduler.registerSynchronizer(new Scheduler.Synchronizer() {
public void afterCompletion(boolean success) {
if (!success) runnable.run();
}
public void beforeCompletion() {
}
});
}
}
| apache-2.0 |
dinkelaker/hbs4ode | dao-hibernate/src/main/java/org/apache/ode/daohib/bpel/XmlDataDaoImpl.java | 5098 | /*
* 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.ode.daohib.bpel;
import org.apache.ode.bpel.dao.ScopeDAO;
import org.apache.ode.bpel.dao.XmlDataDAO;
import org.apache.ode.daohib.SessionManager;
import org.apache.ode.daohib.bpel.hobj.HLargeData;
import org.apache.ode.daohib.bpel.hobj.HVariableProperty;
import org.apache.ode.daohib.bpel.hobj.HXmlData;
import org.apache.ode.utils.DOMUtils;
import java.util.Iterator;
import org.hibernate.Query;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
/**
* Hibernate-based {@link XmlDataDAO} implementation.
*/
class XmlDataDaoImpl extends HibernateDao implements XmlDataDAO {
private static final String QUERY_PROPERTY =
"from " + HVariableProperty.class.getName() +
" as p where p.xmlData.id = ? and p.name = ?";
private HXmlData _data;
private Node _node;
/**
* @param hobj
*/
public XmlDataDaoImpl(SessionManager sm, HXmlData hobj) {
super(sm, hobj);
_data = hobj;
}
/**
* @see org.apache.ode.bpel.dao.XmlDataDAO#isNull()
*/
public boolean isNull() {
return _data.getData() == null;
}
/**
* @see org.apache.ode.bpel.dao.XmlDataDAO#get()
*/
public Node get() {
if(_node == null){
_node = prepare();
}
return _node;
}
/**
* @see org.apache.ode.bpel.dao.XmlDataDAO#remove()
*/
public void remove() {
}
/**
* @see org.apache.ode.bpel.dao.XmlDataDAO#set(org.w3c.dom.Node)
*/
public void set(Node val) {
_node = val;
_data.setSimpleType(!(val instanceof Element));
if (_data.getData() != null) _sm.getSession().delete(_data.getData());
HLargeData ld = new HLargeData();
if(_data.isSimpleType()) {
ld.setBinary(_node.getNodeValue().getBytes());
_data.setData(ld);
} else {
ld.setBinary(DOMUtils.domToString(_node).getBytes());
_data.setData(ld);
}
getSession().save(ld);
getSession().saveOrUpdate(_data);
}
/**
* @see org.apache.ode.bpel.dao.XmlDataDAO#getProperty(java.lang.String)
*/
public String getProperty(String propertyName) {
HVariableProperty p = _getProperty(propertyName);
return p == null
? null
: p.getValue();
}
/**
* @see org.apache.ode.bpel.dao.XmlDataDAO#setProperty(java.lang.String, java.lang.String)
*/
public void setProperty(String pname, String pvalue) {
HVariableProperty p = _getProperty(pname);
if(p == null){
p = new HVariableProperty(_data, pname, pvalue);
getSession().save(p);
// _data.addProperty(p);
}else{
p.setValue(pvalue);
getSession().update(p);
}
}
/**
* @see org.apache.ode.bpel.dao.XmlDataDAO#getScopeDAO()
*/
public ScopeDAO getScopeDAO() {
return new ScopeDaoImpl(_sm,_data.getScope());
}
private HVariableProperty _getProperty(String propertyName){
Iterator iter;
Query qry = getSession().createQuery(QUERY_PROPERTY);
qry.setLong(0, _data.getId());
qry.setString(1, propertyName);
iter = qry.iterate();
return iter.hasNext()
? (HVariableProperty)iter.next()
: null;
}
private Node prepare(){
if(_data.getData() == null)
return null;
String data = _data.getData().getText();
if(_data.isSimpleType()){
Document d = DOMUtils.newDocument();
// we create a dummy wrapper element
// prevents some apps from complaining
// when text node is not actual child of document
Element e = d.createElement("text-node-wrapper");
Text tnode = d.createTextNode(data);
d.appendChild(e);
e.appendChild(tnode);
return tnode;
}else{
try{
return DOMUtils.stringToDOM(data);
}catch(Exception e){
throw new RuntimeException(e);
}
}
}
public String getName() {
return _data.getName();
}
}
| apache-2.0 |
Vedenin/java_in_examples | other/src/main/java/com/github/vedenin/rus/arrays/ConvertArrayToStringAndPrintTest.java | 1973 | package com.github.vedenin.rus.arrays;
import java.util.Arrays;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
/**
* Тестирование превращения массива в строку для печати
*
* Created by vedenin on 04.02.16.
*/
public class ConvertArrayToStringAndPrintTest {
public static void main(String[] s) throws Exception {
/* (JDK 5) Использование Arrays.toString и Arrays.deepToString */
// simple array
String[] array = new String[]{"John", "Mary", "Bob"};
System.out.println(Arrays.toString(array)); // Напечатает: [John, Mary, Bob]
// nested array
String[][] deepArray = new String[][]{{"John", "Mary"}, {"Alice", "Bob"}};
System.out.println(Arrays.toString(deepArray)); // Напечатает: [[Ljava.lang.String;@106d69c, [Ljava.lang.String;@52e922]
System.out.println(Arrays.deepToString(deepArray)); // Напечатает: [[John, Mary], [Alice, Bob]]
//double Array
double[] arrayGiven = {7.0, 9.0, 5.0, 1.0, 3.0};
System.out.println(Arrays.toString(arrayGiven)); // Напечатает: [7.0, 9.0, 5.0, 1.0, 3.0 ]
//int Array
int[] arrayInt = {7, 9, 5, 1, 3};
System.out.println(Arrays.toString(arrayInt)); // Напечатает: [7, 9, 5, 1, 3 ]
/* (JDK 8) Использование Stream API */
Arrays.asList(array).stream().forEach(System.out::print); // Напечатает: JohnMaryBob
System.out.println();
Arrays.asList(deepArray).stream().forEach(s1 -> Arrays.asList(s1).stream().forEach(System.out::print));
System.out.println();
DoubleStream.of(arrayGiven).forEach((d) -> System.out.print(d + " ")); // Напечатает: 7.0 9.0 5.0 1.0 3.0
System.out.println();
IntStream.of(arrayInt).forEach(System.out::print); // Напечатает: 79513
}
}
| apache-2.0 |
Fabryprog/camel | core/camel-core/src/test/java/org/apache/camel/language/TokenizerTest.java | 18428 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.language;
import java.util.List;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangeTestSupport;
import org.apache.camel.Expression;
import org.apache.camel.language.tokenizer.TokenizeLanguage;
import org.apache.camel.model.language.TokenizerExpression;
import org.junit.Test;
public class TokenizerTest extends ExchangeTestSupport {
@Override
protected void populateExchange(Exchange exchange) {
super.populateExchange(exchange);
exchange.getIn().setHeader("names", "Claus,James,Willem");
}
@Test
public void testTokenizeHeaderWithStringContructor() throws Exception {
TokenizerExpression definition = new TokenizerExpression(",");
definition.setHeaderName("names");
List<?> names = definition.createExpression(exchange.getContext()).evaluate(exchange, List.class);
assertEquals(3, names.size());
assertEquals("Claus", names.get(0));
assertEquals("James", names.get(1));
assertEquals("Willem", names.get(2));
}
@Test
public void testTokenizeHeader() throws Exception {
Expression exp = TokenizeLanguage.tokenize("names", ",");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(3, names.size());
assertEquals("Claus", names.get(0));
assertEquals("James", names.get(1));
assertEquals("Willem", names.get(2));
}
@Test
public void testTokenizeBody() throws Exception {
Expression exp = TokenizeLanguage.tokenize(",");
exchange.getIn().setBody("Hadrian,Charles");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(2, names.size());
assertEquals("Hadrian", names.get(0));
assertEquals("Charles", names.get(1));
}
@Test
public void testTokenizeBodyRegEx() throws Exception {
Expression exp = TokenizeLanguage.tokenize("(\\W+)\\s*", true);
exchange.getIn().setBody("The little fox");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(3, names.size());
assertEquals("The", names.get(0));
assertEquals("little", names.get(1));
assertEquals("fox", names.get(2));
}
@Test
public void testTokenizeHeaderRegEx() throws Exception {
Expression exp = TokenizeLanguage.tokenize("quote", "(\\W+)\\s*", true);
exchange.getIn().setHeader("quote", "Camel rocks");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(2, names.size());
assertEquals("Camel", names.get(0));
assertEquals("rocks", names.get(1));
}
@Test
public void testTokenizeManualConfiguration() throws Exception {
TokenizeLanguage lan = new TokenizeLanguage();
lan.setHeaderName("names");
lan.setRegex(false);
lan.setToken(",");
Expression exp = lan.createExpression();
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(3, names.size());
assertEquals("Claus", names.get(0));
assertEquals("James", names.get(1));
assertEquals("Willem", names.get(2));
assertEquals("names", lan.getHeaderName());
assertEquals(",", lan.getToken());
assertEquals(false, lan.isRegex());
assertEquals(false, lan.isSingleton());
}
@Test
public void testTokenizePairSpecial() throws Exception {
Expression exp = TokenizeLanguage.tokenizePair("!", "@", false);
exchange.getIn().setBody("2011-11-11\n!James@!Claus@\n2 records");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(2, names.size());
assertEquals("James", names.get(0));
assertEquals("Claus", names.get(1));
}
@Test
public void testTokenizePair() throws Exception {
Expression exp = TokenizeLanguage.tokenizePair("[START]", "[END]", false);
exchange.getIn().setBody("2011-11-11\n[START]James[END]\n[START]Claus[END]\n2 records");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(2, names.size());
assertEquals("James", names.get(0));
assertEquals("Claus", names.get(1));
}
@Test
public void testTokenizePairSimple() throws Exception {
Expression exp = TokenizeLanguage.tokenizePair("${header.foo}", "${header.bar}", false);
exchange.getIn().setHeader("foo", "[START]");
exchange.getIn().setHeader("bar", "[END]");
exchange.getIn().setBody("2011-11-11\n[START]James[END]\n[START]Claus[END]\n2 records");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(2, names.size());
assertEquals("James", names.get(0));
assertEquals("Claus", names.get(1));
}
@Test
public void testTokenizePairIncludeTokens() throws Exception {
Expression exp = TokenizeLanguage.tokenizePair("[START]", "[END]", true);
exchange.getIn().setBody("2011-11-11\n[START]James[END]\n[START]Claus[END]\n2 records");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(2, names.size());
assertEquals("[START]James[END]", names.get(0));
assertEquals("[START]Claus[END]", names.get(1));
}
@Test
public void testTokenizeXMLPair() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("<person>", null);
exchange.getIn().setBody("<persons><person>James</person><person>Claus</person><person>Jonathan</person><person>Hadrian</person></persons>");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(4, names.size());
assertEquals("<person>James</person>", names.get(0));
assertEquals("<person>Claus</person>", names.get(1));
assertEquals("<person>Jonathan</person>", names.get(2));
assertEquals("<person>Hadrian</person>", names.get(3));
}
@Test
public void testTokenizeXMLPairSimple() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("${header.foo}", null);
exchange.getIn().setHeader("foo", "<person>");
exchange.getIn().setBody("<persons><person>James</person><person>Claus</person><person>Jonathan</person><person>Hadrian</person></persons>");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(4, names.size());
assertEquals("<person>James</person>", names.get(0));
assertEquals("<person>Claus</person>", names.get(1));
assertEquals("<person>Jonathan</person>", names.get(2));
assertEquals("<person>Hadrian</person>", names.get(3));
}
@Test
public void testTokenizeXMLPairNoXMLTag() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("person", null);
exchange.getIn().setBody("<persons><person>James</person><person>Claus</person><person>Jonathan</person><person>Hadrian</person></persons>");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(4, names.size());
assertEquals("<person>James</person>", names.get(0));
assertEquals("<person>Claus</person>", names.get(1));
assertEquals("<person>Jonathan</person>", names.get(2));
assertEquals("<person>Hadrian</person>", names.get(3));
}
@Test
public void testTokenizeXMLPairWithNoise() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("<person>", null);
exchange.getIn().setBody("<?xml version=\"1.0\"?><!-- bla bla --><persons>\n<person>James</person>\n<person>Claus</person>\n"
+ "<!-- more bla bla --><person>Jonathan</person>\n<person>Hadrian</person>\n</persons> ");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(4, names.size());
assertEquals("<person>James</person>", names.get(0));
assertEquals("<person>Claus</person>", names.get(1));
assertEquals("<person>Jonathan</person>", names.get(2));
assertEquals("<person>Hadrian</person>", names.get(3));
}
@Test
public void testTokenizeXMLPairEmpty() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("<person>", null);
exchange.getIn().setBody("<?xml version=\"1.0\"?><!-- bla bla --><persons></persons> ");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(0, names.size());
}
@Test
public void testTokenizeXMLPairNoData() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("<person>", null);
exchange.getIn().setBody("");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(0, names.size());
}
@Test
public void testTokenizeXMLPairNullData() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("<person>", null);
exchange.getIn().setBody(null);
List<?> names = exp.evaluate(exchange, List.class);
assertNull(names);
}
@Test
public void testTokenizeXMLPairWithSimilarChildNames() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("Trip", "Trips");
exchange.getIn().setBody("<?xml version='1.0' encoding='UTF-8'?>\n<Trips>\n<Trip>\n<TripType>\n</TripType>\n</Trip>\n</Trips>");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(1, names.size());
}
@Test
public void testTokenizeXMLPairWithDefaultNamespace() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("<person>", "<persons>");
exchange.getIn().setBody("<?xml version=\"1.0\"?><persons xmlns=\"http:acme.com/persons\">\n<person>James</person>\n<person>Claus</person>\n"
+ "<person>Jonathan</person>\n<person>Hadrian</person>\n</persons>\n");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(4, names.size());
assertEquals("<person xmlns=\"http:acme.com/persons\">James</person>", names.get(0));
assertEquals("<person xmlns=\"http:acme.com/persons\">Claus</person>", names.get(1));
assertEquals("<person xmlns=\"http:acme.com/persons\">Jonathan</person>", names.get(2));
assertEquals("<person xmlns=\"http:acme.com/persons\">Hadrian</person>", names.get(3));
}
@Test
public void testTokenizeXMLPairWithDefaultNamespaceNotInherit() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("<person>", null);
exchange.getIn().setBody("<?xml version=\"1.0\"?><persons xmlns=\"http:acme.com/persons\">\n<person>James</person>\n<person>Claus</person>\n"
+ "<person>Jonathan</person>\n<person>Hadrian</person>\n</persons>\n");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(4, names.size());
assertEquals("<person>James</person>", names.get(0));
assertEquals("<person>Claus</person>", names.get(1));
assertEquals("<person>Jonathan</person>", names.get(2));
assertEquals("<person>Hadrian</person>", names.get(3));
}
@Test
public void testTokenizeXMLPairWithDefaultAndFooNamespace() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("<person>", "<persons>");
exchange.getIn().setBody("<?xml version=\"1.0\"?><persons xmlns=\"http:acme.com/persons\" xmlns:foo=\"http:foo.com\">\n<person>James</person>\n<person>Claus</person>\n"
+ "<person>Jonathan</person>\n<person>Hadrian</person>\n</persons>\n");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(4, names.size());
assertEquals("<person xmlns=\"http:acme.com/persons\" xmlns:foo=\"http:foo.com\">James</person>", names.get(0));
assertEquals("<person xmlns=\"http:acme.com/persons\" xmlns:foo=\"http:foo.com\">Claus</person>", names.get(1));
assertEquals("<person xmlns=\"http:acme.com/persons\" xmlns:foo=\"http:foo.com\">Jonathan</person>", names.get(2));
assertEquals("<person xmlns=\"http:acme.com/persons\" xmlns:foo=\"http:foo.com\">Hadrian</person>", names.get(3));
}
@Test
public void testTokenizeXMLPairWithLocalNamespace() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("<person>", null);
exchange.getIn().setBody("<?xml version=\"1.0\"?><persons>\n<person xmlns=\"http:acme.com/persons\">James</person>\n<person xmlns=\"http:acme.com/persons\">Claus</person>\n"
+ "<person xmlns=\"http:acme.com/persons\">Jonathan</person>\n<person xmlns=\"http:acme.com/persons\">Hadrian</person>\n</persons>\n");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(4, names.size());
assertEquals("<person xmlns=\"http:acme.com/persons\">James</person>", names.get(0));
assertEquals("<person xmlns=\"http:acme.com/persons\">Claus</person>", names.get(1));
assertEquals("<person xmlns=\"http:acme.com/persons\">Jonathan</person>", names.get(2));
assertEquals("<person xmlns=\"http:acme.com/persons\">Hadrian</person>", names.get(3));
}
@Test
public void testTokenizeXMLPairWithLocalAndInheritedNamespace() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("<person>", "<persons>");
exchange.getIn().setBody("<?xml version=\"1.0\"?><persons xmlns=\"http:acme.com/persons\">\n<person xmlns:foo=\"http:foo.com\">James</person>\n<person>Claus</person>\n"
+ "<person>Jonathan</person>\n<person xmlns:bar=\"http:bar.com\">Hadrian</person>\n</persons>\n");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(4, names.size());
assertEquals("<person xmlns:foo=\"http:foo.com\" xmlns=\"http:acme.com/persons\">James</person>", names.get(0));
assertEquals("<person xmlns=\"http:acme.com/persons\">Claus</person>", names.get(1));
assertEquals("<person xmlns=\"http:acme.com/persons\">Jonathan</person>", names.get(2));
assertEquals("<person xmlns:bar=\"http:bar.com\" xmlns=\"http:acme.com/persons\">Hadrian</person>", names.get(3));
}
@Test
public void testTokenizeXMLPairWithLocalAndNotInheritedNamespace() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("<person>", null);
exchange.getIn().setBody("<?xml version=\"1.0\"?><persons xmlns=\"http:acme.com/persons\">\n<person xmlns:foo=\"http:foo.com\">James</person>\n"
+ "<person>Claus</person>\n<person>Jonathan</person>\n<person xmlns:bar=\"http:bar.com\">Hadrian</person>\n</persons>\n");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(4, names.size());
assertEquals("<person xmlns:foo=\"http:foo.com\">James</person>", names.get(0));
assertEquals("<person>Claus</person>", names.get(1));
assertEquals("<person>Jonathan</person>", names.get(2));
assertEquals("<person xmlns:bar=\"http:bar.com\">Hadrian</person>", names.get(3));
}
@Test
public void testTokenizeXMLPairWithAttributes() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("<person>", null);
exchange.getIn().setBody("<persons><person id=\"1\">James</person><person id=\"2\">Claus</person><person id=\"3\">Jonathan</person>"
+ "<person id=\"4\">Hadrian</person></persons>");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(4, names.size());
assertEquals("<person id=\"1\">James</person>", names.get(0));
assertEquals("<person id=\"2\">Claus</person>", names.get(1));
assertEquals("<person id=\"3\">Jonathan</person>", names.get(2));
assertEquals("<person id=\"4\">Hadrian</person>", names.get(3));
}
@Test
public void testTokenizeXMLPairWithAttributesInheritNamespace() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("<person>", "<persons>");
exchange.getIn().setBody("<persons xmlns=\"http:acme.com/persons\"><person id=\"1\">James</person><person id=\"2\">Claus</person>"
+ "<person id=\"3\">Jonathan</person><person id=\"4\">Hadrian</person></persons>");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(4, names.size());
assertEquals("<person id=\"1\" xmlns=\"http:acme.com/persons\">James</person>", names.get(0));
assertEquals("<person id=\"2\" xmlns=\"http:acme.com/persons\">Claus</person>", names.get(1));
assertEquals("<person id=\"3\" xmlns=\"http:acme.com/persons\">Jonathan</person>", names.get(2));
assertEquals("<person id=\"4\" xmlns=\"http:acme.com/persons\">Hadrian</person>", names.get(3));
}
@Test
public void testTokenizeXMLPairWithAttributes2InheritNamespace() throws Exception {
Expression exp = TokenizeLanguage.tokenizeXML("<person>", "<persons>");
exchange.getIn().setBody("<persons riders=\"true\" xmlns=\"http:acme.com/persons\"><person id=\"1\">James</person><person id=\"2\">Claus</person>"
+ "<person id=\"3\">Jonathan</person><person id=\"4\">Hadrian</person></persons>");
List<?> names = exp.evaluate(exchange, List.class);
assertEquals(4, names.size());
assertEquals("<person id=\"1\" xmlns=\"http:acme.com/persons\">James</person>", names.get(0));
assertEquals("<person id=\"2\" xmlns=\"http:acme.com/persons\">Claus</person>", names.get(1));
assertEquals("<person id=\"3\" xmlns=\"http:acme.com/persons\">Jonathan</person>", names.get(2));
assertEquals("<person id=\"4\" xmlns=\"http:acme.com/persons\">Hadrian</person>", names.get(3));
}
} | apache-2.0 |
jmostella/armeria | core/src/main/java/com/linecorp/armeria/server/AnnotatedValueResolver.java | 48024 | /*
* Copyright 2018 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.server;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static com.linecorp.armeria.common.HttpParameters.EMPTY_PARAMETERS;
import static com.linecorp.armeria.internal.DefaultValues.getSpecifiedValue;
import static com.linecorp.armeria.server.AnnotatedElementNameUtil.findName;
import static com.linecorp.armeria.server.AnnotatedHttpServiceTypeUtil.normalizeContainerType;
import static com.linecorp.armeria.server.AnnotatedHttpServiceTypeUtil.stringToType;
import static com.linecorp.armeria.server.AnnotatedHttpServiceTypeUtil.validateElementType;
import static java.util.Objects.requireNonNull;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Ascii;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.MapMaker;
import com.linecorp.armeria.common.AggregatedHttpMessage;
import com.linecorp.armeria.common.HttpHeaderNames;
import com.linecorp.armeria.common.HttpParameters;
import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.common.MediaType;
import com.linecorp.armeria.common.Request;
import com.linecorp.armeria.common.RequestContext;
import com.linecorp.armeria.common.util.Exceptions;
import com.linecorp.armeria.internal.FallthroughException;
import com.linecorp.armeria.server.AnnotatedBeanFactory.BeanFactoryId;
import com.linecorp.armeria.server.annotation.ByteArrayRequestConverterFunction;
import com.linecorp.armeria.server.annotation.Cookies;
import com.linecorp.armeria.server.annotation.Default;
import com.linecorp.armeria.server.annotation.Header;
import com.linecorp.armeria.server.annotation.JacksonRequestConverterFunction;
import com.linecorp.armeria.server.annotation.Param;
import com.linecorp.armeria.server.annotation.RequestConverterFunction;
import com.linecorp.armeria.server.annotation.RequestObject;
import com.linecorp.armeria.server.annotation.StringRequestConverterFunction;
import io.netty.handler.codec.http.HttpConstants;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.cookie.Cookie;
import io.netty.handler.codec.http.cookie.ServerCookieDecoder;
import io.netty.util.AsciiString;
final class AnnotatedValueResolver {
private static final Logger logger = LoggerFactory.getLogger(AnnotatedValueResolver.class);
private static final List<RequestObjectResolver> defaultRequestConverters =
ImmutableList.of((resolverContext, expectedResultType, beanFactoryId) ->
AnnotatedBeanFactory.find(beanFactoryId)
.orElseThrow(RequestConverterFunction::fallthrough)
.apply(resolverContext),
RequestObjectResolver.of(new JacksonRequestConverterFunction()),
RequestObjectResolver.of(new StringRequestConverterFunction()),
RequestObjectResolver.of(new ByteArrayRequestConverterFunction()));
private static final Object[] emptyArguments = new Object[0];
/**
* Returns an array of arguments which are resolved by each {@link AnnotatedValueResolver} of the
* specified {@code resolvers}.
*/
static Object[] toArguments(List<AnnotatedValueResolver> resolvers,
ResolverContext resolverContext) {
requireNonNull(resolvers, "resolvers");
requireNonNull(resolverContext, "resolverContext");
if (resolvers.isEmpty()) {
return emptyArguments;
}
return resolvers.stream().map(resolver -> resolver.resolve(resolverContext)).toArray();
}
/**
* Returns a list of {@link RequestObjectResolver} that default request converters are added.
*/
static List<RequestObjectResolver> toRequestObjectResolvers(List<RequestConverterFunction> converters) {
final ImmutableList.Builder<RequestObjectResolver> builder = ImmutableList.builder();
// Wrap every converters received from a user with a default object resolver.
converters.stream().map(RequestObjectResolver::of).forEach(builder::add);
builder.addAll(defaultRequestConverters);
return builder.build();
}
/**
* Returns a list of {@link AnnotatedValueResolver} which is constructed with the specified
* {@link Executable}, {@code pathParams} and {@code objectResolvers}. The {@link Executable} can be
* one of {@link Constructor} or {@link Method}.
*/
static List<AnnotatedValueResolver> of(Executable constructorOrMethod, Set<String> pathParams,
List<RequestObjectResolver> objectResolvers) {
final Parameter[] parameters = constructorOrMethod.getParameters();
if (parameters.length == 0) {
throw new NoParameterException(constructorOrMethod.toGenericString());
}
//
// Try to check whether it is an annotated constructor or method first. e.g.
//
// @Param
// void setter(String name) { ... }
//
// In this case, we need to retrieve the value of @Param annotation from 'name' parameter,
// not the constructor or method. Also 'String' type is used for the parameter.
//
final Optional<AnnotatedValueResolver> resolver;
if (isAnnotationPresent(constructorOrMethod)) {
//
// Only allow a single parameter on an annotated method. The followings cause an error:
//
// @Param
// void setter(String name, int id, String address) { ... }
//
// @Param
// void setter() { ... }
//
if (parameters.length != 1) {
throw new IllegalArgumentException("Only one parameter is allowed to an annotated method: " +
constructorOrMethod.toGenericString());
}
//
// Filter out like the following case:
//
// @Param
// void setter(@Header String name) { ... }
//
if (isAnnotationPresent(parameters[0])) {
throw new IllegalArgumentException("Both a method and parameter are annotated: " +
constructorOrMethod.toGenericString());
}
resolver = of(constructorOrMethod,
parameters[0], parameters[0].getType(), pathParams, objectResolvers);
} else {
//
// There's no annotation. So there should be no @Default annotation, too.
// e.g.
// @Default("a")
// void method1(ServiceRequestContext) { ... }
//
if (constructorOrMethod.isAnnotationPresent(Default.class)) {
throw new IllegalArgumentException(
'@' + Default.class.getSimpleName() + " is not supported for: " +
constructorOrMethod.toGenericString());
}
resolver = Optional.empty();
}
//
// If there is no annotation on the constructor or method, try to check whether it has
// annotated parameters. e.g.
//
// void setter1(@Param String name) { ... }
// void setter2(@Param String name, @Header List<String> xForwardedFor) { ... }
//
final List<AnnotatedValueResolver> list =
resolver.<List<AnnotatedValueResolver>>map(ImmutableList::of).orElseGet(
() -> Arrays.stream(parameters)
.map(p -> of(p, pathParams, objectResolvers))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList()));
if (list.isEmpty()) {
throw new NoAnnotatedParameterException(constructorOrMethod.toGenericString());
}
if (list.size() != parameters.length) {
throw new IllegalArgumentException("Unsupported parameter exists: " +
constructorOrMethod.toGenericString());
}
return list;
}
/**
* Returns a list of {@link AnnotatedValueResolver} which is constructed with the specified
* {@link Parameter}, {@code pathParams} and {@code objectResolvers}.
*/
static Optional<AnnotatedValueResolver> of(Parameter parameter, Set<String> pathParams,
List<RequestObjectResolver> objectResolvers) {
return of(parameter, parameter, parameter.getType(), pathParams, objectResolvers);
}
/**
* Returns a list of {@link AnnotatedValueResolver} which is constructed with the specified
* {@link Field}, {@code pathParams} and {@code objectResolvers}.
*/
static Optional<AnnotatedValueResolver> of(Field field, Set<String> pathParams,
List<RequestObjectResolver> objectResolvers) {
return of(field, field, field.getType(), pathParams, objectResolvers);
}
/**
* Creates a new {@link AnnotatedValueResolver} instance if the specified {@code annotatedElement} is
* a component of {@link AnnotatedHttpService}.
*
* @param annotatedElement an element which is annotated with a value specifier such as {@link Param} and
* {@link Header}.
* @param typeElement an element which is used for retrieving its type and name.
* @param type a type of the given {@link Parameter} or {@link Field}. It is a type of
* the specified {@code typeElement} parameter.
* @param pathParams a set of path variables.
* @param objectResolvers a list of {@link RequestObjectResolver} to be evaluated for the objects which
* are annotated with {@link RequestObject} annotation.
*/
private static Optional<AnnotatedValueResolver> of(AnnotatedElement annotatedElement,
AnnotatedElement typeElement, Class<?> type,
Set<String> pathParams,
List<RequestObjectResolver> objectResolvers) {
requireNonNull(annotatedElement, "annotatedElement");
requireNonNull(typeElement, "typeElement");
requireNonNull(type, "type");
requireNonNull(pathParams, "pathParams");
requireNonNull(objectResolvers, "objectResolvers");
final Param param = annotatedElement.getAnnotation(Param.class);
if (param != null) {
final String name = findName(param, typeElement);
if (pathParams.contains(name)) {
return Optional.of(ofPathVariable(param, name, annotatedElement, typeElement, type));
} else {
return Optional.of(ofHttpParameter(param, name, annotatedElement, typeElement, type));
}
}
final Header header = annotatedElement.getAnnotation(Header.class);
if (header != null) {
return Optional.of(ofHeader(header, annotatedElement, typeElement, type));
}
final RequestObject requestObject = annotatedElement.getAnnotation(RequestObject.class);
if (requestObject != null) {
return Optional.of(ofRequestObject(requestObject, annotatedElement, type,
pathParams, objectResolvers));
}
// There should be no '@Default' annotation on 'annotatedElement' if 'annotatedElement' is
// different from 'typeElement', because it was checked before calling this method.
// So, 'typeElement' should be used when finding an injectable type because we need to check
// syntactic errors like below:
//
// void method1(@Default("a") ServiceRequestContext) { ... }
//
return Optional.ofNullable(ofInjectableTypes(typeElement, type));
}
private static boolean isAnnotationPresent(AnnotatedElement element) {
return element.isAnnotationPresent(Param.class) ||
element.isAnnotationPresent(Header.class) ||
element.isAnnotationPresent(RequestObject.class);
}
private static AnnotatedValueResolver ofPathVariable(Param param, String name,
AnnotatedElement annotatedElement,
AnnotatedElement typeElement, Class<?> type) {
return builder(annotatedElement, type)
.annotation(param)
.httpElementName(name)
.typeElement(typeElement)
.pathVariable(true)
.resolver(resolver(ctx -> ctx.context().pathParam(name)))
.build();
}
private static AnnotatedValueResolver ofHttpParameter(Param param, String name,
AnnotatedElement annotatedElement,
AnnotatedElement typeElement, Class<?> type) {
return builder(annotatedElement, type)
.annotation(param)
.httpElementName(name)
.typeElement(typeElement)
.supportOptional(true)
.supportDefault(true)
.supportContainer(true)
.aggregation(AggregationStrategy.FOR_FORM_DATA)
.resolver(resolver(ctx -> ctx.httpParameters().getAll(name),
() -> "Cannot resolve a value from HTTP parameter: " + name))
.build();
}
private static AnnotatedValueResolver ofHeader(Header header,
AnnotatedElement annotatedElement,
AnnotatedElement typeElement, Class<?> type) {
final String name = findName(header, typeElement);
return builder(annotatedElement, type)
.annotation(header)
.httpElementName(name)
.typeElement(typeElement)
.supportOptional(true)
.supportDefault(true)
.supportContainer(true)
.resolver(resolver(
ctx -> ctx.request().headers().getAll(AsciiString.of(name)),
() -> "Cannot resolve a value from HTTP header: " + name))
.build();
}
private static AnnotatedValueResolver ofRequestObject(RequestObject requestObject,
AnnotatedElement annotatedElement,
Class<?> type, Set<String> pathParams,
List<RequestObjectResolver> objectResolvers) {
final List<RequestObjectResolver> newObjectResolvers;
if (requestObject.value() != RequestConverterFunction.class) {
// There is a converter which is specified by a user.
final RequestConverterFunction requestConverterFunction =
AnnotatedHttpServiceFactory.getInstance(requestObject, RequestConverterFunction.class);
newObjectResolvers = ImmutableList.<RequestObjectResolver>builder()
.add(RequestObjectResolver.of(requestConverterFunction))
.addAll(objectResolvers)
.build();
} else {
newObjectResolvers = objectResolvers;
}
// To do recursive resolution like a bean inside another bean, the original object resolvers should
// be passed into the AnnotatedBeanFactory#register.
final BeanFactoryId beanFactoryId = AnnotatedBeanFactory.register(type, pathParams, objectResolvers);
return builder(annotatedElement, type)
.annotation(requestObject)
.aggregation(AggregationStrategy.ALWAYS)
.resolver(resolver(newObjectResolvers, beanFactoryId))
.build();
}
@Nullable
private static AnnotatedValueResolver ofInjectableTypes(AnnotatedElement annotatedElement, Class<?> type) {
if (type == RequestContext.class || type == ServiceRequestContext.class) {
return builder(annotatedElement, type)
.resolver((unused, ctx) -> ctx.context())
.build();
}
if (type == Request.class || type == HttpRequest.class) {
return builder(annotatedElement, type)
.resolver((unused, ctx) -> ctx.request())
.build();
}
if (type == AggregatedHttpMessage.class) {
return builder(annotatedElement, AggregatedHttpMessage.class)
.resolver((unused, ctx) -> ctx.message())
.aggregation(AggregationStrategy.ALWAYS)
.build();
}
if (type == HttpParameters.class) {
return builder(annotatedElement, HttpParameters.class)
.resolver((unused, ctx) -> ctx.httpParameters())
.aggregation(AggregationStrategy.FOR_FORM_DATA)
.build();
}
if (type == Cookies.class) {
return builder(annotatedElement, Cookies.class)
.resolver((unused, ctx) -> {
final List<String> values = ctx.request().headers().getAll(HttpHeaderNames.COOKIE);
if (values.isEmpty()) {
return Cookies.copyOf(ImmutableSet.of());
}
final ImmutableSet.Builder<Cookie> cookies = ImmutableSet.builder();
values.stream()
.map(ServerCookieDecoder.STRICT::decode)
.forEach(cookies::addAll);
return Cookies.copyOf(cookies.build());
})
.build();
}
// Unsupported type.
return null;
}
/**
* Returns a single value resolver which retrieves a value from the specified {@code getter}
* and converts it.
*/
private static BiFunction<AnnotatedValueResolver, ResolverContext, Object>
resolver(Function<ResolverContext, String> getter) {
return (resolver, ctx) -> resolver.convert(getter.apply(ctx));
}
/**
* Returns a collection value resolver which retrieves a list of string from the specified {@code getter}
* and adds them to the specified collection data type.
*/
private static BiFunction<AnnotatedValueResolver, ResolverContext, Object>
resolver(Function<ResolverContext, List<String>> getter, Supplier<String> failureMessageSupplier) {
return (resolver, ctx) -> {
final List<String> values = getter.apply(ctx);
if (!resolver.hasContainer()) {
if (values != null && !values.isEmpty()) {
return resolver.convert(values.get(0));
}
return resolver.defaultOrException();
}
try {
assert resolver.containerType() != null;
@SuppressWarnings("unchecked")
final Collection<Object> resolvedValues =
(Collection<Object>) resolver.containerType().newInstance();
// Do not convert value here because the element type is String.
if (values != null && !values.isEmpty()) {
values.stream().map(resolver::convert).forEach(resolvedValues::add);
} else {
final Object defaultValue = resolver.defaultOrException();
if (defaultValue != null) {
resolvedValues.add(defaultValue);
}
}
return resolvedValues;
} catch (Throwable cause) {
throw new IllegalArgumentException(failureMessageSupplier.get(), cause);
}
};
}
/**
* Returns a bean resolver which retrieves a value using request converters. If the target element
* is an annotated bean, a bean factory of the specified {@link BeanFactoryId} will be used for creating an
* instance.
*/
private static BiFunction<AnnotatedValueResolver, ResolverContext, Object>
resolver(List<RequestObjectResolver> objectResolvers, BeanFactoryId beanFactoryId) {
return (resolver, ctx) -> {
Object value = null;
for (final RequestObjectResolver objectResolver : objectResolvers) {
try {
value = objectResolver.convert(ctx, resolver.elementType(), beanFactoryId);
break;
} catch (FallthroughException ignore) {
// Do nothing.
} catch (Throwable cause) {
Exceptions.throwUnsafely(cause);
}
}
if (value != null) {
return value;
}
throw new IllegalArgumentException("No suitable request converter found for a @" +
RequestObject.class.getSimpleName() + " '" +
resolver.elementType().getSimpleName() + '\'');
};
}
@Nullable
private final Annotation annotation;
@Nullable
private final String httpElementName;
private final boolean isPathVariable;
private final boolean shouldExist;
private final boolean shouldWrapValueAsOptional;
@Nullable
private final Class<?> containerType;
private final Class<?> elementType;
@Nullable
private final Object defaultValue;
private final BiFunction<AnnotatedValueResolver, ResolverContext, Object> resolver;
@Nullable
private final EnumConverter<?> enumConverter;
private final AggregationStrategy aggregationStrategy;
private static final ConcurrentMap<Class<?>, EnumConverter<?>> enumConverters = new MapMaker().makeMap();
private AnnotatedValueResolver(@Nullable Annotation annotation, @Nullable String httpElementName,
boolean isPathVariable, boolean shouldExist,
boolean shouldWrapValueAsOptional,
@Nullable Class<?> containerType, Class<?> elementType,
@Nullable String defaultValue,
BiFunction<AnnotatedValueResolver, ResolverContext, Object> resolver,
AggregationStrategy aggregationStrategy) {
this.annotation = annotation;
this.httpElementName = httpElementName;
this.isPathVariable = isPathVariable;
this.shouldExist = shouldExist;
this.shouldWrapValueAsOptional = shouldWrapValueAsOptional;
this.elementType = requireNonNull(elementType, "elementType");
this.containerType = containerType;
this.resolver = requireNonNull(resolver, "resolver");
this.aggregationStrategy = requireNonNull(aggregationStrategy, "aggregationStrategy");
enumConverter = enumConverter(elementType);
// Must be called after initializing 'enumConverter'.
this.defaultValue = defaultValue != null ? convert(defaultValue, elementType, enumConverter)
: null;
}
@Nullable
private static EnumConverter<?> enumConverter(Class<?> elementType) {
if (!elementType.isEnum()) {
return null;
}
return enumConverters.computeIfAbsent(elementType, newElementType -> {
logger.debug("Registered an Enum {}", newElementType);
return new EnumConverter<>(newElementType.asSubclass(Enum.class));
});
}
@VisibleForTesting
@Nullable
Annotation annotation() {
return annotation;
}
boolean isAnnotationType(Class<? extends Annotation> target) {
return annotation != null &&
annotation.annotationType() == target;
}
@Nullable
String httpElementName() {
// Currently, this is non-null only if the element is one of the HTTP path variable,
// parameter or header.
return httpElementName;
}
boolean isPathVariable() {
return isPathVariable;
}
@VisibleForTesting
public boolean shouldExist() {
return shouldExist;
}
@VisibleForTesting
@Nullable
Class<?> containerType() {
// 'List' or 'Set'
return containerType;
}
@VisibleForTesting
Class<?> elementType() {
return elementType;
}
@VisibleForTesting
@Nullable
Object defaultValue() {
return defaultValue;
}
AggregationStrategy aggregationStrategy() {
return aggregationStrategy;
}
boolean hasContainer() {
return containerType != null &&
(List.class.isAssignableFrom(containerType) || Set.class.isAssignableFrom(containerType));
}
Object resolve(ResolverContext ctx) {
final Object resolved = resolver.apply(this, ctx);
return shouldWrapValueAsOptional ? Optional.ofNullable(resolved)
: resolved;
}
private static Object convert(String value, Class<?> elementType,
@Nullable EnumConverter<?> enumConverter) {
return enumConverter != null ? enumConverter.toEnum(value)
: stringToType(value, elementType);
}
@Nullable
private Object convert(@Nullable String value) {
if (value == null) {
return defaultOrException();
}
return convert(value, elementType, enumConverter);
}
@Nullable
private Object defaultOrException() {
if (!shouldExist) {
// May return 'null' if no default value is specified.
return defaultValue;
}
throw new IllegalArgumentException("Mandatory parameter is missing: " + httpElementName);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("annotation",
annotation != null ? annotation.annotationType().getSimpleName() : "(none)")
.add("httpElementName", httpElementName)
.add("pathVariable", isPathVariable)
.add("shouldExist", shouldExist)
.add("shouldWrapValueAsOptional", shouldWrapValueAsOptional)
.add("elementType", elementType.getSimpleName())
.add("containerType",
containerType != null ? containerType.getSimpleName() : "(none)")
.add("defaultValue", defaultValue)
.add("defaultValueType",
defaultValue != null ? defaultValue.getClass().getSimpleName() : "(none)")
.add("resolver", resolver)
.add("enumConverter", enumConverter)
.toString();
}
private static Builder builder(AnnotatedElement annotatedElement, Type type) {
return new Builder(annotatedElement, type);
}
private static final class Builder {
private final AnnotatedElement annotatedElement;
private final Type type;
private AnnotatedElement typeElement;
@Nullable
private Annotation annotation;
@Nullable
private String httpElementName;
private boolean pathVariable;
private boolean supportContainer;
private boolean supportOptional;
private boolean supportDefault;
@Nullable
private BiFunction<AnnotatedValueResolver, ResolverContext, Object> resolver;
private AggregationStrategy aggregation = AggregationStrategy.NONE;
private Builder(AnnotatedElement annotatedElement, Type type) {
this.annotatedElement = requireNonNull(annotatedElement, "annotatedElement");
this.type = requireNonNull(type, "type");
typeElement = annotatedElement;
}
/**
* Sets the annotation which is one of {@link Param}, {@link Header} or {@link RequestObject}.
*/
private Builder annotation(Annotation annotation) {
this.annotation = annotation;
return this;
}
/**
* Sets a name of the element.
*/
private Builder httpElementName(String httpElementName) {
this.httpElementName = httpElementName;
return this;
}
/**
* Sets whether this element is a path variable.
*/
private Builder pathVariable(boolean pathVariable) {
this.pathVariable = pathVariable;
return this;
}
/**
* Sets whether the value type can be a {@link List} or {@link Set}.
*/
private Builder supportContainer(boolean supportContainer) {
this.supportContainer = supportContainer;
return this;
}
/**
* Sets whether the value type can be wrapped by {@link Optional}.
*/
private Builder supportOptional(boolean supportOptional) {
this.supportOptional = supportOptional;
return this;
}
/**
* Sets whether the element can be annotated with {@link Default} annotation.
*/
private Builder supportDefault(boolean supportDefault) {
this.supportDefault = supportDefault;
return this;
}
/**
* Sets an {@link AnnotatedElement} which is used to infer its type.
*/
private Builder typeElement(AnnotatedElement typeElement) {
this.typeElement = typeElement;
return this;
}
/**
* Sets a value resolver.
*/
private Builder resolver(BiFunction<AnnotatedValueResolver, ResolverContext, Object> resolver) {
this.resolver = resolver;
return this;
}
/**
* Sets an {@link AggregationStrategy} for the element.
*/
private Builder aggregation(AggregationStrategy aggregation) {
this.aggregation = aggregation;
return this;
}
private static Type parameterizedTypeOf(AnnotatedElement element) {
if (element instanceof Parameter) {
return ((Parameter) element).getParameterizedType();
}
if (element instanceof Field) {
return ((Field) element).getGenericType();
}
throw new IllegalArgumentException("Unsupported annotated element: " +
element.getClass().getSimpleName());
}
private static Entry<Class<?>, Class<?>> resolveTypes(Type parameterizedType, Type type,
boolean unwrapOptionalType) {
if (unwrapOptionalType) {
// Unwrap once again so that a pattern like 'Optional<List<?>>' can be supported.
assert parameterizedType instanceof ParameterizedType : String.valueOf(parameterizedType);
parameterizedType = ((ParameterizedType) parameterizedType).getActualTypeArguments()[0];
}
final Class<?> elementType;
final Class<?> containerType;
if (parameterizedType instanceof ParameterizedType) {
try {
elementType =
(Class<?>) ((ParameterizedType) parameterizedType).getActualTypeArguments()[0];
} catch (Throwable cause) {
throw new IllegalArgumentException("Invalid parameter type: " + parameterizedType, cause);
}
containerType = normalizeContainerType(
(Class<?>) ((ParameterizedType) parameterizedType).getRawType());
} else {
elementType = unwrapOptionalType ? (Class<?>) parameterizedType : (Class<?>) type;
containerType = null;
}
return new SimpleImmutableEntry<>(containerType, validateElementType(elementType));
}
private AnnotatedValueResolver build() {
checkArgument(resolver != null, "'resolver' should be specified");
// Request convert may produce 'Optional<?>' value. But it is different from supporting
// 'Optional' type. So if the annotation is 'RequestObject', 'shouldWrapValueAsOptional'
// is always set as 'false'.
final boolean shouldWrapValueAsOptional = type == Optional.class &&
(annotation == null ||
annotation.annotationType() != RequestObject.class);
if (!supportOptional && shouldWrapValueAsOptional) {
throw new IllegalArgumentException(
'@' + Optional.class.getSimpleName() + " is not supported for: " +
(annotation != null ? annotation.annotationType().getSimpleName()
: type.getTypeName()));
}
final boolean shouldExist;
final String defaultValue;
final Default aDefault = annotatedElement.getAnnotation(Default.class);
if (aDefault != null) {
if (!supportDefault) {
throw new IllegalArgumentException(
'@' + Default.class.getSimpleName() + " is not supported for: " +
(annotation != null ? annotation.annotationType().getSimpleName()
: type.getTypeName()));
}
// Warn unusual usage. e.g. @Param @Default("a") Optional<String> param
if (shouldWrapValueAsOptional) {
// 'annotatedElement' can be one of constructor, field, method or parameter.
// So, it may be printed verbosely but it's okay because it provides where this message
// is caused.
logger.warn("Both {} type and @{} are specified on {}. One of them can be omitted.",
Optional.class.getSimpleName(), Default.class.getSimpleName(),
annotatedElement);
}
shouldExist = false;
defaultValue = getSpecifiedValue(aDefault.value()).get();
} else {
shouldExist = !shouldWrapValueAsOptional;
// Set the default value to 'null' if it was not specified.
defaultValue = null;
}
if (pathVariable && !shouldExist) {
throw new IllegalArgumentException("Path variable should be mandatory: " + annotatedElement);
}
final Entry<Class<?>, Class<?>> types;
if (annotation != null &&
(annotation.annotationType() == Param.class ||
annotation.annotationType() == Header.class)) {
assert httpElementName != null;
// The value annotated with @Param or @Header should be converted to the desired type,
// so the type should be resolved here.
final Type parameterizedType = parameterizedTypeOf(typeElement);
types = resolveTypes(parameterizedType, type, shouldWrapValueAsOptional);
// Currently a container type such as 'List' and 'Set' is allowed to @Header annotation
// and HTTP parameters specified by @Param annotation.
if (!supportContainer && types.getKey() != null) {
throw new IllegalArgumentException("Unsupported collection type: " + parameterizedType);
}
} else {
assert type.getClass() == Class.class : String.valueOf(type);
//
// Here, 'type' should be one of the following types:
// - RequestContext (or ServiceRequestContext)
// - Request (or HttpRequest)
// - AggregatedHttpMessage
// - HttpParameters
// - User classes which can be converted by request converter
//
// So the container type should be 'null'.
//
types = new SimpleImmutableEntry<>(null, (Class<?>) type);
}
return new AnnotatedValueResolver(annotation, httpElementName, pathVariable, shouldExist,
shouldWrapValueAsOptional, types.getKey(), types.getValue(),
defaultValue, resolver, aggregation);
}
}
private static boolean isFormData(@Nullable MediaType contentType) {
return contentType != null && contentType.belongsTo(MediaType.FORM_DATA);
}
enum AggregationStrategy {
NONE, ALWAYS, FOR_FORM_DATA;
/**
* Returns whether the request should be aggregated.
*/
static boolean aggregationRequired(AggregationStrategy strategy, HttpRequest req) {
requireNonNull(strategy, "strategy");
switch (strategy) {
case ALWAYS:
return true;
case FOR_FORM_DATA:
return isFormData(req.headers().contentType());
}
return false;
}
/**
* Returns {@link AggregationStrategy} which specifies how to aggregate the request
* for injecting its parameters.
*/
static AggregationStrategy from(List<AnnotatedValueResolver> resolvers) {
AggregationStrategy strategy = NONE;
for (final AnnotatedValueResolver r : resolvers) {
switch (r.aggregationStrategy()) {
case ALWAYS:
return ALWAYS;
case FOR_FORM_DATA:
strategy = FOR_FORM_DATA;
break;
}
}
return strategy;
}
}
/**
* A context which is used while resolving parameter values.
*/
static class ResolverContext {
private final ServiceRequestContext context;
private final HttpRequest request;
@Nullable
private final AggregatedHttpMessage message;
@Nullable
private volatile HttpParameters httpParameters;
ResolverContext(ServiceRequestContext context, HttpRequest request,
@Nullable AggregatedHttpMessage message) {
this.context = requireNonNull(context, "context");
this.request = requireNonNull(request, "request");
this.message = message;
}
ServiceRequestContext context() {
return context;
}
HttpRequest request() {
return request;
}
@Nullable
AggregatedHttpMessage message() {
return message;
}
HttpParameters httpParameters() {
HttpParameters result = httpParameters;
if (result == null) {
synchronized (this) {
result = httpParameters;
if (result == null) {
httpParameters = result = httpParametersOf(context.query(),
request.headers().contentType(),
message);
}
}
}
return result;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("context", context)
.add("request", request)
.add("message", message)
.add("httpParameters", httpParameters)
.toString();
}
/**
* Returns a map of parameters decoded from a request.
*
* <p>Usually one of a query string of a URI or URL-encoded form data is specified in the request.
* If both of them exist though, they would be decoded and merged into a parameter map.</p>
*
* <p>Names and values of the parameters would be decoded as UTF-8 character set.</p>
*
* @see QueryStringDecoder#QueryStringDecoder(String, boolean)
* @see HttpConstants#DEFAULT_CHARSET
*/
private static HttpParameters httpParametersOf(@Nullable String query,
@Nullable MediaType contentType,
@Nullable AggregatedHttpMessage message) {
try {
Map<String, List<String>> parameters = null;
if (query != null) {
parameters = new QueryStringDecoder(query, false).parameters();
}
if (message != null && isFormData(contentType)) {
// Respect 'charset' attribute of the 'content-type' header if it exists.
final String body = message.content().toString(
contentType.charset().orElse(StandardCharsets.US_ASCII));
if (!body.isEmpty()) {
final Map<String, List<String>> p =
new QueryStringDecoder(body, false).parameters();
if (parameters == null) {
parameters = p;
} else if (p != null) {
parameters.putAll(p);
}
}
}
if (parameters == null || parameters.isEmpty()) {
return EMPTY_PARAMETERS;
}
return HttpParameters.copyOf(parameters);
} catch (Exception e) {
// If we failed to decode the query string, we ignore the exception raised here.
// A missing parameter might be checked when invoking the annotated method.
logger.debug("Failed to decode query string: {}", query, e);
return EMPTY_PARAMETERS;
}
}
}
private static final class EnumConverter<T extends Enum<T>> {
private final boolean isCaseSensitiveEnum;
private final Map<String, T> enumMap;
/**
* Creates an instance for the given {@link Enum} class.
*/
EnumConverter(Class<T> enumClass) {
final Set<T> enumInstances = EnumSet.allOf(enumClass);
final Map<String, T> lowerCaseEnumMap = enumInstances.stream().collect(
toImmutableMap(e -> Ascii.toLowerCase(e.name()), Function.identity(), (e1, e2) -> e1));
if (enumInstances.size() != lowerCaseEnumMap.size()) {
enumMap = enumInstances.stream().collect(toImmutableMap(Enum::name, Function.identity()));
isCaseSensitiveEnum = true;
} else {
enumMap = lowerCaseEnumMap;
isCaseSensitiveEnum = false;
}
}
/**
* Returns the {@link Enum} value corresponding to the specified {@code str}.
*/
T toEnum(String str) {
final T result = enumMap.get(isCaseSensitiveEnum ? str : Ascii.toLowerCase(str));
if (result != null) {
return result;
}
throw new IllegalArgumentException(
"unknown enum value: " + str + " (expected: " + enumMap.values() + ')');
}
}
/**
* An interface to make a {@link RequestConverterFunction} be adapted for
* {@link AnnotatedValueResolver} internal implementation.
*/
@FunctionalInterface
interface RequestObjectResolver {
static RequestObjectResolver of(RequestConverterFunction function) {
return (resolverContext, expectedResultType, beanFactoryId) -> {
final AggregatedHttpMessage message = resolverContext.message();
if (message == null) {
throw new IllegalArgumentException(
"Cannot convert this request to an object because it is not aggregated.");
}
return function.convertRequest(resolverContext.context(), message, expectedResultType);
};
}
@Nullable
Object convert(ResolverContext resolverContext, Class<?> expectedResultType,
@Nullable BeanFactoryId beanFactoryId) throws Throwable;
}
/**
* A subtype of {@link IllegalArgumentException} which is raised when no annotated parameters exist
* in a constructor or method.
*/
static class NoAnnotatedParameterException extends IllegalArgumentException {
private static final long serialVersionUID = -6003890710456747277L;
NoAnnotatedParameterException(String name) {
super("No annotated parameters found from: " + name);
}
}
/**
* A subtype of {@link NoAnnotatedParameterException} which is raised when no parameters exist in
* a constructor or method.
*/
static class NoParameterException extends NoAnnotatedParameterException {
private static final long serialVersionUID = 3390292442571367102L;
NoParameterException(String name) {
super("No parameters found from: " + name);
}
}
}
| apache-2.0 |
philliprower/cas | core/cas-server-core-tickets/src/test/java/org/apereo/cas/ticket/expiration/HardTimeoutExpirationPolicyTests.java | 965 | package org.apereo.cas.ticket.expiration;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.val;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author Misagh Moayyed
* @since 4.1
*/
public class HardTimeoutExpirationPolicyTests {
private static final File JSON_FILE = new File(FileUtils.getTempDirectoryPath(), "hardTimeoutExpirationPolicy.json");
private static final ObjectMapper MAPPER = new ObjectMapper().findAndRegisterModules();
@Test
public void verifySerializeANeverExpiresExpirationPolicyToJson() throws IOException {
val policyWritten = new HardTimeoutExpirationPolicy();
MAPPER.writeValue(JSON_FILE, policyWritten);
val policyRead = MAPPER.readValue(JSON_FILE, HardTimeoutExpirationPolicy.class);
assertEquals(policyWritten, policyRead);
}
}
| apache-2.0 |
robsoncardosoti/flowable-engine | modules/flowable-engine/src/test/java/org/flowable/engine/test/bpmn/servicetask/CreateUserAndMembershipTestDelegate.java | 2078 | /* 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.engine.test.bpmn.servicetask;
import org.flowable.engine.IdentityService;
import org.flowable.engine.ManagementService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.flowable.engine.impl.context.Context;
import org.flowable.engine.impl.interceptor.Command;
import org.flowable.engine.impl.interceptor.CommandContext;
import org.flowable.idm.api.Group;
import org.flowable.idm.api.User;
/**
* @author Joram Barrez
*/
public class CreateUserAndMembershipTestDelegate implements JavaDelegate {
@Override
public void execute(DelegateExecution execution) {
ManagementService managementService = Context.getProcessEngineConfiguration().getManagementService();
managementService.executeCommand(new Command<Void>() {
@Override
public Void execute(CommandContext commandContext) {
return null;
}
});
IdentityService identityService = Context.getProcessEngineConfiguration().getIdentityService();
String username = "Kermit";
User user = identityService.newUser(username);
user.setPassword("123");
user.setFirstName("Manually");
user.setLastName("created");
identityService.saveUser(user);
// Add admin group
Group group = identityService.newGroup("admin");
identityService.saveGroup(group);
identityService.createMembership(username, "admin");
}
}
| apache-2.0 |
cexbrayat/camel | camel-core/src/test/java/org/apache/camel/processor/RecipientListBeanTest.java | 2243 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.processor;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.JndiRegistry;
/**
* @version
*/
public class RecipientListBeanTest extends ContextTestSupport {
@Override
protected JndiRegistry createRegistry() throws Exception {
JndiRegistry jndi = super.createRegistry();
jndi.bind("myBean", new MyBean());
return jndi;
}
public void testRecipientListWithBean() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Hello c");
String out = template.requestBody("direct:start", "direct:a,direct:b,direct:c", String.class);
assertEquals("Hello c", out);
assertMockEndpointsSatisfied();
}
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:start").recipientList(bean("myBean", "foo")).to("mock:result");
from("direct:a").transform(constant("Hello a"));
from("direct:b").transform(constant("Hello b"));
from("direct:c").transform(constant("Hello c"));
}
};
}
public class MyBean {
public String[] foo(String body) {
return body.split(",");
}
}
} | apache-2.0 |
mehdi149/OF_COMPILER_0.1 | gen-src/main/java/org/projectfloodlight/openflow/protocol/ver15/OFTableDescStatsRequestVer15.java | 11425 | // Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_class.java
// Do not modify
package org.projectfloodlight.openflow.protocol.ver15;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;
class OFTableDescStatsRequestVer15 implements OFTableDescStatsRequest {
private static final Logger logger = LoggerFactory.getLogger(OFTableDescStatsRequestVer15.class);
// version: 1.5
final static byte WIRE_VERSION = 6;
final static int LENGTH = 16;
private final static long DEFAULT_XID = 0x0L;
private final static Set<OFStatsRequestFlags> DEFAULT_FLAGS = ImmutableSet.<OFStatsRequestFlags>of();
// OF message fields
private final long xid;
private final Set<OFStatsRequestFlags> flags;
//
// Immutable default instance
final static OFTableDescStatsRequestVer15 DEFAULT = new OFTableDescStatsRequestVer15(
DEFAULT_XID, DEFAULT_FLAGS
);
// package private constructor - used by readers, builders, and factory
OFTableDescStatsRequestVer15(long xid, Set<OFStatsRequestFlags> flags) {
if(flags == null) {
throw new NullPointerException("OFTableDescStatsRequestVer15: property flags cannot be null");
}
this.xid = xid;
this.flags = flags;
}
// Accessors for OF message fields
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
@Override
public OFType getType() {
return OFType.STATS_REQUEST;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFStatsType getStatsType() {
return OFStatsType.TABLE_DESC;
}
@Override
public Set<OFStatsRequestFlags> getFlags() {
return flags;
}
public OFTableDescStatsRequest.Builder createBuilder() {
return new BuilderWithParent(this);
}
static class BuilderWithParent implements OFTableDescStatsRequest.Builder {
final OFTableDescStatsRequestVer15 parentMessage;
// OF message fields
private boolean xidSet;
private long xid;
private boolean flagsSet;
private Set<OFStatsRequestFlags> flags;
BuilderWithParent(OFTableDescStatsRequestVer15 parentMessage) {
this.parentMessage = parentMessage;
}
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
@Override
public OFType getType() {
return OFType.STATS_REQUEST;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFTableDescStatsRequest.Builder setXid(long xid) {
this.xid = xid;
this.xidSet = true;
return this;
}
@Override
public OFStatsType getStatsType() {
return OFStatsType.TABLE_DESC;
}
@Override
public Set<OFStatsRequestFlags> getFlags() {
return flags;
}
@Override
public OFTableDescStatsRequest.Builder setFlags(Set<OFStatsRequestFlags> flags) {
this.flags = flags;
this.flagsSet = true;
return this;
}
@Override
public OFTableDescStatsRequest build() {
long xid = this.xidSet ? this.xid : parentMessage.xid;
Set<OFStatsRequestFlags> flags = this.flagsSet ? this.flags : parentMessage.flags;
if(flags == null)
throw new NullPointerException("Property flags must not be null");
//
return new OFTableDescStatsRequestVer15(
xid,
flags
);
}
}
static class Builder implements OFTableDescStatsRequest.Builder {
// OF message fields
private boolean xidSet;
private long xid;
private boolean flagsSet;
private Set<OFStatsRequestFlags> flags;
@Override
public OFVersion getVersion() {
return OFVersion.OF_15;
}
@Override
public OFType getType() {
return OFType.STATS_REQUEST;
}
@Override
public long getXid() {
return xid;
}
@Override
public OFTableDescStatsRequest.Builder setXid(long xid) {
this.xid = xid;
this.xidSet = true;
return this;
}
@Override
public OFStatsType getStatsType() {
return OFStatsType.TABLE_DESC;
}
@Override
public Set<OFStatsRequestFlags> getFlags() {
return flags;
}
@Override
public OFTableDescStatsRequest.Builder setFlags(Set<OFStatsRequestFlags> flags) {
this.flags = flags;
this.flagsSet = true;
return this;
}
//
@Override
public OFTableDescStatsRequest build() {
long xid = this.xidSet ? this.xid : DEFAULT_XID;
Set<OFStatsRequestFlags> flags = this.flagsSet ? this.flags : DEFAULT_FLAGS;
if(flags == null)
throw new NullPointerException("Property flags must not be null");
return new OFTableDescStatsRequestVer15(
xid,
flags
);
}
}
final static Reader READER = new Reader();
static class Reader implements OFMessageReader<OFTableDescStatsRequest> {
@Override
public OFTableDescStatsRequest readFrom(ByteBuf bb) throws OFParseError {
int start = bb.readerIndex();
// fixed value property version == 6
byte version = bb.readByte();
if(version != (byte) 0x6)
throw new OFParseError("Wrong version: Expected=OFVersion.OF_15(6), got="+version);
// fixed value property type == 18
byte type = bb.readByte();
if(type != (byte) 0x12)
throw new OFParseError("Wrong type: Expected=OFType.STATS_REQUEST(18), got="+type);
int length = U16.f(bb.readShort());
if(length != 16)
throw new OFParseError("Wrong length: Expected=16(16), got="+length);
if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
// Buffer does not have all data yet
bb.readerIndex(start);
return null;
}
if(logger.isTraceEnabled())
logger.trace("readFrom - length={}", length);
long xid = U32.f(bb.readInt());
// fixed value property statsType == 14
short statsType = bb.readShort();
if(statsType != (short) 0xe)
throw new OFParseError("Wrong statsType: Expected=OFStatsType.TABLE_DESC(14), got="+statsType);
Set<OFStatsRequestFlags> flags = OFStatsRequestFlagsSerializerVer15.readFrom(bb);
// pad: 4 bytes
bb.skipBytes(4);
OFTableDescStatsRequestVer15 tableDescStatsRequestVer15 = new OFTableDescStatsRequestVer15(
xid,
flags
);
if(logger.isTraceEnabled())
logger.trace("readFrom - read={}", tableDescStatsRequestVer15);
return tableDescStatsRequestVer15;
}
}
public void putTo(PrimitiveSink sink) {
FUNNEL.funnel(this, sink);
}
final static OFTableDescStatsRequestVer15Funnel FUNNEL = new OFTableDescStatsRequestVer15Funnel();
static class OFTableDescStatsRequestVer15Funnel implements Funnel<OFTableDescStatsRequestVer15> {
private static final long serialVersionUID = 1L;
@Override
public void funnel(OFTableDescStatsRequestVer15 message, PrimitiveSink sink) {
// fixed value property version = 6
sink.putByte((byte) 0x6);
// fixed value property type = 18
sink.putByte((byte) 0x12);
// fixed value property length = 16
sink.putShort((short) 0x10);
sink.putLong(message.xid);
// fixed value property statsType = 14
sink.putShort((short) 0xe);
OFStatsRequestFlagsSerializerVer15.putTo(message.flags, sink);
// skip pad (4 bytes)
}
}
public void writeTo(ByteBuf bb) {
WRITER.write(bb, this);
}
final static Writer WRITER = new Writer();
static class Writer implements OFMessageWriter<OFTableDescStatsRequestVer15> {
@Override
public void write(ByteBuf bb, OFTableDescStatsRequestVer15 message) {
// fixed value property version = 6
bb.writeByte((byte) 0x6);
// fixed value property type = 18
bb.writeByte((byte) 0x12);
// fixed value property length = 16
bb.writeShort((short) 0x10);
bb.writeInt(U32.t(message.xid));
// fixed value property statsType = 14
bb.writeShort((short) 0xe);
OFStatsRequestFlagsSerializerVer15.writeTo(bb, message.flags);
// pad: 4 bytes
bb.writeZero(4);
}
}
@Override
public String toString() {
StringBuilder b = new StringBuilder("OFTableDescStatsRequestVer15(");
b.append("xid=").append(xid);
b.append(", ");
b.append("flags=").append(flags);
b.append(")");
return b.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFTableDescStatsRequestVer15 other = (OFTableDescStatsRequestVer15) obj;
if( xid != other.xid)
return false;
if (flags == null) {
if (other.flags != null)
return false;
} else if (!flags.equals(other.flags))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * (int) (xid ^ (xid >>> 32));
result = prime * result + ((flags == null) ? 0 : flags.hashCode());
return result;
}
}
| apache-2.0 |
prabushi/devstudio-tooling-esb | plugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src/org/wso2/developerstudio/eclipse/gmf/esb/provider/EndPointPropertyItemProvider.java | 11996 | /**
* Copyright 2009-2012 WSO2, Inc. (http://wso2.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.eclipse.gmf.esb.provider;
import java.util.Collection;
import java.util.List;
import org.apache.commons.lang.WordUtils;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.util.ResourceLocator;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ItemProviderAdapter;
import org.eclipse.emf.edit.provider.ViewerNotification;
import org.wso2.developerstudio.eclipse.gmf.esb.EndPointProperty;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbFactory;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage;
import org.wso2.developerstudio.eclipse.gmf.esb.PropertyValueType;
import org.wso2.developerstudio.eclipse.gmf.esb.presentation.EEFPropertyViewUtil;
/**
* This is the item provider adapter for a {@link org.wso2.developerstudio.eclipse.gmf.esb.EndPointProperty} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class EndPointPropertyItemProvider extends ItemProviderAdapter implements IEditingDomainItemProvider,
IStructuredItemContentProvider, ITreeItemContentProvider, IItemLabelProvider, IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EndPointPropertyItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
addNamePropertyDescriptor(object);
addValuePropertyDescriptor(object);
addScopePropertyDescriptor(object);
addValueTypePropertyDescriptor(object);
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the Name feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addNamePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_EndPointProperty_name_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_EndPointProperty_name_feature", "_UI_EndPointProperty_type"),
EsbPackage.Literals.END_POINT_PROPERTY__NAME,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Value feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addValuePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_EndPointProperty_value_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_EndPointProperty_value_feature", "_UI_EndPointProperty_type"),
EsbPackage.Literals.END_POINT_PROPERTY__VALUE,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Scope feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addScopePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_EndPointProperty_scope_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_EndPointProperty_scope_feature", "_UI_EndPointProperty_type"),
EsbPackage.Literals.END_POINT_PROPERTY__SCOPE,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the Value Type feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addValueTypePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_EndPointProperty_valueType_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_EndPointProperty_valueType_feature", "_UI_EndPointProperty_type"),
EsbPackage.Literals.END_POINT_PROPERTY__VALUE_TYPE,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
/**
* This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an
* {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or
* {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) {
if (childrenFeatures == null) {
super.getChildrenFeatures(object);
childrenFeatures.add(EsbPackage.Literals.END_POINT_PROPERTY__VALUE_EXPRESSION);
}
return childrenFeatures;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EStructuralFeature getChildFeature(Object object, Object child) {
// Check the type of the specified child object and return the proper feature to use for
// adding (see {@link AddCommand}) it as a child.
return super.getChildFeature(object, child);
}
/**
* This returns EndPointProperty.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/EndPointProperty"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
@Override
public String getText(Object object) {
String propertyName = ((EndPointProperty) object).getName();
String propertyNameLabel = WordUtils.abbreviate(propertyName, 40, 45, " ...");
String propertyValueType = ((EndPointProperty) object).getValueType().toString();
String propertyValue = ((EndPointProperty) object).getValue();
String valueExpression = ((EndPointProperty) object).getValueExpression().toString();
if (propertyValueType.equalsIgnoreCase(PropertyValueType.LITERAL.getName())) {
if (((EndPointProperty) object).getValue() != null) {
return propertyName == null || propertyName.length() == 0 ? getString("_UI_EndPointProperty_type")
: getString("_UI_EndPointProperty_type") + " - "
+ EEFPropertyViewUtil.spaceFormat(propertyNameLabel)
+ EEFPropertyViewUtil.spaceFormat(propertyValue);
} else {
return propertyName == null || propertyName.length() == 0 ? getString("_UI_EndPointProperty_type")
: getString("_UI_EndPointProperty_type") + " - "
+ EEFPropertyViewUtil.spaceFormat(propertyNameLabel);
}
} else {
return propertyName == null || propertyName.length() == 0 ? getString("_UI_EndPointProperty_type")
: getString("_UI_EndPointProperty_type") + " - "
+ EEFPropertyViewUtil.spaceFormat(propertyNameLabel)
+ EEFPropertyViewUtil.spaceFormat(valueExpression);
}
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(EndPointProperty.class)) {
case EsbPackage.END_POINT_PROPERTY__NAME:
case EsbPackage.END_POINT_PROPERTY__VALUE:
case EsbPackage.END_POINT_PROPERTY__SCOPE:
case EsbPackage.END_POINT_PROPERTY__VALUE_TYPE:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
case EsbPackage.END_POINT_PROPERTY__VALUE_EXPRESSION:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
newChildDescriptors.add
(createChildParameter
(EsbPackage.Literals.END_POINT_PROPERTY__VALUE_EXPRESSION,
EsbFactory.eINSTANCE.createNamespacedProperty()));
}
/**
* Return the resource locator for this item provider's resources.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ResourceLocator getResourceLocator() {
return EsbEditPlugin.INSTANCE;
}
}
| apache-2.0 |
mehdi149/OF_COMPILER_0.1 | gen-src/main/java/org/projectfloodlight/openflow/protocol/bsntlv/OFBsnTlvExternalGatewayMac.java | 1862 | // Copyright (c) 2008 The Board of Trustees of The Leland Stanford Junior University
// Copyright (c) 2011, 2012 Open Networking Foundation
// Copyright (c) 2012, 2013 Big Switch Networks, Inc.
// This library was generated by the LoxiGen Compiler.
// See the file LICENSE.txt which should have been included in the source distribution
// Automatically generated by LOXI from template of_interface.java
// Do not modify
package org.projectfloodlight.openflow.protocol.bsntlv;
import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import io.netty.buffer.ByteBuf;
public interface OFBsnTlvExternalGatewayMac extends OFObject, OFBsnTlv {
int getType();
MacAddress getValue();
OFVersion getVersion();
void writeTo(ByteBuf channelBuffer);
Builder createBuilder();
public interface Builder extends OFBsnTlv.Builder {
OFBsnTlvExternalGatewayMac build();
int getType();
MacAddress getValue();
Builder setValue(MacAddress value);
OFVersion getVersion();
}
}
| apache-2.0 |
NLPchina/ansj_seg | plugin/ansj_lucene6_plugin/src/test/java/org/ansj/ansj_lucene_plug/IndexAndTest.java | 4074 | package org.ansj.ansj_lucene_plug;
import org.ansj.domain.Term;
import org.ansj.library.DicLibrary;
import org.ansj.lucene6.AnsjAnalyzer;
import org.ansj.lucene6.AnsjAnalyzer.TYPE;
import org.ansj.splitWord.analysis.IndexAnalysis;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.*;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.junit.Test;
import java.io.IOException;
import java.io.StringReader;
public class IndexAndTest {
@Test
public void test() throws Exception {
DicLibrary.put(DicLibrary.DEFAULT, "../../library/default.dic");
PerFieldAnalyzerWrapper analyzer = new PerFieldAnalyzerWrapper(new AnsjAnalyzer(TYPE.index_ansj));
Directory directory = null;
IndexWriter iwriter = null;
IndexWriterConfig ic = new IndexWriterConfig(analyzer);
String text = "旅游和服务是最好的";
System.out.println(IndexAnalysis.parse(text));
// 建立内存索引对象
directory = new RAMDirectory();
iwriter = new IndexWriter(directory, ic);
addContent(iwriter, text);
iwriter.commit();
iwriter.close();
System.out.println("索引建立完毕");
Analyzer queryAnalyzer = new AnsjAnalyzer(AnsjAnalyzer.TYPE.index_ansj);
System.out.println("index ok to search!");
for (Term t : IndexAnalysis.parse(text)) {
System.out.println(t.getName());
search(queryAnalyzer, directory, "\"" + t.getName() + "\"");
}
}
private void search(Analyzer queryAnalyzer, Directory directory, String queryStr) throws CorruptIndexException, IOException, ParseException {
IndexSearcher isearcher;
DirectoryReader directoryReader = DirectoryReader.open(directory);
// 查询索引
isearcher = new IndexSearcher(directoryReader);
QueryParser tq = new QueryParser("text", queryAnalyzer);
Query query = tq.parse(queryStr);
System.out.println(query);
TopDocs hits = isearcher.search(query, 5);
System.out.println(queryStr + ":共找到" + hits.totalHits + "条记录!");
for (int i = 0; i < hits.scoreDocs.length; i++) {
int docId = hits.scoreDocs[i].doc;
Document document = isearcher.doc(docId);
System.out.println(toHighlighter(queryAnalyzer, query, document));
}
}
private void addContent(IndexWriter iwriter, String text) throws CorruptIndexException, IOException {
Document doc = new Document();
IndexableField field = new TextField("text", text, Store.YES);
doc.add(field);
iwriter.addDocument(doc);
}
/**
* 高亮设置
*
* @param query
* @param doc
* @param field
* @return
*/
private String toHighlighter(Analyzer analyzer, Query query, Document doc) {
String field = "text";
try {
SimpleHTMLFormatter simpleHtmlFormatter = new SimpleHTMLFormatter("<font color=\"red\">", "</font>");
Highlighter highlighter = new Highlighter(simpleHtmlFormatter, new QueryScorer(query));
TokenStream tokenStream1 = analyzer.tokenStream("text", new StringReader(doc.get(field)));
String highlighterStr = highlighter.getBestFragment(tokenStream1, doc.get(field));
return highlighterStr == null ? doc.get(field) : highlighterStr;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidTokenOffsetsException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
| apache-2.0 |
pnowojski/presto | presto-main/src/main/java/com/facebook/presto/operator/MultiChannelGroupByHash.java | 13353 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.PageBuilder;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.gen.JoinCompiler;
import com.facebook.presto.util.array.LongBigArray;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static com.facebook.presto.operator.SyntheticAddress.decodePosition;
import static com.facebook.presto.operator.SyntheticAddress.decodeSliceIndex;
import static com.facebook.presto.operator.SyntheticAddress.encodeSyntheticAddress;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.sql.gen.JoinCompiler.PagesHashStrategyFactory;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.airlift.slice.SizeOf.sizeOf;
import static it.unimi.dsi.fastutil.HashCommon.arraySize;
import static it.unimi.dsi.fastutil.HashCommon.murmurHash3;
// This implementation assumes arrays used in the hash are always a power of 2
public class MultiChannelGroupByHash
implements GroupByHash
{
private static final JoinCompiler JOIN_COMPILER = new JoinCompiler();
private static final float FILL_RATIO = 0.9f;
private final List<Type> types;
private final int[] channels;
private final PagesHashStrategy hashStrategy;
private final List<ObjectArrayList<Block>> channelBuilders;
private final HashGenerator hashGenerator;
private final Optional<Integer> precomputedHashChannel;
private PageBuilder currentPageBuilder;
private long completedPagesMemorySize;
private int maxFill;
private int mask;
private long[] key;
private int[] value;
private final LongBigArray groupAddress;
private int nextGroupId;
public MultiChannelGroupByHash(List<? extends Type> hashTypes, int[] hashChannels, Optional<Integer> inputHashChannel, int expectedSize)
{
checkNotNull(hashTypes, "hashTypes is null");
checkArgument(hashTypes.size() == hashChannels.length, "hashTypes and hashChannels have different sizes");
checkNotNull(inputHashChannel, "inputHashChannel is null");
checkArgument(expectedSize > 0, "expectedSize must be greater than zero");
this.types = inputHashChannel.isPresent() ? ImmutableList.copyOf(Iterables.concat(hashTypes, ImmutableList.of(BIGINT))) : ImmutableList.copyOf(hashTypes);
this.channels = checkNotNull(hashChannels, "hashChannels is null").clone();
this.hashGenerator = inputHashChannel.isPresent() ? new PrecomputedHashGenerator(inputHashChannel.get()) : new InterpretedHashGenerator(ImmutableList.copyOf(hashTypes), hashChannels);
// For each hashed channel, create an appendable list to hold the blocks (builders). As we
// add new values we append them to the existing block builder until it fills up and then
// we add a new block builder to each list.
ImmutableList.Builder<Integer> outputChannels = ImmutableList.builder();
ImmutableList.Builder<ObjectArrayList<Block>> channelBuilders = ImmutableList.builder();
for (int i = 0; i < hashChannels.length; i++) {
outputChannels.add(i);
channelBuilders.add(ObjectArrayList.wrap(new Block[1024], 0));
}
if (inputHashChannel.isPresent()) {
this.precomputedHashChannel = Optional.of(hashChannels.length);
channelBuilders.add(ObjectArrayList.wrap(new Block[1024], 0));
}
else {
this.precomputedHashChannel = Optional.empty();
}
this.channelBuilders = channelBuilders.build();
PagesHashStrategyFactory pagesHashStrategyFactory = JOIN_COMPILER.compilePagesHashStrategyFactory(this.types, outputChannels.build());
hashStrategy = pagesHashStrategyFactory.createPagesHashStrategy(this.channelBuilders, this.precomputedHashChannel);
startNewPage();
// reserve memory for the arrays
int hashSize = arraySize(expectedSize, FILL_RATIO);
maxFill = calculateMaxFill(hashSize);
mask = hashSize - 1;
key = new long[hashSize];
Arrays.fill(key, -1);
value = new int[hashSize];
groupAddress = new LongBigArray();
groupAddress.ensureCapacity(maxFill);
}
@Override
public long getEstimatedSize()
{
return (sizeOf(channelBuilders.get(0).elements()) * channelBuilders.size()) +
completedPagesMemorySize +
currentPageBuilder.getSizeInBytes() +
sizeOf(key) +
sizeOf(value) +
groupAddress.sizeOf();
}
@Override
public List<Type> getTypes()
{
return types;
}
@Override
public int getGroupCount()
{
return nextGroupId;
}
@Override
public void appendValuesTo(int groupId, PageBuilder pageBuilder, int outputChannelOffset)
{
long address = groupAddress.get(groupId);
int blockIndex = decodeSliceIndex(address);
int position = decodePosition(address);
hashStrategy.appendTo(blockIndex, position, pageBuilder, outputChannelOffset);
}
@Override
public void addPage(Page page)
{
Block[] hashBlocks = extractHashColumns(page);
// get the group id for each position
int positionCount = page.getPositionCount();
for (int position = 0; position < positionCount; position++) {
// get the group for the current row
putIfAbsent(position, page, hashBlocks);
}
}
@Override
public GroupByIdBlock getGroupIds(Page page)
{
int positionCount = page.getPositionCount();
// we know the exact size required for the block
BlockBuilder blockBuilder = BIGINT.createFixedSizeBlockBuilder(positionCount);
// extract the hash columns
Block[] hashBlocks = extractHashColumns(page);
// get the group id for each position
for (int position = 0; position < positionCount; position++) {
// get the group for the current row
int groupId = putIfAbsent(position, page, hashBlocks);
// output the group id for this row
BIGINT.writeLong(blockBuilder, groupId);
}
return new GroupByIdBlock(nextGroupId, blockBuilder.build());
}
@Override
public boolean contains(int position, Page page)
{
int rawHash = hashStrategy.hashRow(position, page.getBlocks());
int hashPosition = getHashPosition(rawHash, mask);
// look for a slot containing this key
while (key[hashPosition] != -1) {
long address = key[hashPosition];
if (hashStrategy.positionEqualsRow(decodeSliceIndex(address), decodePosition(address), position, page.getBlocks())) {
// found an existing slot for this key
return true;
}
// increment position and mask to handle wrap around
hashPosition = (hashPosition + 1) & mask;
}
return false;
}
@Override
public int putIfAbsent(int position, Page page)
{
return putIfAbsent(position, page, extractHashColumns(page));
}
private int putIfAbsent(int position, Page page, Block[] hashBlocks)
{
int rawHash = hashGenerator.hashPosition(position, page);
int hashPosition = getHashPosition(rawHash, mask);
// look for an empty slot or a slot containing this key
int groupId = -1;
while (key[hashPosition] != -1) {
long address = key[hashPosition];
if (positionEqualsCurrentRow(decodeSliceIndex(address), decodePosition(address), position, hashBlocks)) {
// found an existing slot for this key
groupId = value[hashPosition];
break;
}
// increment position and mask to handle wrap around
hashPosition = (hashPosition + 1) & mask;
}
// did we find an existing group?
if (groupId < 0) {
groupId = addNewGroup(hashPosition, position, page, rawHash);
}
return groupId;
}
private int addNewGroup(int hashPosition, int position, Page page, int rawHash)
{
// add the row to the open page
Block[] blocks = page.getBlocks();
for (int i = 0; i < channels.length; i++) {
int hashChannel = channels[i];
Type type = types.get(i);
type.appendTo(blocks[hashChannel], position, currentPageBuilder.getBlockBuilder(i));
}
if (precomputedHashChannel.isPresent()) {
BIGINT.writeLong(currentPageBuilder.getBlockBuilder(precomputedHashChannel.get()), rawHash);
}
currentPageBuilder.declarePosition();
int pageIndex = channelBuilders.get(0).size() - 1;
int pagePosition = currentPageBuilder.getPositionCount() - 1;
long address = encodeSyntheticAddress(pageIndex, pagePosition);
// record group id in hash
int groupId = nextGroupId++;
key[hashPosition] = address;
value[hashPosition] = groupId;
groupAddress.set(groupId, address);
// create new page builder if this page is full
if (currentPageBuilder.isFull()) {
startNewPage();
}
// increase capacity, if necessary
if (nextGroupId >= maxFill) {
rehash(maxFill * 2);
}
return groupId;
}
private void startNewPage()
{
if (currentPageBuilder != null) {
completedPagesMemorySize += currentPageBuilder.getSizeInBytes();
}
currentPageBuilder = new PageBuilder(types);
for (int i = 0; i < types.size(); i++) {
channelBuilders.get(i).add(currentPageBuilder.getBlockBuilder(i));
}
}
private void rehash(int size)
{
int newSize = arraySize(size + 1, FILL_RATIO);
int newMask = newSize - 1;
long[] newKey = new long[newSize];
Arrays.fill(newKey, -1);
int[] newValue = new int[newSize];
int oldIndex = 0;
for (int groupId = 0; groupId < nextGroupId; groupId++) {
// seek to the next used slot
while (key[oldIndex] == -1) {
oldIndex++;
}
// get the address for this slot
long address = key[oldIndex];
// find an empty slot for the address
int pos = getHashPosition(hashPosition(address), newMask);
while (newKey[pos] != -1) {
pos = (pos + 1) & newMask;
}
// record the mapping
newKey[pos] = address;
newValue[pos] = value[oldIndex];
oldIndex++;
}
this.mask = newMask;
this.maxFill = calculateMaxFill(newSize);
this.key = newKey;
this.value = newValue;
groupAddress.ensureCapacity(maxFill);
}
private Block[] extractHashColumns(Page page)
{
Block[] hashBlocks = new Block[channels.length];
for (int i = 0; i < channels.length; i++) {
hashBlocks[i] = page.getBlock(channels[i]);
}
return hashBlocks;
}
private int hashPosition(long sliceAddress)
{
int sliceIndex = decodeSliceIndex(sliceAddress);
int position = decodePosition(sliceAddress);
if (precomputedHashChannel.isPresent()) {
return getRawHash(sliceIndex, position);
}
return hashStrategy.hashPosition(sliceIndex, position);
}
private int getRawHash(int sliceIndex, int position)
{
return (int) channelBuilders.get(precomputedHashChannel.get()).get(sliceIndex).getLong(position, 0);
}
private boolean positionEqualsCurrentRow(int sliceIndex, int slicePosition, int position, Block[] blocks)
{
return hashStrategy.positionEqualsRow(sliceIndex, slicePosition, position, blocks);
}
private static int getHashPosition(int rawHash, int mask)
{
return murmurHash3(rawHash) & mask;
}
private static int calculateMaxFill(int hashSize)
{
checkArgument(hashSize > 0, "hashSize must greater than 0");
int maxFill = (int) Math.ceil(hashSize * FILL_RATIO);
if (maxFill == hashSize) {
maxFill--;
}
checkArgument(hashSize > maxFill, "hashSize must be larger than maxFill");
return maxFill;
}
}
| apache-2.0 |
jfoenixadmin/JFoenix | demo/src/main/java/demos/components/DatePickerDemo.java | 2537 | /*
* JFoenix
* Copyright (c) 2015, JFoenix and/or its affiliates., All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
*/
package demos.components;
import com.jfoenix.controls.JFXDatePicker;
import com.jfoenix.controls.JFXTimePicker;
import demos.MainDemo;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.DatePicker;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class DatePickerDemo extends Application {
@Override
public void start(Stage stage) {
FlowPane main = new FlowPane();
main.setVgap(20);
main.setHgap(20);
DatePicker datePicker = new DatePicker();
main.getChildren().add(datePicker);
JFXDatePicker datePickerFX = new JFXDatePicker();
main.getChildren().add(datePickerFX);
datePickerFX.setPromptText("pick a date");
JFXTimePicker blueDatePicker = new JFXTimePicker();
blueDatePicker.setDefaultColor(Color.valueOf("#3f51b5"));
blueDatePicker.setOverLay(true);
main.getChildren().add(blueDatePicker);
StackPane pane = new StackPane();
pane.getChildren().add(main);
StackPane.setMargin(main, new Insets(100));
pane.setStyle("-fx-background-color:WHITE");
final Scene scene = new Scene(pane, 400, 700);
final ObservableList<String> stylesheets = scene.getStylesheets();
stylesheets.addAll(MainDemo.class.getResource("/css/jfoenix-fonts.css").toExternalForm(),
MainDemo.class.getResource("/css/jfoenix-design.css").toExternalForm());
stage.setTitle("JFX Date Picker Demo");
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
| apache-2.0 |
welterde/ewok | com/planet_ink/coffee_mud/Abilities/Spells/Spell_Blademouth.java | 4439 | package com.planet_ink.coffee_mud.Abilities.Spells;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2010 Bo Zimmerman
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.
*/
@SuppressWarnings("unchecked")
public class Spell_Blademouth extends Spell
{
public String ID() { return "Spell_Blademouth"; }
public String name(){return "Blademouth";}
public String displayText(){return "(blades in your mouth)";}
public int abstractQuality(){return Ability.QUALITY_MALICIOUS;}
protected int canAffectCode(){return CAN_MOBS;}
public int classificationCode(){ return Ability.ACODE_SPELL|Ability.DOMAIN_EVOCATION;}
public Vector limbsToRemove=new Vector();
protected boolean noRecurse=false;
public void executeMsg(Environmental host, CMMsg msg)
{
if((msg.sourceMinor()==CMMsg.TYP_SPEAK)
&&(!noRecurse)
&&(affected instanceof MOB)
&&(invoker!=null)
&&(msg.amISource((MOB)affected))
&&(msg.source().location()!=null)
&&(msg.source().charStats().getMyRace().bodyMask()[Race.BODY_MOUTH]>=0))
{
noRecurse=true;
try{CMLib.combat().postDamage(invoker,msg.source(),this,msg.source().maxState().getHitPoints()/10,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,Weapon.TYPE_SLASHING,"The blades in <T-YOUPOSS> mouth <DAMAGE> <T-HIM-HER>!");
}finally{noRecurse=false;}
}
super.executeMsg(host,msg);
}
public int castingQuality(MOB mob, Environmental target)
{
if(mob!=null)
{
if(target instanceof MOB)
{
if(((MOB)target).charStats().getMyRace().bodyMask()[Race.BODY_MOUTH]<=0)
return Ability.QUALITY_INDIFFERENT;
}
}
return super.castingQuality(mob,target);
}
public boolean invoke(MOB mob, Vector commands, Environmental givenTarget, boolean auto, int asLevel)
{
MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null) return false;
if(target.charStats().getMyRace().bodyMask()[Race.BODY_MOUTH]<=0)
{
if(!auto)
mob.tell("There is no mouth on "+target.name()+" to fill with blades!");
return false;
}
// the invoke method for spells receives as
// parameters the invoker, and the REMAINING
// command line parameters, divided into words,
// and added as String objects to a vector.
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
// now see if it worked
boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
// it worked, so build a copy of this ability,
// and add it to the affects list of the
// affected MOB. Then tell everyone else
// what happened.
CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),(auto?"!":"^S<S-NAME> invoke(s) a sharp spell upon <T-NAMESELF>"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
super.maliciousAffect(mob,target,asLevel,0,-1);
}
}
else
return maliciousFizzle(mob,target,"<S-NAME> incant(s) sharply at <T-NAMESELF>, but flub(s) the spell.");
// return whether it worked
return success;
}
}
| apache-2.0 |
pjworkspace/wscs | weixin-sdk/src/main/java/com/weixin/sdk/msg/in/event/InCustomEvent.java | 2179 | /**
* Copyright (c) 2011-2015, Unas 小强哥 (unas@qq.com).
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.weixin.sdk.msg.in.event;
/**
接入会话:
<xml>
<ToUserName><![CDATA[touser]]></ToUserName>
<FromUserName><![CDATA[fromuser]]></FromUserName>
<CreateTime>1399197672</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[kf_create_session]]></Event>
<KfAccount><![CDATA[test1@test]]></KfAccount>
</xml>
关闭会话:
<xml>
<ToUserName><![CDATA[touser]]></ToUserName>
<FromUserName><![CDATA[fromuser]]></FromUserName>
<CreateTime>1399197672</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[kf_close_session]]></Event>
<KfAccount><![CDATA[test1@test]]></KfAccount>
</xml>
转接会话:
<xml>
<ToUserName><![CDATA[touser]]></ToUserName>
<FromUserName><![CDATA[fromuser]]></FromUserName>
<CreateTime>1399197672</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[kf_switch_session]]></Event>
<FromKfAccount><![CDATA[test1@test]]></FromKfAccount>
<ToKfAccount><![CDATA[test2@test]]></ToKfAccount>
</xml>
*/
public class InCustomEvent extends EventInMsg
{
// 接入会话:kf_create_session
public static final String EVENT_INCUSTOM_KF_CREATE_SESSION = "kf_create_session";
// 关闭会话:kf_close_session
public static final String EVENT_INCUSTOM_KF_CLOSE_SESSION = "kf_close_session";
// 转接会话:kf_switch_session
public static final String EVENT_INCUSTOM_KF_SWITCH_SESSION = "kf_switch_session";
private String kfAccount;
private String toKfAccount;
public InCustomEvent(String toUserName, String fromUserName, Integer createTime, String msgType, String event)
{
super(toUserName, fromUserName, createTime, msgType, event);
}
public String getKfAccount()
{
return kfAccount;
}
public void setKfAccount(String kfAccount)
{
this.kfAccount = kfAccount;
}
public String getToKfAccount()
{
return toKfAccount;
}
public void setToKfAccount(String toKfAccount)
{
this.toKfAccount = toKfAccount;
}
}
| apache-2.0 |
Juklabs/edmundo | insert.java | 757 | import greenfoot.*;
public class insert extends Actor
{
pause p = new pause();
player pa = new player();
GreenfootSound SFX2 = new GreenfootSound("sfx/button_click.mp3");
public void act()
{
setLocation(550, 275);
if(Greenfoot.isKeyDown("escape"))
{
SFX2.play();
getWorld().removeObjects(getWorld().getObjects(insert.class));
p.setPaused(false);
}
if(Greenfoot.isKeyDown("enter"))
{
SFX2.play();
if(pa.getKey() && getWorld().getObjects(complete.class).isEmpty()) {
getWorld().addObject(new complete(),550,275);
}
else if(!pa.getKey() && getWorld().getObjects(no_key.class).isEmpty()) {
getWorld().addObject(new no_key(),550,275);
}
}
}
} | apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-logging/v2/1.31.0/com/google/api/services/logging/v2/model/SourceLocation.java | 4414 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.logging.v2.model;
/**
* Specifies a location in a source code file.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Logging API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class SourceLocation extends com.google.api.client.json.GenericJson {
/**
* Source file name. Depending on the runtime environment, this might be a simple name or a fully-
* qualified name.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String file;
/**
* Human-readable name of the function or method being invoked, with optional context such as the
* class or package name. This information is used in contexts such as the logs viewer, where a
* file and line number are less meaningful. The format can vary by language. For example:
* qual.if.ied.Class.method (Java), dir/package.func (Go), function (Python).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String functionName;
/**
* Line within the source file.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key @com.google.api.client.json.JsonString
private java.lang.Long line;
/**
* Source file name. Depending on the runtime environment, this might be a simple name or a fully-
* qualified name.
* @return value or {@code null} for none
*/
public java.lang.String getFile() {
return file;
}
/**
* Source file name. Depending on the runtime environment, this might be a simple name or a fully-
* qualified name.
* @param file file or {@code null} for none
*/
public SourceLocation setFile(java.lang.String file) {
this.file = file;
return this;
}
/**
* Human-readable name of the function or method being invoked, with optional context such as the
* class or package name. This information is used in contexts such as the logs viewer, where a
* file and line number are less meaningful. The format can vary by language. For example:
* qual.if.ied.Class.method (Java), dir/package.func (Go), function (Python).
* @return value or {@code null} for none
*/
public java.lang.String getFunctionName() {
return functionName;
}
/**
* Human-readable name of the function or method being invoked, with optional context such as the
* class or package name. This information is used in contexts such as the logs viewer, where a
* file and line number are less meaningful. The format can vary by language. For example:
* qual.if.ied.Class.method (Java), dir/package.func (Go), function (Python).
* @param functionName functionName or {@code null} for none
*/
public SourceLocation setFunctionName(java.lang.String functionName) {
this.functionName = functionName;
return this;
}
/**
* Line within the source file.
* @return value or {@code null} for none
*/
public java.lang.Long getLine() {
return line;
}
/**
* Line within the source file.
* @param line line or {@code null} for none
*/
public SourceLocation setLine(java.lang.Long line) {
this.line = line;
return this;
}
@Override
public SourceLocation set(String fieldName, Object value) {
return (SourceLocation) super.set(fieldName, value);
}
@Override
public SourceLocation clone() {
return (SourceLocation) super.clone();
}
}
| apache-2.0 |
mastinno/geojson-jackson-java | src/main/java/org/geojson/MultiLineString.java | 430 | package org.geojson;
import java.util.List;
public class MultiLineString extends Geometry<List<LngLatAlt>> {
public MultiLineString() {
}
public MultiLineString(List<LngLatAlt> line) {
add(line);
}
@Override
public <T> T accept(GeoJsonObjectVisitor<T> geoJsonObjectVisitor) {
return geoJsonObjectVisitor.visit(this);
}
@Override
public String toString() {
return "MultiLineString{} " + super.toString();
}
}
| apache-2.0 |
jGauravGupta/jpamodeler | jcode-util/src/main/java/io/github/jeddict/jcode/SecurityConstants.java | 1229 | /**
* Copyright 2013-2019 the original author or authors from the Jeddict project (https://jeddict.github.io/).
*
* 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
* workingCopy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.github.jeddict.jcode;
/**
*
* @author Gaurav Gupta
*/
public class SecurityConstants {
public static final String EMBEDDED_IDENTITY_STORE_DEFINITION = "javax.security.identitystore.annotation.EmbeddedIdentityStoreDefinition";
public static final String CREDENTIALS = "javax.security.identitystore.annotation.Credentials";
public static final String CALLER_NAME = "callerName";
public static final String PASSWORD = "password";
public static final String DEFAULT_CREDENTIALS = "user";
}
| apache-2.0 |
apache/commons-imaging | src/test/java/org/apache/commons/imaging/formats/gif/GifReadTest.java | 9196 | /*
* 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.imaging.formats.gif;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.stream.Stream;
import org.apache.commons.imaging.ImageInfo;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.Imaging;
import org.apache.commons.imaging.common.bytesource.ByteSourceFile;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class GifReadTest extends GifBaseTest {
public static Stream<File> data() throws Exception {
return getGifImages().stream();
}
public static Stream<File> singleImageData() throws Exception {
return getGifImagesWithSingleImage().stream();
}
public static Stream<File> animatedImageData() throws Exception {
return getAnimatedGifImages().stream();
}
@Disabled(value = "RoundtripTest has to be fixed before implementation can throw UnsupportedOperationException")
@ParameterizedTest
@MethodSource("data")
public void testMetadata(final File imageFile) {
Assertions.assertThrows(UnsupportedOperationException.class, () -> Imaging.getMetadata(imageFile));
}
@ParameterizedTest
@MethodSource("data")
public void testImageInfo(final File imageFile) throws Exception {
final ImageInfo imageInfo = Imaging.getImageInfo(imageFile);
assertNotNull(imageInfo);
// TODO assert more
}
@ParameterizedTest
@MethodSource("data")
public void testImageDimensions(final File imageFile) throws Exception {
final ImageInfo imageInfo = Imaging.getImageInfo(imageFile);
final GifImageMetadata metadata = (GifImageMetadata) Imaging.getMetadata(imageFile);
final List<BufferedImage> images = Imaging.getAllBufferedImages(imageFile);
int width = 0;
int height = 0;
for(int i = 0; i < images.size(); i++) {
final BufferedImage image = images.get(i);
final GifImageMetadataItem metadataItem = metadata.getItems().get(i);
final int xOffset = metadataItem.getLeftPosition();
final int yOffset = metadataItem.getTopPosition();
width = Math.max(width, image.getWidth() + xOffset);
height = Math.max(height, image.getHeight() + yOffset);
}
assertEquals(width, metadata.getWidth());
assertEquals(height, metadata.getHeight());
assertEquals(width, imageInfo.getWidth());
assertEquals(height, imageInfo.getHeight());
}
@ParameterizedTest
@MethodSource("data")
public void testBufferedImage(final File imageFile) throws Exception {
final BufferedImage image = Imaging.getBufferedImage(imageFile);
assertNotNull(image);
// TODO assert more
}
@ParameterizedTest
@MethodSource("singleImageData")
public void testBufferedImagesForSingleImageGif(final File imageFile) throws Exception {
final List<BufferedImage> images = Imaging.getAllBufferedImages(imageFile);
assertEquals(1, images.size());
}
@ParameterizedTest
@MethodSource("animatedImageData")
public void testBufferedImagesForAnimatedImageGif(final File imageFile) throws Exception {
final List<BufferedImage> images = Imaging.getAllBufferedImages(imageFile);
assertTrue(images.size() > 1);
}
@Test
public void testCreateMetadataWithDisposalMethods() {
for(final DisposalMethod disposalMethod : DisposalMethod.values()) {
final GifImageMetadataItem metadataItem = new GifImageMetadataItem(0, 0, 0, disposalMethod);
Assertions.assertEquals(disposalMethod, metadataItem.getDisposalMethod());
}
}
@Test
public void testConvertValidDisposalMethodValues() throws ImageReadException {
final DisposalMethod unspecified = GifImageParser.createDisposalMethodFromIntValue(0);
final DisposalMethod doNotDispose = GifImageParser.createDisposalMethodFromIntValue(1);
final DisposalMethod restoreToBackground = GifImageParser.createDisposalMethodFromIntValue(2);
final DisposalMethod restoreToPrevious = GifImageParser.createDisposalMethodFromIntValue(3);
final DisposalMethod toBeDefined1 = GifImageParser.createDisposalMethodFromIntValue(4);
final DisposalMethod toBeDefined2 = GifImageParser.createDisposalMethodFromIntValue(5);
final DisposalMethod toBeDefined3 = GifImageParser.createDisposalMethodFromIntValue(6);
final DisposalMethod toBeDefined4 = GifImageParser.createDisposalMethodFromIntValue(7);
Assertions.assertEquals(unspecified, DisposalMethod.UNSPECIFIED);
Assertions.assertEquals(doNotDispose, DisposalMethod.DO_NOT_DISPOSE);
Assertions.assertEquals(restoreToBackground, DisposalMethod.RESTORE_TO_BACKGROUND);
Assertions.assertEquals(restoreToPrevious, DisposalMethod.RESTORE_TO_PREVIOUS);
Assertions.assertEquals(toBeDefined1, DisposalMethod.TO_BE_DEFINED_1);
Assertions.assertEquals(toBeDefined2, DisposalMethod.TO_BE_DEFINED_2);
Assertions.assertEquals(toBeDefined3, DisposalMethod.TO_BE_DEFINED_3);
Assertions.assertEquals(toBeDefined4, DisposalMethod.TO_BE_DEFINED_4);
}
@Test
public void testConvertInvalidDisposalMethodValues() {
Assertions.assertThrows(ImageReadException.class, () -> GifImageParser.createDisposalMethodFromIntValue(8));
}
/**
* The GIF image data may lead to out of bound array access. This
* test verifies that we handle that case and raise an appropriate
* exception.
*
* <p>See Google OSS Fuzz issue 33501</p>
*
* @throws IOException if it fails to read the test image
*/
@Test
public void testUncaughtExceptionOssFuzz33501() throws IOException {
final String input = "/images/gif/oss-fuzz-33501/clusterfuzz-testcase-minimized-ImagingGifFuzzer-5914278319226880";
final String file = GifReadTest.class.getResource(input).getFile();
final GifImageParser parser = new GifImageParser();
assertThrows(ImageReadException.class, () -> parser.getBufferedImage(new ByteSourceFile(new File(file)), new GifImagingParameters()));
}
/**
* The GIF image Lzw compression may contain a table with length inferior to
* the length of entries in the image data. Which results in an ArrayOutOfBoundsException.
* This verifies that instead of throwing an AOOBE, we are handling the case and
* informing the user why the parser failed to read it, by throwin an ImageReadException
* with a more descriptive message.
*
* <p>See Google OSS Fuzz issue 33464</p>
*
* @throws IOException if it fails to read the test image
*/
@Test
public void testUncaughtExceptionOssFuzz33464() throws IOException {
final String input = "/images/gif/oss-fuzz-33464/clusterfuzz-testcase-minimized-ImagingGifFuzzer-5174009164595200";
final String file = GifReadTest.class.getResource(input).getFile();
final GifImageParser parser = new GifImageParser();
assertThrows(ImageReadException.class, () -> parser.getBufferedImage(new ByteSourceFile(new File(file)), new GifImagingParameters()));
}
/**
* Test that invalid indexes are validated when accessing GIF color table array.
*
* <p>See Google OSS Fuzz issue 34185</p>
*
* @throws IOException if it fails to read the test image
*/
@Test
public void testUncaughtExceptionOssFuzz34185() throws IOException {
final String input = "/images/gif/IMAGING-318/clusterfuzz-testcase-minimized-ImagingGifFuzzer-5005192379629568";
final String file = GifReadTest.class.getResource(input).getFile();
final GifImageParser parser = new GifImageParser();
assertThrows(ImageReadException.class, () -> parser.getBufferedImage(new ByteSourceFile(new File(file)), new GifImagingParameters()));
}
}
| apache-2.0 |
Teiid-Designer/teiid-webui | teiid-webui-webapp/src/main/java/org/teiid/webui/client/widgets/ServiceFlowListWidget.java | 1154 | /*
* Copyright 2014 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.teiid.webui.client.widgets;
import org.jboss.errai.ui.client.widget.ListWidget;
import com.google.gwt.user.client.ui.FlowPanel;
/**
* ServiceFlowPanel - extends Errai ListWidget, providing the desired Flow behavior for the DataServicesLibraryScreen
*
*/
public class ServiceFlowListWidget extends ListWidget<ServiceRow, LibraryServiceWidget> {
public ServiceFlowListWidget() {
super(new FlowPanel());
}
@Override
public Class<LibraryServiceWidget> getItemWidgetType() {
return LibraryServiceWidget.class;
}
} | apache-2.0 |
TitasNandi/Summer_Project | dkpro-similarity-master/dkpro-similarity-experiments-wordpairs-asl/src/main/java/dkpro/similarity/experiments/wordpairs/io/SemanticRelatednessResultWriter.java | 13282 | /*******************************************************************************
* Copyright 2013
* Ubiquitous Knowledge Processing (UKP) Lab
* Technische Universität Darmstadt
*
* 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 dkpro.similarity.experiments.wordpairs.io;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;
import org.apache.commons.math3.stat.correlation.SpearmansCorrelation;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.fit.component.JCasAnnotator_ImplBase;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import de.tudarmstadt.ukp.dkpro.core.api.metadata.type.DocumentMetaData;
import dkpro.similarity.type.SemRelWordPair;
import dkpro.similarity.type.SemanticRelatedness;
public class SemanticRelatednessResultWriter extends JCasAnnotator_ImplBase {
private static final String SEP = ":";
private static final String LF = System.getProperty("line.separator");
public static final String PARAM_SHOW_DETAILS = "ShowDetails";
@ConfigurationParameter(name = PARAM_SHOW_DETAILS, mandatory=true, defaultValue="false")
private boolean showDetails;
@Override
public void process(JCas jcas)
throws AnalysisEngineProcessException
{
Result result = new Result();
for (SemanticRelatedness sr : JCasUtil.select(jcas, SemanticRelatedness.class)) {
String measureName = sr.getMeasureName();
String measureType = sr.getMeasureType();
String term1 = sr.getTerm1();
String term2 = sr.getTerm2();
double relatednessValue = sr.getRelatednessValue();
String measureKey = measureType + "-" + measureName;
SemRelWordPair wp = (SemRelWordPair) sr.getWordPair();
result.addScore(term1, term2, measureKey, relatednessValue, wp.getGoldValue());
}
if (showDetails) {
System.out.println("UNFILTERED");
System.out.println(result.getWordpairs().size() + " word pairs");
System.out.println( getFormattedResultMap(result) );
}
// filter invalid keys in the result object (i.e. wordpairs where at least one measure returned NOT_FOUND)
Result filteredResult = getFilteredResult(result);
if (showDetails) {
System.out.println("FILTERED");
System.out.println(filteredResult.getWordpairs().size() + " word pairs");
System.out.println( getFormattedResultMap(filteredResult) );
}
if (showDetails) {
System.out.println(DocumentMetaData.get(jcas).getDocumentTitle());
System.out.println( getMeasures(filteredResult) );
System.out.println( getCorrelations(filteredResult) );
System.out.println();
}
else {
for (String measure : filteredResult.measures) {
System.out.println(getShortResults(filteredResult, measure,
DocumentMetaData.get(jcas).getDocumentTitle()));
}
}
}
private String getFormattedResultMap(Result result) {
StringBuilder sb = new StringBuilder();
sb.append("Term1");
sb.append(SEP);
sb.append("Term2");
sb.append(SEP);
sb.append("Gold");
sb.append(SEP);
sb.append(StringUtils.join(result.getMeasures(), SEP));
sb.append(LF);
for (String wordpair : result.getWordpairs()) {
sb.append(wordpair);
sb.append(SEP);
sb.append(result.getGoldValue(wordpair));
for (String measure : result.getMeasures()) {
sb.append(SEP);
sb.append(result.getScore(wordpair, measure));
}
sb.append(LF);
}
sb.append(LF);
return sb.toString();
}
private class Result {
private final Map<String,Scores> wordpairScoresMap;
private final Map<String,Double> wordpairGoldMap;
private final Set<String> measures;
public Result() {
wordpairScoresMap = new TreeMap<String,Scores>();
wordpairGoldMap = new TreeMap<String,Double>();
measures = new TreeSet<String>();
}
public void addScore(String term1, String term2, String measureKey, double relatednessValue, double goldValue) throws AnalysisEngineProcessException {
String key = getKeyTerm(term1, term2);
addScore(key, measureKey, relatednessValue, goldValue);
}
public void addScore(String key, String measureKey, double relatednessValue, double goldValue) throws AnalysisEngineProcessException {
measures.add(measureKey);
if (
//word pair is already stored in map
wordpairGoldMap.containsKey(key)
&&
//it has been evaluated with the same measure "measureKey"
wordpairScoresMap.get( key ).containsMeasure(measureKey)
) {
System.out.println("wordpairGoldMap already contains key: " + key);
System.out.println("Ignoring this duplicate word pair. Duplicates might occurr because of stemming.");
return;
}
wordpairGoldMap.put(key, goldValue);
if (wordpairScoresMap.containsKey(key)) {
Scores scores = wordpairScoresMap.get( key );
scores.update(measureKey, relatednessValue);
wordpairScoresMap.put(key, scores);
}
else {
Scores scores = new Scores(measureKey, relatednessValue);
wordpairScoresMap.put(key, scores);
}
}
public Set<String> getMeasures() {
return measures;
}
public Set<String> getWordpairs() {
return wordpairScoresMap.keySet();
}
public Double getScore(String wordpair, String measure) {
return wordpairScoresMap.get(wordpair).getValue(measure);
}
public Double getGoldValue(String wordpair) {
return wordpairGoldMap.get(wordpair);
}
/**
* @return The list of gold standard values in key sorted order.
*/
public List<Double> getGoldList() {
List<Double> goldList = new ArrayList<Double>();
for (String wordpair : wordpairGoldMap.keySet()) {
goldList.add(wordpairGoldMap.get(wordpair));
}
return goldList;
}
/**
* @param measure
* @return The list of scores for the given measure in key sorted order.
*/
public List<Double> getScoreList(String measure) {
List<Double> scoreList = new ArrayList<Double>();
for (String wordpair : wordpairGoldMap.keySet()) {
scoreList.add(wordpairScoresMap.get(wordpair).getValue(measure));
}
return scoreList;
}
private String getKeyTerm(String term1, String term2) {
String key;
if (term1.compareTo(term2) < 0) {
key = term1 + SEP + term2;
}
else {
key = term2 + SEP + term1;
}
return key;
}
}
private static class Scores {
private final Map<String,Double> measureScoreMap;
public Scores(String measureKey, double relatednessValue) {
measureScoreMap = new TreeMap<String,Double>();
measureScoreMap.put(measureKey, relatednessValue);
}
public void update(String measureKey, double relatednessValue) throws AnalysisEngineProcessException {
if (measureScoreMap.containsKey(measureKey)) {
throw new AnalysisEngineProcessException(new Throwable("Score for measure " + measureKey + " already exists. Do you have run the measure twice? Might also be caused by a duplicate word pair (e.g. money-cash and bank-money/money-bank are included twice in the original Fikelstein-353 dataset)."));
}
measureScoreMap.put(measureKey, relatednessValue);
}
public boolean containsMeasure(String measure) {
return measureScoreMap.containsKey(measure);
}
public Double getValue(String measure) {
return measureScoreMap.get(measure);
}
}
private Result getFilteredResult(Result result) throws AnalysisEngineProcessException {
Set<String> wordpairsToFilter = new HashSet<String>();
for (String wordpair : result.getWordpairs()) {
for (String measure : result.getMeasures()) {
if (result.getScore(wordpair, measure) == null) {
wordpairsToFilter.add(wordpair);
}
else if (result.getScore(wordpair, measure) < 0.0) {
wordpairsToFilter.add(wordpair);
}
}
}
Result filteredResult = new Result();
for (String wordpair : result.getWordpairs()) {
if (!wordpairsToFilter.contains(wordpair)) {
for (String measure : result.getMeasures()) {
filteredResult.addScore(wordpair, measure, result.getScore(wordpair, measure), result.getGoldValue(wordpair));
}
}
}
return filteredResult;
}
private String getShortResults(Result result, String measure, String document) {
StringBuilder sb = new StringBuilder();
sb.append("RESULT");
sb.append(SEP);
sb.append(document);
sb.append(SEP);
sb.append(measure);
sb.append(SEP);
List<Double> scoreList = result.getScoreList(measure);
List<Double> goldList = result.getGoldList();
double pearsonCorrelation = new PearsonsCorrelation().correlation(
ArrayUtils.toPrimitive(goldList.toArray(new Double[goldList.size()])),
ArrayUtils.toPrimitive(scoreList.toArray(new Double[goldList.size()]))
);
double spearmanCorrelation = new SpearmansCorrelation().correlation(
ArrayUtils.toPrimitive(goldList.toArray(new Double[goldList.size()])),
ArrayUtils.toPrimitive(scoreList.toArray(new Double[goldList.size()]))
);
sb.append(spearmanCorrelation);
sb.append(SEP);
sb.append(pearsonCorrelation);
return sb.toString();
}
private String getCorrelations(Result result) {
Map<String,Double> pearsonCorrelationMap = new HashMap<String,Double>();
Map<String,Double> spearmanCorrelationMap = new HashMap<String,Double>();
List<Double> goldList = result.getGoldList();
for (String measure : result.getMeasures()) {
List<Double> scoreList = result.getScoreList(measure);
double pearsonCorrelation = new PearsonsCorrelation().correlation(
ArrayUtils.toPrimitive(goldList.toArray(new Double[goldList.size()])),
ArrayUtils.toPrimitive(scoreList.toArray(new Double[goldList.size()]))
);
pearsonCorrelationMap.put(measure, pearsonCorrelation);
double spearmanCorrelation = new SpearmansCorrelation().correlation(
ArrayUtils.toPrimitive(goldList.toArray(new Double[goldList.size()])),
ArrayUtils.toPrimitive(scoreList.toArray(new Double[goldList.size()]))
);
spearmanCorrelationMap.put(measure, spearmanCorrelation);
}
StringBuilder sb = new StringBuilder();
sb.append("Pearson: ");
for (String measure : result.getMeasures()) {
sb.append(pearsonCorrelationMap.get(measure));
sb.append(SEP);
}
sb.append(LF);
sb.append("Spearman: ");
for (String measure : result.getMeasures()) {
sb.append(spearmanCorrelationMap.get(measure));
sb.append(SEP);
}
return sb.toString();
}
private String getMeasures(Result result) {
StringBuilder sb = new StringBuilder();
sb.append("Measure: ");
for (String measure : result.getMeasures()) {
sb.append(measure);
sb.append(SEP);
}
return sb.toString();
}
} | apache-2.0 |
omindu/carbon-identity-framework | components/configuration-mgt/org.wso2.carbon.identity.api.server.configuration.mgt/src/gen/java/org/wso2/carbon/identity/configuration/mgt/endpoint/dto/ResourceFileDTO.java | 1162 | package org.wso2.carbon.identity.configuration.mgt.endpoint.dto;
import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.*;
import javax.validation.constraints.NotNull;
@ApiModel(description = "")
public class ResourceFileDTO {
@NotNull
private String name = null;
private String file = null;
/**
* Describes the name of the file.
**/
@ApiModelProperty(required = true, value = "Describes the name of the file.")
@JsonProperty("name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* Provide the location of the file
**/
@ApiModelProperty(value = "Provide the location of the file")
@JsonProperty("file")
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ResourceFileDTO {\n");
sb.append(" name: ").append(name).append("\n");
sb.append(" file: ").append(file).append("\n");
sb.append("}\n");
return sb.toString();
}
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-monitoring/v3/1.31.0/com/google/api/services/monitoring/v3/model/Error.java | 2686 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.monitoring.v3.model;
/**
* Detailed information about an error category.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Monitoring API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class Error extends com.google.api.client.json.GenericJson {
/**
* The number of points that couldn't be written because of status.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer pointCount;
/**
* The status of the requested write operation.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private Status status;
/**
* The number of points that couldn't be written because of status.
* @return value or {@code null} for none
*/
public java.lang.Integer getPointCount() {
return pointCount;
}
/**
* The number of points that couldn't be written because of status.
* @param pointCount pointCount or {@code null} for none
*/
public Error setPointCount(java.lang.Integer pointCount) {
this.pointCount = pointCount;
return this;
}
/**
* The status of the requested write operation.
* @return value or {@code null} for none
*/
public Status getStatus() {
return status;
}
/**
* The status of the requested write operation.
* @param status status or {@code null} for none
*/
public Error setStatus(Status status) {
this.status = status;
return this;
}
@Override
public Error set(String fieldName, Object value) {
return (Error) super.set(fieldName, value);
}
@Override
public Error clone() {
return (Error) super.clone();
}
}
| apache-2.0 |
Gaduo/hapi-fhir | hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/model/Patient.java | 135364 | package org.hl7.fhir.dstu3.model;
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Tue, Dec 6, 2016 09:42-0500 for FHIR v1.8.0
import java.util.*;
import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.dstu3.model.Enumerations.*;
import ca.uhn.fhir.model.api.annotation.ResourceDef;
import ca.uhn.fhir.model.api.annotation.SearchParamDefinition;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.ChildOrder;
import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.model.api.annotation.Block;
import org.hl7.fhir.instance.model.api.*;
import org.hl7.fhir.exceptions.FHIRException;
/**
* Demographics and other administrative information about an individual or animal receiving care or other health-related services.
*/
@ResourceDef(name="Patient", profile="http://hl7.org/fhir/Profile/Patient")
public class Patient extends DomainResource {
public enum LinkType {
/**
* The patient resource containing this link must no longer be used. The link points forward to another patient resource that must be used in lieu of the patient resource that contains this link.
*/
REPLACE,
/**
* The patient resource containing this link is in use and valid but not considered the main source of information about a patient. The link points forward to another patient resource that should be consulted to retrieve additional patient information.
*/
REFER,
/**
* The patient resource containing this link is in use and valid, but points to another patient resource that is known to contain data about the same person. Data in this resource might overlap or contradict information found in the other patient resource. This link does not indicate any relative importance of the resources concerned, and both should be regarded as equally valid.
*/
SEEALSO,
/**
* added to help the parsers with the generic types
*/
NULL;
public static LinkType fromCode(String codeString) throws FHIRException {
if (codeString == null || "".equals(codeString))
return null;
if ("replace".equals(codeString))
return REPLACE;
if ("refer".equals(codeString))
return REFER;
if ("seealso".equals(codeString))
return SEEALSO;
if (Configuration.isAcceptInvalidEnums())
return null;
else
throw new FHIRException("Unknown LinkType code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case REPLACE: return "replace";
case REFER: return "refer";
case SEEALSO: return "seealso";
default: return "?";
}
}
public String getSystem() {
switch (this) {
case REPLACE: return "http://hl7.org/fhir/link-type";
case REFER: return "http://hl7.org/fhir/link-type";
case SEEALSO: return "http://hl7.org/fhir/link-type";
default: return "?";
}
}
public String getDefinition() {
switch (this) {
case REPLACE: return "The patient resource containing this link must no longer be used. The link points forward to another patient resource that must be used in lieu of the patient resource that contains this link.";
case REFER: return "The patient resource containing this link is in use and valid but not considered the main source of information about a patient. The link points forward to another patient resource that should be consulted to retrieve additional patient information.";
case SEEALSO: return "The patient resource containing this link is in use and valid, but points to another patient resource that is known to contain data about the same person. Data in this resource might overlap or contradict information found in the other patient resource. This link does not indicate any relative importance of the resources concerned, and both should be regarded as equally valid.";
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case REPLACE: return "Replace";
case REFER: return "Refer";
case SEEALSO: return "See also";
default: return "?";
}
}
}
public static class LinkTypeEnumFactory implements EnumFactory<LinkType> {
public LinkType fromCode(String codeString) throws IllegalArgumentException {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("replace".equals(codeString))
return LinkType.REPLACE;
if ("refer".equals(codeString))
return LinkType.REFER;
if ("seealso".equals(codeString))
return LinkType.SEEALSO;
throw new IllegalArgumentException("Unknown LinkType code '"+codeString+"'");
}
public Enumeration<LinkType> fromType(Base code) throws FHIRException {
if (code == null || code.isEmpty())
return null;
String codeString = ((PrimitiveType) code).asStringValue();
if (codeString == null || "".equals(codeString))
return null;
if ("replace".equals(codeString))
return new Enumeration<LinkType>(this, LinkType.REPLACE);
if ("refer".equals(codeString))
return new Enumeration<LinkType>(this, LinkType.REFER);
if ("seealso".equals(codeString))
return new Enumeration<LinkType>(this, LinkType.SEEALSO);
throw new FHIRException("Unknown LinkType code '"+codeString+"'");
}
public String toCode(LinkType code) {
if (code == LinkType.REPLACE)
return "replace";
if (code == LinkType.REFER)
return "refer";
if (code == LinkType.SEEALSO)
return "seealso";
return "?";
}
public String toSystem(LinkType code) {
return code.getSystem();
}
}
@Block()
public static class ContactComponent extends BackboneElement implements IBaseBackboneElement {
/**
* The nature of the relationship between the patient and the contact person.
*/
@Child(name = "relationship", type = {CodeableConcept.class}, order=1, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
@Description(shortDefinition="The kind of relationship", formalDefinition="The nature of the relationship between the patient and the contact person." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/v2-0131")
protected List<CodeableConcept> relationship;
/**
* A name associated with the contact person.
*/
@Child(name = "name", type = {HumanName.class}, order=2, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="A name associated with the contact person", formalDefinition="A name associated with the contact person." )
protected HumanName name;
/**
* A contact detail for the person, e.g. a telephone number or an email address.
*/
@Child(name = "telecom", type = {ContactPoint.class}, order=3, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
@Description(shortDefinition="A contact detail for the person", formalDefinition="A contact detail for the person, e.g. a telephone number or an email address." )
protected List<ContactPoint> telecom;
/**
* Address for the contact person.
*/
@Child(name = "address", type = {Address.class}, order=4, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Address for the contact person", formalDefinition="Address for the contact person." )
protected Address address;
/**
* Administrative Gender - the gender that the contact person is considered to have for administration and record keeping purposes.
*/
@Child(name = "gender", type = {CodeType.class}, order=5, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="male | female | other | unknown", formalDefinition="Administrative Gender - the gender that the contact person is considered to have for administration and record keeping purposes." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/administrative-gender")
protected Enumeration<AdministrativeGender> gender;
/**
* Organization on behalf of which the contact is acting or for which the contact is working.
*/
@Child(name = "organization", type = {Organization.class}, order=6, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Organization that is associated with the contact", formalDefinition="Organization on behalf of which the contact is acting or for which the contact is working." )
protected Reference organization;
/**
* The actual object that is the target of the reference (Organization on behalf of which the contact is acting or for which the contact is working.)
*/
protected Organization organizationTarget;
/**
* The period during which this contact person or organization is valid to be contacted relating to this patient.
*/
@Child(name = "period", type = {Period.class}, order=7, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="The period during which this contact person or organization is valid to be contacted relating to this patient", formalDefinition="The period during which this contact person or organization is valid to be contacted relating to this patient." )
protected Period period;
private static final long serialVersionUID = 364269017L;
/**
* Constructor
*/
public ContactComponent() {
super();
}
/**
* @return {@link #relationship} (The nature of the relationship between the patient and the contact person.)
*/
public List<CodeableConcept> getRelationship() {
if (this.relationship == null)
this.relationship = new ArrayList<CodeableConcept>();
return this.relationship;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public ContactComponent setRelationship(List<CodeableConcept> theRelationship) {
this.relationship = theRelationship;
return this;
}
public boolean hasRelationship() {
if (this.relationship == null)
return false;
for (CodeableConcept item : this.relationship)
if (!item.isEmpty())
return true;
return false;
}
public CodeableConcept addRelationship() { //3
CodeableConcept t = new CodeableConcept();
if (this.relationship == null)
this.relationship = new ArrayList<CodeableConcept>();
this.relationship.add(t);
return t;
}
public ContactComponent addRelationship(CodeableConcept t) { //3
if (t == null)
return this;
if (this.relationship == null)
this.relationship = new ArrayList<CodeableConcept>();
this.relationship.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #relationship}, creating it if it does not already exist
*/
public CodeableConcept getRelationshipFirstRep() {
if (getRelationship().isEmpty()) {
addRelationship();
}
return getRelationship().get(0);
}
/**
* @return {@link #name} (A name associated with the contact person.)
*/
public HumanName getName() {
if (this.name == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ContactComponent.name");
else if (Configuration.doAutoCreate())
this.name = new HumanName(); // cc
return this.name;
}
public boolean hasName() {
return this.name != null && !this.name.isEmpty();
}
/**
* @param value {@link #name} (A name associated with the contact person.)
*/
public ContactComponent setName(HumanName value) {
this.name = value;
return this;
}
/**
* @return {@link #telecom} (A contact detail for the person, e.g. a telephone number or an email address.)
*/
public List<ContactPoint> getTelecom() {
if (this.telecom == null)
this.telecom = new ArrayList<ContactPoint>();
return this.telecom;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public ContactComponent setTelecom(List<ContactPoint> theTelecom) {
this.telecom = theTelecom;
return this;
}
public boolean hasTelecom() {
if (this.telecom == null)
return false;
for (ContactPoint item : this.telecom)
if (!item.isEmpty())
return true;
return false;
}
public ContactPoint addTelecom() { //3
ContactPoint t = new ContactPoint();
if (this.telecom == null)
this.telecom = new ArrayList<ContactPoint>();
this.telecom.add(t);
return t;
}
public ContactComponent addTelecom(ContactPoint t) { //3
if (t == null)
return this;
if (this.telecom == null)
this.telecom = new ArrayList<ContactPoint>();
this.telecom.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #telecom}, creating it if it does not already exist
*/
public ContactPoint getTelecomFirstRep() {
if (getTelecom().isEmpty()) {
addTelecom();
}
return getTelecom().get(0);
}
/**
* @return {@link #address} (Address for the contact person.)
*/
public Address getAddress() {
if (this.address == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ContactComponent.address");
else if (Configuration.doAutoCreate())
this.address = new Address(); // cc
return this.address;
}
public boolean hasAddress() {
return this.address != null && !this.address.isEmpty();
}
/**
* @param value {@link #address} (Address for the contact person.)
*/
public ContactComponent setAddress(Address value) {
this.address = value;
return this;
}
/**
* @return {@link #gender} (Administrative Gender - the gender that the contact person is considered to have for administration and record keeping purposes.). This is the underlying object with id, value and extensions. The accessor "getGender" gives direct access to the value
*/
public Enumeration<AdministrativeGender> getGenderElement() {
if (this.gender == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ContactComponent.gender");
else if (Configuration.doAutoCreate())
this.gender = new Enumeration<AdministrativeGender>(new AdministrativeGenderEnumFactory()); // bb
return this.gender;
}
public boolean hasGenderElement() {
return this.gender != null && !this.gender.isEmpty();
}
public boolean hasGender() {
return this.gender != null && !this.gender.isEmpty();
}
/**
* @param value {@link #gender} (Administrative Gender - the gender that the contact person is considered to have for administration and record keeping purposes.). This is the underlying object with id, value and extensions. The accessor "getGender" gives direct access to the value
*/
public ContactComponent setGenderElement(Enumeration<AdministrativeGender> value) {
this.gender = value;
return this;
}
/**
* @return Administrative Gender - the gender that the contact person is considered to have for administration and record keeping purposes.
*/
public AdministrativeGender getGender() {
return this.gender == null ? null : this.gender.getValue();
}
/**
* @param value Administrative Gender - the gender that the contact person is considered to have for administration and record keeping purposes.
*/
public ContactComponent setGender(AdministrativeGender value) {
if (value == null)
this.gender = null;
else {
if (this.gender == null)
this.gender = new Enumeration<AdministrativeGender>(new AdministrativeGenderEnumFactory());
this.gender.setValue(value);
}
return this;
}
/**
* @return {@link #organization} (Organization on behalf of which the contact is acting or for which the contact is working.)
*/
public Reference getOrganization() {
if (this.organization == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ContactComponent.organization");
else if (Configuration.doAutoCreate())
this.organization = new Reference(); // cc
return this.organization;
}
public boolean hasOrganization() {
return this.organization != null && !this.organization.isEmpty();
}
/**
* @param value {@link #organization} (Organization on behalf of which the contact is acting or for which the contact is working.)
*/
public ContactComponent setOrganization(Reference value) {
this.organization = value;
return this;
}
/**
* @return {@link #organization} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Organization on behalf of which the contact is acting or for which the contact is working.)
*/
public Organization getOrganizationTarget() {
if (this.organizationTarget == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ContactComponent.organization");
else if (Configuration.doAutoCreate())
this.organizationTarget = new Organization(); // aa
return this.organizationTarget;
}
/**
* @param value {@link #organization} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Organization on behalf of which the contact is acting or for which the contact is working.)
*/
public ContactComponent setOrganizationTarget(Organization value) {
this.organizationTarget = value;
return this;
}
/**
* @return {@link #period} (The period during which this contact person or organization is valid to be contacted relating to this patient.)
*/
public Period getPeriod() {
if (this.period == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ContactComponent.period");
else if (Configuration.doAutoCreate())
this.period = new Period(); // cc
return this.period;
}
public boolean hasPeriod() {
return this.period != null && !this.period.isEmpty();
}
/**
* @param value {@link #period} (The period during which this contact person or organization is valid to be contacted relating to this patient.)
*/
public ContactComponent setPeriod(Period value) {
this.period = value;
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("relationship", "CodeableConcept", "The nature of the relationship between the patient and the contact person.", 0, java.lang.Integer.MAX_VALUE, relationship));
childrenList.add(new Property("name", "HumanName", "A name associated with the contact person.", 0, java.lang.Integer.MAX_VALUE, name));
childrenList.add(new Property("telecom", "ContactPoint", "A contact detail for the person, e.g. a telephone number or an email address.", 0, java.lang.Integer.MAX_VALUE, telecom));
childrenList.add(new Property("address", "Address", "Address for the contact person.", 0, java.lang.Integer.MAX_VALUE, address));
childrenList.add(new Property("gender", "code", "Administrative Gender - the gender that the contact person is considered to have for administration and record keeping purposes.", 0, java.lang.Integer.MAX_VALUE, gender));
childrenList.add(new Property("organization", "Reference(Organization)", "Organization on behalf of which the contact is acting or for which the contact is working.", 0, java.lang.Integer.MAX_VALUE, organization));
childrenList.add(new Property("period", "Period", "The period during which this contact person or organization is valid to be contacted relating to this patient.", 0, java.lang.Integer.MAX_VALUE, period));
}
@Override
public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
switch (hash) {
case -261851592: /*relationship*/ return this.relationship == null ? new Base[0] : this.relationship.toArray(new Base[this.relationship.size()]); // CodeableConcept
case 3373707: /*name*/ return this.name == null ? new Base[0] : new Base[] {this.name}; // HumanName
case -1429363305: /*telecom*/ return this.telecom == null ? new Base[0] : this.telecom.toArray(new Base[this.telecom.size()]); // ContactPoint
case -1147692044: /*address*/ return this.address == null ? new Base[0] : new Base[] {this.address}; // Address
case -1249512767: /*gender*/ return this.gender == null ? new Base[0] : new Base[] {this.gender}; // Enumeration<AdministrativeGender>
case 1178922291: /*organization*/ return this.organization == null ? new Base[0] : new Base[] {this.organization}; // Reference
case -991726143: /*period*/ return this.period == null ? new Base[0] : new Base[] {this.period}; // Period
default: return super.getProperty(hash, name, checkValid);
}
}
@Override
public void setProperty(int hash, String name, Base value) throws FHIRException {
switch (hash) {
case -261851592: // relationship
this.getRelationship().add(castToCodeableConcept(value)); // CodeableConcept
break;
case 3373707: // name
this.name = castToHumanName(value); // HumanName
break;
case -1429363305: // telecom
this.getTelecom().add(castToContactPoint(value)); // ContactPoint
break;
case -1147692044: // address
this.address = castToAddress(value); // Address
break;
case -1249512767: // gender
this.gender = new AdministrativeGenderEnumFactory().fromType(value); // Enumeration<AdministrativeGender>
break;
case 1178922291: // organization
this.organization = castToReference(value); // Reference
break;
case -991726143: // period
this.period = castToPeriod(value); // Period
break;
default: super.setProperty(hash, name, value);
}
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("relationship"))
this.getRelationship().add(castToCodeableConcept(value));
else if (name.equals("name"))
this.name = castToHumanName(value); // HumanName
else if (name.equals("telecom"))
this.getTelecom().add(castToContactPoint(value));
else if (name.equals("address"))
this.address = castToAddress(value); // Address
else if (name.equals("gender"))
this.gender = new AdministrativeGenderEnumFactory().fromType(value); // Enumeration<AdministrativeGender>
else if (name.equals("organization"))
this.organization = castToReference(value); // Reference
else if (name.equals("period"))
this.period = castToPeriod(value); // Period
else
super.setProperty(name, value);
}
@Override
public Base makeProperty(int hash, String name) throws FHIRException {
switch (hash) {
case -261851592: return addRelationship(); // CodeableConcept
case 3373707: return getName(); // HumanName
case -1429363305: return addTelecom(); // ContactPoint
case -1147692044: return getAddress(); // Address
case -1249512767: throw new FHIRException("Cannot make property gender as it is not a complex type"); // Enumeration<AdministrativeGender>
case 1178922291: return getOrganization(); // Reference
case -991726143: return getPeriod(); // Period
default: return super.makeProperty(hash, name);
}
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("relationship")) {
return addRelationship();
}
else if (name.equals("name")) {
this.name = new HumanName();
return this.name;
}
else if (name.equals("telecom")) {
return addTelecom();
}
else if (name.equals("address")) {
this.address = new Address();
return this.address;
}
else if (name.equals("gender")) {
throw new FHIRException("Cannot call addChild on a primitive type Patient.gender");
}
else if (name.equals("organization")) {
this.organization = new Reference();
return this.organization;
}
else if (name.equals("period")) {
this.period = new Period();
return this.period;
}
else
return super.addChild(name);
}
public ContactComponent copy() {
ContactComponent dst = new ContactComponent();
copyValues(dst);
if (relationship != null) {
dst.relationship = new ArrayList<CodeableConcept>();
for (CodeableConcept i : relationship)
dst.relationship.add(i.copy());
};
dst.name = name == null ? null : name.copy();
if (telecom != null) {
dst.telecom = new ArrayList<ContactPoint>();
for (ContactPoint i : telecom)
dst.telecom.add(i.copy());
};
dst.address = address == null ? null : address.copy();
dst.gender = gender == null ? null : gender.copy();
dst.organization = organization == null ? null : organization.copy();
dst.period = period == null ? null : period.copy();
return dst;
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof ContactComponent))
return false;
ContactComponent o = (ContactComponent) other;
return compareDeep(relationship, o.relationship, true) && compareDeep(name, o.name, true) && compareDeep(telecom, o.telecom, true)
&& compareDeep(address, o.address, true) && compareDeep(gender, o.gender, true) && compareDeep(organization, o.organization, true)
&& compareDeep(period, o.period, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof ContactComponent))
return false;
ContactComponent o = (ContactComponent) other;
return compareValues(gender, o.gender, true);
}
public boolean isEmpty() {
return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(relationship, name, telecom
, address, gender, organization, period);
}
public String fhirType() {
return "Patient.contact";
}
}
@Block()
public static class AnimalComponent extends BackboneElement implements IBaseBackboneElement {
/**
* Identifies the high level taxonomic categorization of the kind of animal.
*/
@Child(name = "species", type = {CodeableConcept.class}, order=1, min=1, max=1, modifier=false, summary=true)
@Description(shortDefinition="E.g. Dog, Cow", formalDefinition="Identifies the high level taxonomic categorization of the kind of animal." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/animal-species")
protected CodeableConcept species;
/**
* Identifies the detailed categorization of the kind of animal.
*/
@Child(name = "breed", type = {CodeableConcept.class}, order=2, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="E.g. Poodle, Angus", formalDefinition="Identifies the detailed categorization of the kind of animal." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/animal-breeds")
protected CodeableConcept breed;
/**
* Indicates the current state of the animal's reproductive organs.
*/
@Child(name = "genderStatus", type = {CodeableConcept.class}, order=3, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="E.g. Neutered, Intact", formalDefinition="Indicates the current state of the animal's reproductive organs." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/animal-genderstatus")
protected CodeableConcept genderStatus;
private static final long serialVersionUID = -549738382L;
/**
* Constructor
*/
public AnimalComponent() {
super();
}
/**
* Constructor
*/
public AnimalComponent(CodeableConcept species) {
super();
this.species = species;
}
/**
* @return {@link #species} (Identifies the high level taxonomic categorization of the kind of animal.)
*/
public CodeableConcept getSpecies() {
if (this.species == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create AnimalComponent.species");
else if (Configuration.doAutoCreate())
this.species = new CodeableConcept(); // cc
return this.species;
}
public boolean hasSpecies() {
return this.species != null && !this.species.isEmpty();
}
/**
* @param value {@link #species} (Identifies the high level taxonomic categorization of the kind of animal.)
*/
public AnimalComponent setSpecies(CodeableConcept value) {
this.species = value;
return this;
}
/**
* @return {@link #breed} (Identifies the detailed categorization of the kind of animal.)
*/
public CodeableConcept getBreed() {
if (this.breed == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create AnimalComponent.breed");
else if (Configuration.doAutoCreate())
this.breed = new CodeableConcept(); // cc
return this.breed;
}
public boolean hasBreed() {
return this.breed != null && !this.breed.isEmpty();
}
/**
* @param value {@link #breed} (Identifies the detailed categorization of the kind of animal.)
*/
public AnimalComponent setBreed(CodeableConcept value) {
this.breed = value;
return this;
}
/**
* @return {@link #genderStatus} (Indicates the current state of the animal's reproductive organs.)
*/
public CodeableConcept getGenderStatus() {
if (this.genderStatus == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create AnimalComponent.genderStatus");
else if (Configuration.doAutoCreate())
this.genderStatus = new CodeableConcept(); // cc
return this.genderStatus;
}
public boolean hasGenderStatus() {
return this.genderStatus != null && !this.genderStatus.isEmpty();
}
/**
* @param value {@link #genderStatus} (Indicates the current state of the animal's reproductive organs.)
*/
public AnimalComponent setGenderStatus(CodeableConcept value) {
this.genderStatus = value;
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("species", "CodeableConcept", "Identifies the high level taxonomic categorization of the kind of animal.", 0, java.lang.Integer.MAX_VALUE, species));
childrenList.add(new Property("breed", "CodeableConcept", "Identifies the detailed categorization of the kind of animal.", 0, java.lang.Integer.MAX_VALUE, breed));
childrenList.add(new Property("genderStatus", "CodeableConcept", "Indicates the current state of the animal's reproductive organs.", 0, java.lang.Integer.MAX_VALUE, genderStatus));
}
@Override
public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
switch (hash) {
case -2008465092: /*species*/ return this.species == null ? new Base[0] : new Base[] {this.species}; // CodeableConcept
case 94001524: /*breed*/ return this.breed == null ? new Base[0] : new Base[] {this.breed}; // CodeableConcept
case -678569453: /*genderStatus*/ return this.genderStatus == null ? new Base[0] : new Base[] {this.genderStatus}; // CodeableConcept
default: return super.getProperty(hash, name, checkValid);
}
}
@Override
public void setProperty(int hash, String name, Base value) throws FHIRException {
switch (hash) {
case -2008465092: // species
this.species = castToCodeableConcept(value); // CodeableConcept
break;
case 94001524: // breed
this.breed = castToCodeableConcept(value); // CodeableConcept
break;
case -678569453: // genderStatus
this.genderStatus = castToCodeableConcept(value); // CodeableConcept
break;
default: super.setProperty(hash, name, value);
}
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("species"))
this.species = castToCodeableConcept(value); // CodeableConcept
else if (name.equals("breed"))
this.breed = castToCodeableConcept(value); // CodeableConcept
else if (name.equals("genderStatus"))
this.genderStatus = castToCodeableConcept(value); // CodeableConcept
else
super.setProperty(name, value);
}
@Override
public Base makeProperty(int hash, String name) throws FHIRException {
switch (hash) {
case -2008465092: return getSpecies(); // CodeableConcept
case 94001524: return getBreed(); // CodeableConcept
case -678569453: return getGenderStatus(); // CodeableConcept
default: return super.makeProperty(hash, name);
}
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("species")) {
this.species = new CodeableConcept();
return this.species;
}
else if (name.equals("breed")) {
this.breed = new CodeableConcept();
return this.breed;
}
else if (name.equals("genderStatus")) {
this.genderStatus = new CodeableConcept();
return this.genderStatus;
}
else
return super.addChild(name);
}
public AnimalComponent copy() {
AnimalComponent dst = new AnimalComponent();
copyValues(dst);
dst.species = species == null ? null : species.copy();
dst.breed = breed == null ? null : breed.copy();
dst.genderStatus = genderStatus == null ? null : genderStatus.copy();
return dst;
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof AnimalComponent))
return false;
AnimalComponent o = (AnimalComponent) other;
return compareDeep(species, o.species, true) && compareDeep(breed, o.breed, true) && compareDeep(genderStatus, o.genderStatus, true)
;
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof AnimalComponent))
return false;
AnimalComponent o = (AnimalComponent) other;
return true;
}
public boolean isEmpty() {
return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(species, breed, genderStatus
);
}
public String fhirType() {
return "Patient.animal";
}
}
@Block()
public static class PatientCommunicationComponent extends BackboneElement implements IBaseBackboneElement {
/**
* The ISO-639-1 alpha 2 code in lower case for the language, optionally followed by a hyphen and the ISO-3166-1 alpha 2 code for the region in upper case; e.g. "en" for English, or "en-US" for American English versus "en-EN" for England English.
*/
@Child(name = "language", type = {CodeableConcept.class}, order=1, min=1, max=1, modifier=false, summary=false)
@Description(shortDefinition="The language which can be used to communicate with the patient about his or her health", formalDefinition="The ISO-639-1 alpha 2 code in lower case for the language, optionally followed by a hyphen and the ISO-3166-1 alpha 2 code for the region in upper case; e.g. \"en\" for English, or \"en-US\" for American English versus \"en-EN\" for England English." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/languages")
protected CodeableConcept language;
/**
* Indicates whether or not the patient prefers this language (over other languages he masters up a certain level).
*/
@Child(name = "preferred", type = {BooleanType.class}, order=2, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Language preference indicator", formalDefinition="Indicates whether or not the patient prefers this language (over other languages he masters up a certain level)." )
protected BooleanType preferred;
private static final long serialVersionUID = 633792918L;
/**
* Constructor
*/
public PatientCommunicationComponent() {
super();
}
/**
* Constructor
*/
public PatientCommunicationComponent(CodeableConcept language) {
super();
this.language = language;
}
/**
* @return {@link #language} (The ISO-639-1 alpha 2 code in lower case for the language, optionally followed by a hyphen and the ISO-3166-1 alpha 2 code for the region in upper case; e.g. "en" for English, or "en-US" for American English versus "en-EN" for England English.)
*/
public CodeableConcept getLanguage() {
if (this.language == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create PatientCommunicationComponent.language");
else if (Configuration.doAutoCreate())
this.language = new CodeableConcept(); // cc
return this.language;
}
public boolean hasLanguage() {
return this.language != null && !this.language.isEmpty();
}
/**
* @param value {@link #language} (The ISO-639-1 alpha 2 code in lower case for the language, optionally followed by a hyphen and the ISO-3166-1 alpha 2 code for the region in upper case; e.g. "en" for English, or "en-US" for American English versus "en-EN" for England English.)
*/
public PatientCommunicationComponent setLanguage(CodeableConcept value) {
this.language = value;
return this;
}
/**
* @return {@link #preferred} (Indicates whether or not the patient prefers this language (over other languages he masters up a certain level).). This is the underlying object with id, value and extensions. The accessor "getPreferred" gives direct access to the value
*/
public BooleanType getPreferredElement() {
if (this.preferred == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create PatientCommunicationComponent.preferred");
else if (Configuration.doAutoCreate())
this.preferred = new BooleanType(); // bb
return this.preferred;
}
public boolean hasPreferredElement() {
return this.preferred != null && !this.preferred.isEmpty();
}
public boolean hasPreferred() {
return this.preferred != null && !this.preferred.isEmpty();
}
/**
* @param value {@link #preferred} (Indicates whether or not the patient prefers this language (over other languages he masters up a certain level).). This is the underlying object with id, value and extensions. The accessor "getPreferred" gives direct access to the value
*/
public PatientCommunicationComponent setPreferredElement(BooleanType value) {
this.preferred = value;
return this;
}
/**
* @return Indicates whether or not the patient prefers this language (over other languages he masters up a certain level).
*/
public boolean getPreferred() {
return this.preferred == null || this.preferred.isEmpty() ? false : this.preferred.getValue();
}
/**
* @param value Indicates whether or not the patient prefers this language (over other languages he masters up a certain level).
*/
public PatientCommunicationComponent setPreferred(boolean value) {
if (this.preferred == null)
this.preferred = new BooleanType();
this.preferred.setValue(value);
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("language", "CodeableConcept", "The ISO-639-1 alpha 2 code in lower case for the language, optionally followed by a hyphen and the ISO-3166-1 alpha 2 code for the region in upper case; e.g. \"en\" for English, or \"en-US\" for American English versus \"en-EN\" for England English.", 0, java.lang.Integer.MAX_VALUE, language));
childrenList.add(new Property("preferred", "boolean", "Indicates whether or not the patient prefers this language (over other languages he masters up a certain level).", 0, java.lang.Integer.MAX_VALUE, preferred));
}
@Override
public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
switch (hash) {
case -1613589672: /*language*/ return this.language == null ? new Base[0] : new Base[] {this.language}; // CodeableConcept
case -1294005119: /*preferred*/ return this.preferred == null ? new Base[0] : new Base[] {this.preferred}; // BooleanType
default: return super.getProperty(hash, name, checkValid);
}
}
@Override
public void setProperty(int hash, String name, Base value) throws FHIRException {
switch (hash) {
case -1613589672: // language
this.language = castToCodeableConcept(value); // CodeableConcept
break;
case -1294005119: // preferred
this.preferred = castToBoolean(value); // BooleanType
break;
default: super.setProperty(hash, name, value);
}
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("language"))
this.language = castToCodeableConcept(value); // CodeableConcept
else if (name.equals("preferred"))
this.preferred = castToBoolean(value); // BooleanType
else
super.setProperty(name, value);
}
@Override
public Base makeProperty(int hash, String name) throws FHIRException {
switch (hash) {
case -1613589672: return getLanguage(); // CodeableConcept
case -1294005119: throw new FHIRException("Cannot make property preferred as it is not a complex type"); // BooleanType
default: return super.makeProperty(hash, name);
}
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("language")) {
this.language = new CodeableConcept();
return this.language;
}
else if (name.equals("preferred")) {
throw new FHIRException("Cannot call addChild on a primitive type Patient.preferred");
}
else
return super.addChild(name);
}
public PatientCommunicationComponent copy() {
PatientCommunicationComponent dst = new PatientCommunicationComponent();
copyValues(dst);
dst.language = language == null ? null : language.copy();
dst.preferred = preferred == null ? null : preferred.copy();
return dst;
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof PatientCommunicationComponent))
return false;
PatientCommunicationComponent o = (PatientCommunicationComponent) other;
return compareDeep(language, o.language, true) && compareDeep(preferred, o.preferred, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof PatientCommunicationComponent))
return false;
PatientCommunicationComponent o = (PatientCommunicationComponent) other;
return compareValues(preferred, o.preferred, true);
}
public boolean isEmpty() {
return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(language, preferred);
}
public String fhirType() {
return "Patient.communication";
}
}
@Block()
public static class PatientLinkComponent extends BackboneElement implements IBaseBackboneElement {
/**
* The other patient resource that the link refers to.
*/
@Child(name = "other", type = {Patient.class, RelatedPerson.class}, order=1, min=1, max=1, modifier=true, summary=true)
@Description(shortDefinition="The other patient or related person resource that the link refers to", formalDefinition="The other patient resource that the link refers to." )
protected Reference other;
/**
* The actual object that is the target of the reference (The other patient resource that the link refers to.)
*/
protected Resource otherTarget;
/**
* The type of link between this patient resource and another patient resource.
*/
@Child(name = "type", type = {CodeType.class}, order=2, min=1, max=1, modifier=true, summary=true)
@Description(shortDefinition="replace | refer | seealso - type of link", formalDefinition="The type of link between this patient resource and another patient resource." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/link-type")
protected Enumeration<LinkType> type;
private static final long serialVersionUID = 1083576633L;
/**
* Constructor
*/
public PatientLinkComponent() {
super();
}
/**
* Constructor
*/
public PatientLinkComponent(Reference other, Enumeration<LinkType> type) {
super();
this.other = other;
this.type = type;
}
/**
* @return {@link #other} (The other patient resource that the link refers to.)
*/
public Reference getOther() {
if (this.other == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create PatientLinkComponent.other");
else if (Configuration.doAutoCreate())
this.other = new Reference(); // cc
return this.other;
}
public boolean hasOther() {
return this.other != null && !this.other.isEmpty();
}
/**
* @param value {@link #other} (The other patient resource that the link refers to.)
*/
public PatientLinkComponent setOther(Reference value) {
this.other = value;
return this;
}
/**
* @return {@link #other} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The other patient resource that the link refers to.)
*/
public Resource getOtherTarget() {
return this.otherTarget;
}
/**
* @param value {@link #other} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The other patient resource that the link refers to.)
*/
public PatientLinkComponent setOtherTarget(Resource value) {
this.otherTarget = value;
return this;
}
/**
* @return {@link #type} (The type of link between this patient resource and another patient resource.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value
*/
public Enumeration<LinkType> getTypeElement() {
if (this.type == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create PatientLinkComponent.type");
else if (Configuration.doAutoCreate())
this.type = new Enumeration<LinkType>(new LinkTypeEnumFactory()); // bb
return this.type;
}
public boolean hasTypeElement() {
return this.type != null && !this.type.isEmpty();
}
public boolean hasType() {
return this.type != null && !this.type.isEmpty();
}
/**
* @param value {@link #type} (The type of link between this patient resource and another patient resource.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value
*/
public PatientLinkComponent setTypeElement(Enumeration<LinkType> value) {
this.type = value;
return this;
}
/**
* @return The type of link between this patient resource and another patient resource.
*/
public LinkType getType() {
return this.type == null ? null : this.type.getValue();
}
/**
* @param value The type of link between this patient resource and another patient resource.
*/
public PatientLinkComponent setType(LinkType value) {
if (this.type == null)
this.type = new Enumeration<LinkType>(new LinkTypeEnumFactory());
this.type.setValue(value);
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("other", "Reference(Patient|RelatedPerson)", "The other patient resource that the link refers to.", 0, java.lang.Integer.MAX_VALUE, other));
childrenList.add(new Property("type", "code", "The type of link between this patient resource and another patient resource.", 0, java.lang.Integer.MAX_VALUE, type));
}
@Override
public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
switch (hash) {
case 106069776: /*other*/ return this.other == null ? new Base[0] : new Base[] {this.other}; // Reference
case 3575610: /*type*/ return this.type == null ? new Base[0] : new Base[] {this.type}; // Enumeration<LinkType>
default: return super.getProperty(hash, name, checkValid);
}
}
@Override
public void setProperty(int hash, String name, Base value) throws FHIRException {
switch (hash) {
case 106069776: // other
this.other = castToReference(value); // Reference
break;
case 3575610: // type
this.type = new LinkTypeEnumFactory().fromType(value); // Enumeration<LinkType>
break;
default: super.setProperty(hash, name, value);
}
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("other"))
this.other = castToReference(value); // Reference
else if (name.equals("type"))
this.type = new LinkTypeEnumFactory().fromType(value); // Enumeration<LinkType>
else
super.setProperty(name, value);
}
@Override
public Base makeProperty(int hash, String name) throws FHIRException {
switch (hash) {
case 106069776: return getOther(); // Reference
case 3575610: throw new FHIRException("Cannot make property type as it is not a complex type"); // Enumeration<LinkType>
default: return super.makeProperty(hash, name);
}
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("other")) {
this.other = new Reference();
return this.other;
}
else if (name.equals("type")) {
throw new FHIRException("Cannot call addChild on a primitive type Patient.type");
}
else
return super.addChild(name);
}
public PatientLinkComponent copy() {
PatientLinkComponent dst = new PatientLinkComponent();
copyValues(dst);
dst.other = other == null ? null : other.copy();
dst.type = type == null ? null : type.copy();
return dst;
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof PatientLinkComponent))
return false;
PatientLinkComponent o = (PatientLinkComponent) other;
return compareDeep(other, o.other, true) && compareDeep(type, o.type, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof PatientLinkComponent))
return false;
PatientLinkComponent o = (PatientLinkComponent) other;
return compareValues(type, o.type, true);
}
public boolean isEmpty() {
return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(other, type);
}
public String fhirType() {
return "Patient.link";
}
}
/**
* An identifier for this patient.
*/
@Child(name = "identifier", type = {Identifier.class}, order=0, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="An identifier for this patient", formalDefinition="An identifier for this patient." )
protected List<Identifier> identifier;
/**
* Whether this patient record is in active use.
*/
@Child(name = "active", type = {BooleanType.class}, order=1, min=0, max=1, modifier=true, summary=true)
@Description(shortDefinition="Whether this patient's record is in active use", formalDefinition="Whether this patient record is in active use." )
protected BooleanType active;
/**
* A name associated with the individual.
*/
@Child(name = "name", type = {HumanName.class}, order=2, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="A name associated with the patient", formalDefinition="A name associated with the individual." )
protected List<HumanName> name;
/**
* A contact detail (e.g. a telephone number or an email address) by which the individual may be contacted.
*/
@Child(name = "telecom", type = {ContactPoint.class}, order=3, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="A contact detail for the individual", formalDefinition="A contact detail (e.g. a telephone number or an email address) by which the individual may be contacted." )
protected List<ContactPoint> telecom;
/**
* Administrative Gender - the gender that the patient is considered to have for administration and record keeping purposes.
*/
@Child(name = "gender", type = {CodeType.class}, order=4, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="male | female | other | unknown", formalDefinition="Administrative Gender - the gender that the patient is considered to have for administration and record keeping purposes." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/administrative-gender")
protected Enumeration<AdministrativeGender> gender;
/**
* The date of birth for the individual.
*/
@Child(name = "birthDate", type = {DateType.class}, order=5, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="The date of birth for the individual", formalDefinition="The date of birth for the individual." )
protected DateType birthDate;
/**
* Indicates if the individual is deceased or not.
*/
@Child(name = "deceased", type = {BooleanType.class, DateTimeType.class}, order=6, min=0, max=1, modifier=true, summary=true)
@Description(shortDefinition="Indicates if the individual is deceased or not", formalDefinition="Indicates if the individual is deceased or not." )
protected Type deceased;
/**
* Addresses for the individual.
*/
@Child(name = "address", type = {Address.class}, order=7, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Addresses for the individual", formalDefinition="Addresses for the individual." )
protected List<Address> address;
/**
* This field contains a patient's most recent marital (civil) status.
*/
@Child(name = "maritalStatus", type = {CodeableConcept.class}, order=8, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Marital (civil) status of a patient", formalDefinition="This field contains a patient's most recent marital (civil) status." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/marital-status")
protected CodeableConcept maritalStatus;
/**
* Indicates whether the patient is part of a multiple (bool) or indicates the actual birth order (integer).
*/
@Child(name = "multipleBirth", type = {BooleanType.class, IntegerType.class}, order=9, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Whether patient is part of a multiple birth", formalDefinition="Indicates whether the patient is part of a multiple (bool) or indicates the actual birth order (integer)." )
protected Type multipleBirth;
/**
* Image of the patient.
*/
@Child(name = "photo", type = {Attachment.class}, order=10, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
@Description(shortDefinition="Image of the patient", formalDefinition="Image of the patient." )
protected List<Attachment> photo;
/**
* A contact party (e.g. guardian, partner, friend) for the patient.
*/
@Child(name = "contact", type = {}, order=11, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
@Description(shortDefinition="A contact party (e.g. guardian, partner, friend) for the patient", formalDefinition="A contact party (e.g. guardian, partner, friend) for the patient." )
protected List<ContactComponent> contact;
/**
* This patient is known to be an animal.
*/
@Child(name = "animal", type = {}, order=12, min=0, max=1, modifier=true, summary=true)
@Description(shortDefinition="This patient is known to be an animal (non-human)", formalDefinition="This patient is known to be an animal." )
protected AnimalComponent animal;
/**
* Languages which may be used to communicate with the patient about his or her health.
*/
@Child(name = "communication", type = {}, order=13, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
@Description(shortDefinition="A list of Languages which may be used to communicate with the patient about his or her health", formalDefinition="Languages which may be used to communicate with the patient about his or her health." )
protected List<PatientCommunicationComponent> communication;
/**
* Patient's nominated care provider.
*/
@Child(name = "generalPractitioner", type = {Organization.class, Practitioner.class}, order=14, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
@Description(shortDefinition="Patient's nominated primary care provider", formalDefinition="Patient's nominated care provider." )
protected List<Reference> generalPractitioner;
/**
* The actual objects that are the target of the reference (Patient's nominated care provider.)
*/
protected List<Resource> generalPractitionerTarget;
/**
* Organization that is the custodian of the patient record.
*/
@Child(name = "managingOrganization", type = {Organization.class}, order=15, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Organization that is the custodian of the patient record", formalDefinition="Organization that is the custodian of the patient record." )
protected Reference managingOrganization;
/**
* The actual object that is the target of the reference (Organization that is the custodian of the patient record.)
*/
protected Organization managingOrganizationTarget;
/**
* Link to another patient resource that concerns the same actual patient.
*/
@Child(name = "link", type = {}, order=16, min=0, max=Child.MAX_UNLIMITED, modifier=true, summary=true)
@Description(shortDefinition="Link to another patient resource that concerns the same actual person", formalDefinition="Link to another patient resource that concerns the same actual patient." )
protected List<PatientLinkComponent> link;
private static final long serialVersionUID = -1985061666L;
/**
* Constructor
*/
public Patient() {
super();
}
/**
* @return {@link #identifier} (An identifier for this patient.)
*/
public List<Identifier> getIdentifier() {
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
return this.identifier;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public Patient setIdentifier(List<Identifier> theIdentifier) {
this.identifier = theIdentifier;
return this;
}
public boolean hasIdentifier() {
if (this.identifier == null)
return false;
for (Identifier item : this.identifier)
if (!item.isEmpty())
return true;
return false;
}
public Identifier addIdentifier() { //3
Identifier t = new Identifier();
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return t;
}
public Patient addIdentifier(Identifier t) { //3
if (t == null)
return this;
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #identifier}, creating it if it does not already exist
*/
public Identifier getIdentifierFirstRep() {
if (getIdentifier().isEmpty()) {
addIdentifier();
}
return getIdentifier().get(0);
}
/**
* @return {@link #active} (Whether this patient record is in active use.). This is the underlying object with id, value and extensions. The accessor "getActive" gives direct access to the value
*/
public BooleanType getActiveElement() {
if (this.active == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Patient.active");
else if (Configuration.doAutoCreate())
this.active = new BooleanType(); // bb
return this.active;
}
public boolean hasActiveElement() {
return this.active != null && !this.active.isEmpty();
}
public boolean hasActive() {
return this.active != null && !this.active.isEmpty();
}
/**
* @param value {@link #active} (Whether this patient record is in active use.). This is the underlying object with id, value and extensions. The accessor "getActive" gives direct access to the value
*/
public Patient setActiveElement(BooleanType value) {
this.active = value;
return this;
}
/**
* @return Whether this patient record is in active use.
*/
public boolean getActive() {
return this.active == null || this.active.isEmpty() ? false : this.active.getValue();
}
/**
* @param value Whether this patient record is in active use.
*/
public Patient setActive(boolean value) {
if (this.active == null)
this.active = new BooleanType();
this.active.setValue(value);
return this;
}
/**
* @return {@link #name} (A name associated with the individual.)
*/
public List<HumanName> getName() {
if (this.name == null)
this.name = new ArrayList<HumanName>();
return this.name;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public Patient setName(List<HumanName> theName) {
this.name = theName;
return this;
}
public boolean hasName() {
if (this.name == null)
return false;
for (HumanName item : this.name)
if (!item.isEmpty())
return true;
return false;
}
public HumanName addName() { //3
HumanName t = new HumanName();
if (this.name == null)
this.name = new ArrayList<HumanName>();
this.name.add(t);
return t;
}
public Patient addName(HumanName t) { //3
if (t == null)
return this;
if (this.name == null)
this.name = new ArrayList<HumanName>();
this.name.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #name}, creating it if it does not already exist
*/
public HumanName getNameFirstRep() {
if (getName().isEmpty()) {
addName();
}
return getName().get(0);
}
/**
* @return {@link #telecom} (A contact detail (e.g. a telephone number or an email address) by which the individual may be contacted.)
*/
public List<ContactPoint> getTelecom() {
if (this.telecom == null)
this.telecom = new ArrayList<ContactPoint>();
return this.telecom;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public Patient setTelecom(List<ContactPoint> theTelecom) {
this.telecom = theTelecom;
return this;
}
public boolean hasTelecom() {
if (this.telecom == null)
return false;
for (ContactPoint item : this.telecom)
if (!item.isEmpty())
return true;
return false;
}
public ContactPoint addTelecom() { //3
ContactPoint t = new ContactPoint();
if (this.telecom == null)
this.telecom = new ArrayList<ContactPoint>();
this.telecom.add(t);
return t;
}
public Patient addTelecom(ContactPoint t) { //3
if (t == null)
return this;
if (this.telecom == null)
this.telecom = new ArrayList<ContactPoint>();
this.telecom.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #telecom}, creating it if it does not already exist
*/
public ContactPoint getTelecomFirstRep() {
if (getTelecom().isEmpty()) {
addTelecom();
}
return getTelecom().get(0);
}
/**
* @return {@link #gender} (Administrative Gender - the gender that the patient is considered to have for administration and record keeping purposes.). This is the underlying object with id, value and extensions. The accessor "getGender" gives direct access to the value
*/
public Enumeration<AdministrativeGender> getGenderElement() {
if (this.gender == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Patient.gender");
else if (Configuration.doAutoCreate())
this.gender = new Enumeration<AdministrativeGender>(new AdministrativeGenderEnumFactory()); // bb
return this.gender;
}
public boolean hasGenderElement() {
return this.gender != null && !this.gender.isEmpty();
}
public boolean hasGender() {
return this.gender != null && !this.gender.isEmpty();
}
/**
* @param value {@link #gender} (Administrative Gender - the gender that the patient is considered to have for administration and record keeping purposes.). This is the underlying object with id, value and extensions. The accessor "getGender" gives direct access to the value
*/
public Patient setGenderElement(Enumeration<AdministrativeGender> value) {
this.gender = value;
return this;
}
/**
* @return Administrative Gender - the gender that the patient is considered to have for administration and record keeping purposes.
*/
public AdministrativeGender getGender() {
return this.gender == null ? null : this.gender.getValue();
}
/**
* @param value Administrative Gender - the gender that the patient is considered to have for administration and record keeping purposes.
*/
public Patient setGender(AdministrativeGender value) {
if (value == null)
this.gender = null;
else {
if (this.gender == null)
this.gender = new Enumeration<AdministrativeGender>(new AdministrativeGenderEnumFactory());
this.gender.setValue(value);
}
return this;
}
/**
* @return {@link #birthDate} (The date of birth for the individual.). This is the underlying object with id, value and extensions. The accessor "getBirthDate" gives direct access to the value
*/
public DateType getBirthDateElement() {
if (this.birthDate == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Patient.birthDate");
else if (Configuration.doAutoCreate())
this.birthDate = new DateType(); // bb
return this.birthDate;
}
public boolean hasBirthDateElement() {
return this.birthDate != null && !this.birthDate.isEmpty();
}
public boolean hasBirthDate() {
return this.birthDate != null && !this.birthDate.isEmpty();
}
/**
* @param value {@link #birthDate} (The date of birth for the individual.). This is the underlying object with id, value and extensions. The accessor "getBirthDate" gives direct access to the value
*/
public Patient setBirthDateElement(DateType value) {
this.birthDate = value;
return this;
}
/**
* @return The date of birth for the individual.
*/
public Date getBirthDate() {
return this.birthDate == null ? null : this.birthDate.getValue();
}
/**
* @param value The date of birth for the individual.
*/
public Patient setBirthDate(Date value) {
if (value == null)
this.birthDate = null;
else {
if (this.birthDate == null)
this.birthDate = new DateType();
this.birthDate.setValue(value);
}
return this;
}
/**
* @return {@link #deceased} (Indicates if the individual is deceased or not.)
*/
public Type getDeceased() {
return this.deceased;
}
/**
* @return {@link #deceased} (Indicates if the individual is deceased or not.)
*/
public BooleanType getDeceasedBooleanType() throws FHIRException {
if (!(this.deceased instanceof BooleanType))
throw new FHIRException("Type mismatch: the type BooleanType was expected, but "+this.deceased.getClass().getName()+" was encountered");
return (BooleanType) this.deceased;
}
public boolean hasDeceasedBooleanType() {
return this.deceased instanceof BooleanType;
}
/**
* @return {@link #deceased} (Indicates if the individual is deceased or not.)
*/
public DateTimeType getDeceasedDateTimeType() throws FHIRException {
if (!(this.deceased instanceof DateTimeType))
throw new FHIRException("Type mismatch: the type DateTimeType was expected, but "+this.deceased.getClass().getName()+" was encountered");
return (DateTimeType) this.deceased;
}
public boolean hasDeceasedDateTimeType() {
return this.deceased instanceof DateTimeType;
}
public boolean hasDeceased() {
return this.deceased != null && !this.deceased.isEmpty();
}
/**
* @param value {@link #deceased} (Indicates if the individual is deceased or not.)
*/
public Patient setDeceased(Type value) {
this.deceased = value;
return this;
}
/**
* @return {@link #address} (Addresses for the individual.)
*/
public List<Address> getAddress() {
if (this.address == null)
this.address = new ArrayList<Address>();
return this.address;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public Patient setAddress(List<Address> theAddress) {
this.address = theAddress;
return this;
}
public boolean hasAddress() {
if (this.address == null)
return false;
for (Address item : this.address)
if (!item.isEmpty())
return true;
return false;
}
public Address addAddress() { //3
Address t = new Address();
if (this.address == null)
this.address = new ArrayList<Address>();
this.address.add(t);
return t;
}
public Patient addAddress(Address t) { //3
if (t == null)
return this;
if (this.address == null)
this.address = new ArrayList<Address>();
this.address.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #address}, creating it if it does not already exist
*/
public Address getAddressFirstRep() {
if (getAddress().isEmpty()) {
addAddress();
}
return getAddress().get(0);
}
/**
* @return {@link #maritalStatus} (This field contains a patient's most recent marital (civil) status.)
*/
public CodeableConcept getMaritalStatus() {
if (this.maritalStatus == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Patient.maritalStatus");
else if (Configuration.doAutoCreate())
this.maritalStatus = new CodeableConcept(); // cc
return this.maritalStatus;
}
public boolean hasMaritalStatus() {
return this.maritalStatus != null && !this.maritalStatus.isEmpty();
}
/**
* @param value {@link #maritalStatus} (This field contains a patient's most recent marital (civil) status.)
*/
public Patient setMaritalStatus(CodeableConcept value) {
this.maritalStatus = value;
return this;
}
/**
* @return {@link #multipleBirth} (Indicates whether the patient is part of a multiple (bool) or indicates the actual birth order (integer).)
*/
public Type getMultipleBirth() {
return this.multipleBirth;
}
/**
* @return {@link #multipleBirth} (Indicates whether the patient is part of a multiple (bool) or indicates the actual birth order (integer).)
*/
public BooleanType getMultipleBirthBooleanType() throws FHIRException {
if (!(this.multipleBirth instanceof BooleanType))
throw new FHIRException("Type mismatch: the type BooleanType was expected, but "+this.multipleBirth.getClass().getName()+" was encountered");
return (BooleanType) this.multipleBirth;
}
public boolean hasMultipleBirthBooleanType() {
return this.multipleBirth instanceof BooleanType;
}
/**
* @return {@link #multipleBirth} (Indicates whether the patient is part of a multiple (bool) or indicates the actual birth order (integer).)
*/
public IntegerType getMultipleBirthIntegerType() throws FHIRException {
if (!(this.multipleBirth instanceof IntegerType))
throw new FHIRException("Type mismatch: the type IntegerType was expected, but "+this.multipleBirth.getClass().getName()+" was encountered");
return (IntegerType) this.multipleBirth;
}
public boolean hasMultipleBirthIntegerType() {
return this.multipleBirth instanceof IntegerType;
}
public boolean hasMultipleBirth() {
return this.multipleBirth != null && !this.multipleBirth.isEmpty();
}
/**
* @param value {@link #multipleBirth} (Indicates whether the patient is part of a multiple (bool) or indicates the actual birth order (integer).)
*/
public Patient setMultipleBirth(Type value) {
this.multipleBirth = value;
return this;
}
/**
* @return {@link #photo} (Image of the patient.)
*/
public List<Attachment> getPhoto() {
if (this.photo == null)
this.photo = new ArrayList<Attachment>();
return this.photo;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public Patient setPhoto(List<Attachment> thePhoto) {
this.photo = thePhoto;
return this;
}
public boolean hasPhoto() {
if (this.photo == null)
return false;
for (Attachment item : this.photo)
if (!item.isEmpty())
return true;
return false;
}
public Attachment addPhoto() { //3
Attachment t = new Attachment();
if (this.photo == null)
this.photo = new ArrayList<Attachment>();
this.photo.add(t);
return t;
}
public Patient addPhoto(Attachment t) { //3
if (t == null)
return this;
if (this.photo == null)
this.photo = new ArrayList<Attachment>();
this.photo.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #photo}, creating it if it does not already exist
*/
public Attachment getPhotoFirstRep() {
if (getPhoto().isEmpty()) {
addPhoto();
}
return getPhoto().get(0);
}
/**
* @return {@link #contact} (A contact party (e.g. guardian, partner, friend) for the patient.)
*/
public List<ContactComponent> getContact() {
if (this.contact == null)
this.contact = new ArrayList<ContactComponent>();
return this.contact;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public Patient setContact(List<ContactComponent> theContact) {
this.contact = theContact;
return this;
}
public boolean hasContact() {
if (this.contact == null)
return false;
for (ContactComponent item : this.contact)
if (!item.isEmpty())
return true;
return false;
}
public ContactComponent addContact() { //3
ContactComponent t = new ContactComponent();
if (this.contact == null)
this.contact = new ArrayList<ContactComponent>();
this.contact.add(t);
return t;
}
public Patient addContact(ContactComponent t) { //3
if (t == null)
return this;
if (this.contact == null)
this.contact = new ArrayList<ContactComponent>();
this.contact.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #contact}, creating it if it does not already exist
*/
public ContactComponent getContactFirstRep() {
if (getContact().isEmpty()) {
addContact();
}
return getContact().get(0);
}
/**
* @return {@link #animal} (This patient is known to be an animal.)
*/
public AnimalComponent getAnimal() {
if (this.animal == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Patient.animal");
else if (Configuration.doAutoCreate())
this.animal = new AnimalComponent(); // cc
return this.animal;
}
public boolean hasAnimal() {
return this.animal != null && !this.animal.isEmpty();
}
/**
* @param value {@link #animal} (This patient is known to be an animal.)
*/
public Patient setAnimal(AnimalComponent value) {
this.animal = value;
return this;
}
/**
* @return {@link #communication} (Languages which may be used to communicate with the patient about his or her health.)
*/
public List<PatientCommunicationComponent> getCommunication() {
if (this.communication == null)
this.communication = new ArrayList<PatientCommunicationComponent>();
return this.communication;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public Patient setCommunication(List<PatientCommunicationComponent> theCommunication) {
this.communication = theCommunication;
return this;
}
public boolean hasCommunication() {
if (this.communication == null)
return false;
for (PatientCommunicationComponent item : this.communication)
if (!item.isEmpty())
return true;
return false;
}
public PatientCommunicationComponent addCommunication() { //3
PatientCommunicationComponent t = new PatientCommunicationComponent();
if (this.communication == null)
this.communication = new ArrayList<PatientCommunicationComponent>();
this.communication.add(t);
return t;
}
public Patient addCommunication(PatientCommunicationComponent t) { //3
if (t == null)
return this;
if (this.communication == null)
this.communication = new ArrayList<PatientCommunicationComponent>();
this.communication.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #communication}, creating it if it does not already exist
*/
public PatientCommunicationComponent getCommunicationFirstRep() {
if (getCommunication().isEmpty()) {
addCommunication();
}
return getCommunication().get(0);
}
/**
* @return {@link #generalPractitioner} (Patient's nominated care provider.)
*/
public List<Reference> getGeneralPractitioner() {
if (this.generalPractitioner == null)
this.generalPractitioner = new ArrayList<Reference>();
return this.generalPractitioner;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public Patient setGeneralPractitioner(List<Reference> theGeneralPractitioner) {
this.generalPractitioner = theGeneralPractitioner;
return this;
}
public boolean hasGeneralPractitioner() {
if (this.generalPractitioner == null)
return false;
for (Reference item : this.generalPractitioner)
if (!item.isEmpty())
return true;
return false;
}
public Reference addGeneralPractitioner() { //3
Reference t = new Reference();
if (this.generalPractitioner == null)
this.generalPractitioner = new ArrayList<Reference>();
this.generalPractitioner.add(t);
return t;
}
public Patient addGeneralPractitioner(Reference t) { //3
if (t == null)
return this;
if (this.generalPractitioner == null)
this.generalPractitioner = new ArrayList<Reference>();
this.generalPractitioner.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #generalPractitioner}, creating it if it does not already exist
*/
public Reference getGeneralPractitionerFirstRep() {
if (getGeneralPractitioner().isEmpty()) {
addGeneralPractitioner();
}
return getGeneralPractitioner().get(0);
}
/**
* @deprecated Use Reference#setResource(IBaseResource) instead
*/
@Deprecated
public List<Resource> getGeneralPractitionerTarget() {
if (this.generalPractitionerTarget == null)
this.generalPractitionerTarget = new ArrayList<Resource>();
return this.generalPractitionerTarget;
}
/**
* @return {@link #managingOrganization} (Organization that is the custodian of the patient record.)
*/
public Reference getManagingOrganization() {
if (this.managingOrganization == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Patient.managingOrganization");
else if (Configuration.doAutoCreate())
this.managingOrganization = new Reference(); // cc
return this.managingOrganization;
}
public boolean hasManagingOrganization() {
return this.managingOrganization != null && !this.managingOrganization.isEmpty();
}
/**
* @param value {@link #managingOrganization} (Organization that is the custodian of the patient record.)
*/
public Patient setManagingOrganization(Reference value) {
this.managingOrganization = value;
return this;
}
/**
* @return {@link #managingOrganization} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Organization that is the custodian of the patient record.)
*/
public Organization getManagingOrganizationTarget() {
if (this.managingOrganizationTarget == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Patient.managingOrganization");
else if (Configuration.doAutoCreate())
this.managingOrganizationTarget = new Organization(); // aa
return this.managingOrganizationTarget;
}
/**
* @param value {@link #managingOrganization} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Organization that is the custodian of the patient record.)
*/
public Patient setManagingOrganizationTarget(Organization value) {
this.managingOrganizationTarget = value;
return this;
}
/**
* @return {@link #link} (Link to another patient resource that concerns the same actual patient.)
*/
public List<PatientLinkComponent> getLink() {
if (this.link == null)
this.link = new ArrayList<PatientLinkComponent>();
return this.link;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public Patient setLink(List<PatientLinkComponent> theLink) {
this.link = theLink;
return this;
}
public boolean hasLink() {
if (this.link == null)
return false;
for (PatientLinkComponent item : this.link)
if (!item.isEmpty())
return true;
return false;
}
public PatientLinkComponent addLink() { //3
PatientLinkComponent t = new PatientLinkComponent();
if (this.link == null)
this.link = new ArrayList<PatientLinkComponent>();
this.link.add(t);
return t;
}
public Patient addLink(PatientLinkComponent t) { //3
if (t == null)
return this;
if (this.link == null)
this.link = new ArrayList<PatientLinkComponent>();
this.link.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #link}, creating it if it does not already exist
*/
public PatientLinkComponent getLinkFirstRep() {
if (getLink().isEmpty()) {
addLink();
}
return getLink().get(0);
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("identifier", "Identifier", "An identifier for this patient.", 0, java.lang.Integer.MAX_VALUE, identifier));
childrenList.add(new Property("active", "boolean", "Whether this patient record is in active use.", 0, java.lang.Integer.MAX_VALUE, active));
childrenList.add(new Property("name", "HumanName", "A name associated with the individual.", 0, java.lang.Integer.MAX_VALUE, name));
childrenList.add(new Property("telecom", "ContactPoint", "A contact detail (e.g. a telephone number or an email address) by which the individual may be contacted.", 0, java.lang.Integer.MAX_VALUE, telecom));
childrenList.add(new Property("gender", "code", "Administrative Gender - the gender that the patient is considered to have for administration and record keeping purposes.", 0, java.lang.Integer.MAX_VALUE, gender));
childrenList.add(new Property("birthDate", "date", "The date of birth for the individual.", 0, java.lang.Integer.MAX_VALUE, birthDate));
childrenList.add(new Property("deceased[x]", "boolean|dateTime", "Indicates if the individual is deceased or not.", 0, java.lang.Integer.MAX_VALUE, deceased));
childrenList.add(new Property("address", "Address", "Addresses for the individual.", 0, java.lang.Integer.MAX_VALUE, address));
childrenList.add(new Property("maritalStatus", "CodeableConcept", "This field contains a patient's most recent marital (civil) status.", 0, java.lang.Integer.MAX_VALUE, maritalStatus));
childrenList.add(new Property("multipleBirth[x]", "boolean|integer", "Indicates whether the patient is part of a multiple (bool) or indicates the actual birth order (integer).", 0, java.lang.Integer.MAX_VALUE, multipleBirth));
childrenList.add(new Property("photo", "Attachment", "Image of the patient.", 0, java.lang.Integer.MAX_VALUE, photo));
childrenList.add(new Property("contact", "", "A contact party (e.g. guardian, partner, friend) for the patient.", 0, java.lang.Integer.MAX_VALUE, contact));
childrenList.add(new Property("animal", "", "This patient is known to be an animal.", 0, java.lang.Integer.MAX_VALUE, animal));
childrenList.add(new Property("communication", "", "Languages which may be used to communicate with the patient about his or her health.", 0, java.lang.Integer.MAX_VALUE, communication));
childrenList.add(new Property("generalPractitioner", "Reference(Organization|Practitioner)", "Patient's nominated care provider.", 0, java.lang.Integer.MAX_VALUE, generalPractitioner));
childrenList.add(new Property("managingOrganization", "Reference(Organization)", "Organization that is the custodian of the patient record.", 0, java.lang.Integer.MAX_VALUE, managingOrganization));
childrenList.add(new Property("link", "", "Link to another patient resource that concerns the same actual patient.", 0, java.lang.Integer.MAX_VALUE, link));
}
@Override
public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
switch (hash) {
case -1618432855: /*identifier*/ return this.identifier == null ? new Base[0] : this.identifier.toArray(new Base[this.identifier.size()]); // Identifier
case -1422950650: /*active*/ return this.active == null ? new Base[0] : new Base[] {this.active}; // BooleanType
case 3373707: /*name*/ return this.name == null ? new Base[0] : this.name.toArray(new Base[this.name.size()]); // HumanName
case -1429363305: /*telecom*/ return this.telecom == null ? new Base[0] : this.telecom.toArray(new Base[this.telecom.size()]); // ContactPoint
case -1249512767: /*gender*/ return this.gender == null ? new Base[0] : new Base[] {this.gender}; // Enumeration<AdministrativeGender>
case -1210031859: /*birthDate*/ return this.birthDate == null ? new Base[0] : new Base[] {this.birthDate}; // DateType
case 561497972: /*deceased*/ return this.deceased == null ? new Base[0] : new Base[] {this.deceased}; // Type
case -1147692044: /*address*/ return this.address == null ? new Base[0] : this.address.toArray(new Base[this.address.size()]); // Address
case 1756919302: /*maritalStatus*/ return this.maritalStatus == null ? new Base[0] : new Base[] {this.maritalStatus}; // CodeableConcept
case -677369713: /*multipleBirth*/ return this.multipleBirth == null ? new Base[0] : new Base[] {this.multipleBirth}; // Type
case 106642994: /*photo*/ return this.photo == null ? new Base[0] : this.photo.toArray(new Base[this.photo.size()]); // Attachment
case 951526432: /*contact*/ return this.contact == null ? new Base[0] : this.contact.toArray(new Base[this.contact.size()]); // ContactComponent
case -1413116420: /*animal*/ return this.animal == null ? new Base[0] : new Base[] {this.animal}; // AnimalComponent
case -1035284522: /*communication*/ return this.communication == null ? new Base[0] : this.communication.toArray(new Base[this.communication.size()]); // PatientCommunicationComponent
case 1488292898: /*generalPractitioner*/ return this.generalPractitioner == null ? new Base[0] : this.generalPractitioner.toArray(new Base[this.generalPractitioner.size()]); // Reference
case -2058947787: /*managingOrganization*/ return this.managingOrganization == null ? new Base[0] : new Base[] {this.managingOrganization}; // Reference
case 3321850: /*link*/ return this.link == null ? new Base[0] : this.link.toArray(new Base[this.link.size()]); // PatientLinkComponent
default: return super.getProperty(hash, name, checkValid);
}
}
@Override
public void setProperty(int hash, String name, Base value) throws FHIRException {
switch (hash) {
case -1618432855: // identifier
this.getIdentifier().add(castToIdentifier(value)); // Identifier
break;
case -1422950650: // active
this.active = castToBoolean(value); // BooleanType
break;
case 3373707: // name
this.getName().add(castToHumanName(value)); // HumanName
break;
case -1429363305: // telecom
this.getTelecom().add(castToContactPoint(value)); // ContactPoint
break;
case -1249512767: // gender
this.gender = new AdministrativeGenderEnumFactory().fromType(value); // Enumeration<AdministrativeGender>
break;
case -1210031859: // birthDate
this.birthDate = castToDate(value); // DateType
break;
case 561497972: // deceased
this.deceased = castToType(value); // Type
break;
case -1147692044: // address
this.getAddress().add(castToAddress(value)); // Address
break;
case 1756919302: // maritalStatus
this.maritalStatus = castToCodeableConcept(value); // CodeableConcept
break;
case -677369713: // multipleBirth
this.multipleBirth = castToType(value); // Type
break;
case 106642994: // photo
this.getPhoto().add(castToAttachment(value)); // Attachment
break;
case 951526432: // contact
this.getContact().add((ContactComponent) value); // ContactComponent
break;
case -1413116420: // animal
this.animal = (AnimalComponent) value; // AnimalComponent
break;
case -1035284522: // communication
this.getCommunication().add((PatientCommunicationComponent) value); // PatientCommunicationComponent
break;
case 1488292898: // generalPractitioner
this.getGeneralPractitioner().add(castToReference(value)); // Reference
break;
case -2058947787: // managingOrganization
this.managingOrganization = castToReference(value); // Reference
break;
case 3321850: // link
this.getLink().add((PatientLinkComponent) value); // PatientLinkComponent
break;
default: super.setProperty(hash, name, value);
}
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("identifier"))
this.getIdentifier().add(castToIdentifier(value));
else if (name.equals("active"))
this.active = castToBoolean(value); // BooleanType
else if (name.equals("name"))
this.getName().add(castToHumanName(value));
else if (name.equals("telecom"))
this.getTelecom().add(castToContactPoint(value));
else if (name.equals("gender"))
this.gender = new AdministrativeGenderEnumFactory().fromType(value); // Enumeration<AdministrativeGender>
else if (name.equals("birthDate"))
this.birthDate = castToDate(value); // DateType
else if (name.equals("deceased[x]"))
this.deceased = castToType(value); // Type
else if (name.equals("address"))
this.getAddress().add(castToAddress(value));
else if (name.equals("maritalStatus"))
this.maritalStatus = castToCodeableConcept(value); // CodeableConcept
else if (name.equals("multipleBirth[x]"))
this.multipleBirth = castToType(value); // Type
else if (name.equals("photo"))
this.getPhoto().add(castToAttachment(value));
else if (name.equals("contact"))
this.getContact().add((ContactComponent) value);
else if (name.equals("animal"))
this.animal = (AnimalComponent) value; // AnimalComponent
else if (name.equals("communication"))
this.getCommunication().add((PatientCommunicationComponent) value);
else if (name.equals("generalPractitioner"))
this.getGeneralPractitioner().add(castToReference(value));
else if (name.equals("managingOrganization"))
this.managingOrganization = castToReference(value); // Reference
else if (name.equals("link"))
this.getLink().add((PatientLinkComponent) value);
else
super.setProperty(name, value);
}
@Override
public Base makeProperty(int hash, String name) throws FHIRException {
switch (hash) {
case -1618432855: return addIdentifier(); // Identifier
case -1422950650: throw new FHIRException("Cannot make property active as it is not a complex type"); // BooleanType
case 3373707: return addName(); // HumanName
case -1429363305: return addTelecom(); // ContactPoint
case -1249512767: throw new FHIRException("Cannot make property gender as it is not a complex type"); // Enumeration<AdministrativeGender>
case -1210031859: throw new FHIRException("Cannot make property birthDate as it is not a complex type"); // DateType
case -1311442804: return getDeceased(); // Type
case -1147692044: return addAddress(); // Address
case 1756919302: return getMaritalStatus(); // CodeableConcept
case -1764672111: return getMultipleBirth(); // Type
case 106642994: return addPhoto(); // Attachment
case 951526432: return addContact(); // ContactComponent
case -1413116420: return getAnimal(); // AnimalComponent
case -1035284522: return addCommunication(); // PatientCommunicationComponent
case 1488292898: return addGeneralPractitioner(); // Reference
case -2058947787: return getManagingOrganization(); // Reference
case 3321850: return addLink(); // PatientLinkComponent
default: return super.makeProperty(hash, name);
}
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("identifier")) {
return addIdentifier();
}
else if (name.equals("active")) {
throw new FHIRException("Cannot call addChild on a primitive type Patient.active");
}
else if (name.equals("name")) {
return addName();
}
else if (name.equals("telecom")) {
return addTelecom();
}
else if (name.equals("gender")) {
throw new FHIRException("Cannot call addChild on a primitive type Patient.gender");
}
else if (name.equals("birthDate")) {
throw new FHIRException("Cannot call addChild on a primitive type Patient.birthDate");
}
else if (name.equals("deceasedBoolean")) {
this.deceased = new BooleanType();
return this.deceased;
}
else if (name.equals("deceasedDateTime")) {
this.deceased = new DateTimeType();
return this.deceased;
}
else if (name.equals("address")) {
return addAddress();
}
else if (name.equals("maritalStatus")) {
this.maritalStatus = new CodeableConcept();
return this.maritalStatus;
}
else if (name.equals("multipleBirthBoolean")) {
this.multipleBirth = new BooleanType();
return this.multipleBirth;
}
else if (name.equals("multipleBirthInteger")) {
this.multipleBirth = new IntegerType();
return this.multipleBirth;
}
else if (name.equals("photo")) {
return addPhoto();
}
else if (name.equals("contact")) {
return addContact();
}
else if (name.equals("animal")) {
this.animal = new AnimalComponent();
return this.animal;
}
else if (name.equals("communication")) {
return addCommunication();
}
else if (name.equals("generalPractitioner")) {
return addGeneralPractitioner();
}
else if (name.equals("managingOrganization")) {
this.managingOrganization = new Reference();
return this.managingOrganization;
}
else if (name.equals("link")) {
return addLink();
}
else
return super.addChild(name);
}
public String fhirType() {
return "Patient";
}
public Patient copy() {
Patient dst = new Patient();
copyValues(dst);
if (identifier != null) {
dst.identifier = new ArrayList<Identifier>();
for (Identifier i : identifier)
dst.identifier.add(i.copy());
};
dst.active = active == null ? null : active.copy();
if (name != null) {
dst.name = new ArrayList<HumanName>();
for (HumanName i : name)
dst.name.add(i.copy());
};
if (telecom != null) {
dst.telecom = new ArrayList<ContactPoint>();
for (ContactPoint i : telecom)
dst.telecom.add(i.copy());
};
dst.gender = gender == null ? null : gender.copy();
dst.birthDate = birthDate == null ? null : birthDate.copy();
dst.deceased = deceased == null ? null : deceased.copy();
if (address != null) {
dst.address = new ArrayList<Address>();
for (Address i : address)
dst.address.add(i.copy());
};
dst.maritalStatus = maritalStatus == null ? null : maritalStatus.copy();
dst.multipleBirth = multipleBirth == null ? null : multipleBirth.copy();
if (photo != null) {
dst.photo = new ArrayList<Attachment>();
for (Attachment i : photo)
dst.photo.add(i.copy());
};
if (contact != null) {
dst.contact = new ArrayList<ContactComponent>();
for (ContactComponent i : contact)
dst.contact.add(i.copy());
};
dst.animal = animal == null ? null : animal.copy();
if (communication != null) {
dst.communication = new ArrayList<PatientCommunicationComponent>();
for (PatientCommunicationComponent i : communication)
dst.communication.add(i.copy());
};
if (generalPractitioner != null) {
dst.generalPractitioner = new ArrayList<Reference>();
for (Reference i : generalPractitioner)
dst.generalPractitioner.add(i.copy());
};
dst.managingOrganization = managingOrganization == null ? null : managingOrganization.copy();
if (link != null) {
dst.link = new ArrayList<PatientLinkComponent>();
for (PatientLinkComponent i : link)
dst.link.add(i.copy());
};
return dst;
}
protected Patient typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof Patient))
return false;
Patient o = (Patient) other;
return compareDeep(identifier, o.identifier, true) && compareDeep(active, o.active, true) && compareDeep(name, o.name, true)
&& compareDeep(telecom, o.telecom, true) && compareDeep(gender, o.gender, true) && compareDeep(birthDate, o.birthDate, true)
&& compareDeep(deceased, o.deceased, true) && compareDeep(address, o.address, true) && compareDeep(maritalStatus, o.maritalStatus, true)
&& compareDeep(multipleBirth, o.multipleBirth, true) && compareDeep(photo, o.photo, true) && compareDeep(contact, o.contact, true)
&& compareDeep(animal, o.animal, true) && compareDeep(communication, o.communication, true) && compareDeep(generalPractitioner, o.generalPractitioner, true)
&& compareDeep(managingOrganization, o.managingOrganization, true) && compareDeep(link, o.link, true)
;
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof Patient))
return false;
Patient o = (Patient) other;
return compareValues(active, o.active, true) && compareValues(gender, o.gender, true) && compareValues(birthDate, o.birthDate, true)
;
}
public boolean isEmpty() {
return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(identifier, active, name
, telecom, gender, birthDate, deceased, address, maritalStatus, multipleBirth
, photo, contact, animal, communication, generalPractitioner, managingOrganization
, link);
}
@Override
public ResourceType getResourceType() {
return ResourceType.Patient;
}
/**
* Search parameter: <b>birthdate</b>
* <p>
* Description: <b>The patient's date of birth</b><br>
* Type: <b>date</b><br>
* Path: <b>Patient.birthDate</b><br>
* </p>
*/
@SearchParamDefinition(name="birthdate", path="Patient.birthDate", description="The patient's date of birth", type="date" )
public static final String SP_BIRTHDATE = "birthdate";
/**
* <b>Fluent Client</b> search parameter constant for <b>birthdate</b>
* <p>
* Description: <b>The patient's date of birth</b><br>
* Type: <b>date</b><br>
* Path: <b>Patient.birthDate</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.DateClientParam BIRTHDATE = new ca.uhn.fhir.rest.gclient.DateClientParam(SP_BIRTHDATE);
/**
* Search parameter: <b>deceased</b>
* <p>
* Description: <b>This patient has been marked as deceased, or as a death date entered</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.deceased[x]</b><br>
* </p>
*/
@SearchParamDefinition(name="deceased", path="Patient.deceased.exists()", description="This patient has been marked as deceased, or as a death date entered", type="token" )
public static final String SP_DECEASED = "deceased";
/**
* <b>Fluent Client</b> search parameter constant for <b>deceased</b>
* <p>
* Description: <b>This patient has been marked as deceased, or as a death date entered</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.deceased[x]</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam DECEASED = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_DECEASED);
/**
* Search parameter: <b>address-state</b>
* <p>
* Description: <b>A state specified in an address</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.address.state</b><br>
* </p>
*/
@SearchParamDefinition(name="address-state", path="Patient.address.state", description="A state specified in an address", type="string" )
public static final String SP_ADDRESS_STATE = "address-state";
/**
* <b>Fluent Client</b> search parameter constant for <b>address-state</b>
* <p>
* Description: <b>A state specified in an address</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.address.state</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS_STATE = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS_STATE);
/**
* Search parameter: <b>gender</b>
* <p>
* Description: <b>Gender of the patient</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.gender</b><br>
* </p>
*/
@SearchParamDefinition(name="gender", path="Patient.gender", description="Gender of the patient", type="token" )
public static final String SP_GENDER = "gender";
/**
* <b>Fluent Client</b> search parameter constant for <b>gender</b>
* <p>
* Description: <b>Gender of the patient</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.gender</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam GENDER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_GENDER);
/**
* Search parameter: <b>animal-species</b>
* <p>
* Description: <b>The species for animal patients</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.animal.species</b><br>
* </p>
*/
@SearchParamDefinition(name="animal-species", path="Patient.animal.species", description="The species for animal patients", type="token" )
public static final String SP_ANIMAL_SPECIES = "animal-species";
/**
* <b>Fluent Client</b> search parameter constant for <b>animal-species</b>
* <p>
* Description: <b>The species for animal patients</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.animal.species</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam ANIMAL_SPECIES = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_ANIMAL_SPECIES);
/**
* Search parameter: <b>link</b>
* <p>
* Description: <b>All patients linked to the given patient</b><br>
* Type: <b>reference</b><br>
* Path: <b>Patient.link.other</b><br>
* </p>
*/
@SearchParamDefinition(name="link", path="Patient.link.other", description="All patients linked to the given patient", type="reference", providesMembershipIn={ @ca.uhn.fhir.model.api.annotation.Compartment(name="Patient"), @ca.uhn.fhir.model.api.annotation.Compartment(name="RelatedPerson") }, target={Patient.class, RelatedPerson.class } )
public static final String SP_LINK = "link";
/**
* <b>Fluent Client</b> search parameter constant for <b>link</b>
* <p>
* Description: <b>All patients linked to the given patient</b><br>
* Type: <b>reference</b><br>
* Path: <b>Patient.link.other</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam LINK = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_LINK);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>Patient:link</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_LINK = new ca.uhn.fhir.model.api.Include("Patient:link").toLocked();
/**
* Search parameter: <b>language</b>
* <p>
* Description: <b>Language code (irrespective of use value)</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.communication.language</b><br>
* </p>
*/
@SearchParamDefinition(name="language", path="Patient.communication.language", description="Language code (irrespective of use value)", type="token" )
public static final String SP_LANGUAGE = "language";
/**
* <b>Fluent Client</b> search parameter constant for <b>language</b>
* <p>
* Description: <b>Language code (irrespective of use value)</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.communication.language</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam LANGUAGE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_LANGUAGE);
/**
* Search parameter: <b>animal-breed</b>
* <p>
* Description: <b>The breed for animal patients</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.animal.breed</b><br>
* </p>
*/
@SearchParamDefinition(name="animal-breed", path="Patient.animal.breed", description="The breed for animal patients", type="token" )
public static final String SP_ANIMAL_BREED = "animal-breed";
/**
* <b>Fluent Client</b> search parameter constant for <b>animal-breed</b>
* <p>
* Description: <b>The breed for animal patients</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.animal.breed</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam ANIMAL_BREED = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_ANIMAL_BREED);
/**
* Search parameter: <b>address-country</b>
* <p>
* Description: <b>A country specified in an address</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.address.country</b><br>
* </p>
*/
@SearchParamDefinition(name="address-country", path="Patient.address.country", description="A country specified in an address", type="string" )
public static final String SP_ADDRESS_COUNTRY = "address-country";
/**
* <b>Fluent Client</b> search parameter constant for <b>address-country</b>
* <p>
* Description: <b>A country specified in an address</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.address.country</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS_COUNTRY = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS_COUNTRY);
/**
* Search parameter: <b>death-date</b>
* <p>
* Description: <b>The date of death has been provided and satisfies this search value</b><br>
* Type: <b>date</b><br>
* Path: <b>Patient.deceasedDateTime</b><br>
* </p>
*/
@SearchParamDefinition(name="death-date", path="Patient.deceased.as(DateTime)", description="The date of death has been provided and satisfies this search value", type="date" )
public static final String SP_DEATH_DATE = "death-date";
/**
* <b>Fluent Client</b> search parameter constant for <b>death-date</b>
* <p>
* Description: <b>The date of death has been provided and satisfies this search value</b><br>
* Type: <b>date</b><br>
* Path: <b>Patient.deceasedDateTime</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.DateClientParam DEATH_DATE = new ca.uhn.fhir.rest.gclient.DateClientParam(SP_DEATH_DATE);
/**
* Search parameter: <b>phonetic</b>
* <p>
* Description: <b>A portion of either family or given name using some kind of phonetic matching algorithm</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.name</b><br>
* </p>
*/
@SearchParamDefinition(name="phonetic", path="Patient.name", description="A portion of either family or given name using some kind of phonetic matching algorithm", type="string" )
public static final String SP_PHONETIC = "phonetic";
/**
* <b>Fluent Client</b> search parameter constant for <b>phonetic</b>
* <p>
* Description: <b>A portion of either family or given name using some kind of phonetic matching algorithm</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.name</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.StringClientParam PHONETIC = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_PHONETIC);
/**
* Search parameter: <b>telecom</b>
* <p>
* Description: <b>The value in any kind of telecom details of the patient</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.telecom</b><br>
* </p>
*/
@SearchParamDefinition(name="telecom", path="Patient.telecom", description="The value in any kind of telecom details of the patient", type="token" )
public static final String SP_TELECOM = "telecom";
/**
* <b>Fluent Client</b> search parameter constant for <b>telecom</b>
* <p>
* Description: <b>The value in any kind of telecom details of the patient</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.telecom</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam TELECOM = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_TELECOM);
/**
* Search parameter: <b>address-city</b>
* <p>
* Description: <b>A city specified in an address</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.address.city</b><br>
* </p>
*/
@SearchParamDefinition(name="address-city", path="Patient.address.city", description="A city specified in an address", type="string" )
public static final String SP_ADDRESS_CITY = "address-city";
/**
* <b>Fluent Client</b> search parameter constant for <b>address-city</b>
* <p>
* Description: <b>A city specified in an address</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.address.city</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS_CITY = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS_CITY);
/**
* Search parameter: <b>email</b>
* <p>
* Description: <b>A value in an email contact</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.telecom(system=email)</b><br>
* </p>
*/
@SearchParamDefinition(name="email", path="Patient.telecom.where(system='email')", description="A value in an email contact", type="token" )
public static final String SP_EMAIL = "email";
/**
* <b>Fluent Client</b> search parameter constant for <b>email</b>
* <p>
* Description: <b>A value in an email contact</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.telecom(system=email)</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam EMAIL = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_EMAIL);
/**
* Search parameter: <b>identifier</b>
* <p>
* Description: <b>A patient identifier</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.identifier</b><br>
* </p>
*/
@SearchParamDefinition(name="identifier", path="Patient.identifier", description="A patient identifier", type="token" )
public static final String SP_IDENTIFIER = "identifier";
/**
* <b>Fluent Client</b> search parameter constant for <b>identifier</b>
* <p>
* Description: <b>A patient identifier</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.identifier</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam IDENTIFIER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_IDENTIFIER);
/**
* Search parameter: <b>given</b>
* <p>
* Description: <b>A portion of the given name of the patient</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.name.given</b><br>
* </p>
*/
@SearchParamDefinition(name="given", path="Patient.name.given", description="A portion of the given name of the patient", type="string" )
public static final String SP_GIVEN = "given";
/**
* <b>Fluent Client</b> search parameter constant for <b>given</b>
* <p>
* Description: <b>A portion of the given name of the patient</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.name.given</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.StringClientParam GIVEN = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_GIVEN);
/**
* Search parameter: <b>address</b>
* <p>
* Description: <b>A server defined search that may match any of the string fields in the Address, including line, city, state, country, postalCode, and/or text</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.address</b><br>
* </p>
*/
@SearchParamDefinition(name="address", path="Patient.address", description="A server defined search that may match any of the string fields in the Address, including line, city, state, country, postalCode, and/or text", type="string" )
public static final String SP_ADDRESS = "address";
/**
* <b>Fluent Client</b> search parameter constant for <b>address</b>
* <p>
* Description: <b>A server defined search that may match any of the string fields in the Address, including line, city, state, country, postalCode, and/or text</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.address</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS);
/**
* Search parameter: <b>general-practitioner</b>
* <p>
* Description: <b>Patient's nominated general practitioner, not the organization that manages the record</b><br>
* Type: <b>reference</b><br>
* Path: <b>Patient.generalPractitioner</b><br>
* </p>
*/
@SearchParamDefinition(name="general-practitioner", path="Patient.generalPractitioner", description="Patient's nominated general practitioner, not the organization that manages the record", type="reference", providesMembershipIn={ @ca.uhn.fhir.model.api.annotation.Compartment(name="Practitioner") }, target={Organization.class, Practitioner.class } )
public static final String SP_GENERAL_PRACTITIONER = "general-practitioner";
/**
* <b>Fluent Client</b> search parameter constant for <b>general-practitioner</b>
* <p>
* Description: <b>Patient's nominated general practitioner, not the organization that manages the record</b><br>
* Type: <b>reference</b><br>
* Path: <b>Patient.generalPractitioner</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam GENERAL_PRACTITIONER = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_GENERAL_PRACTITIONER);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>Patient:general-practitioner</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_GENERAL_PRACTITIONER = new ca.uhn.fhir.model.api.Include("Patient:general-practitioner").toLocked();
/**
* Search parameter: <b>active</b>
* <p>
* Description: <b>Whether the patient record is active</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.active</b><br>
* </p>
*/
@SearchParamDefinition(name="active", path="Patient.active", description="Whether the patient record is active", type="token" )
public static final String SP_ACTIVE = "active";
/**
* <b>Fluent Client</b> search parameter constant for <b>active</b>
* <p>
* Description: <b>Whether the patient record is active</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.active</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam ACTIVE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_ACTIVE);
/**
* Search parameter: <b>address-postalcode</b>
* <p>
* Description: <b>A postalCode specified in an address</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.address.postalCode</b><br>
* </p>
*/
@SearchParamDefinition(name="address-postalcode", path="Patient.address.postalCode", description="A postalCode specified in an address", type="string" )
public static final String SP_ADDRESS_POSTALCODE = "address-postalcode";
/**
* <b>Fluent Client</b> search parameter constant for <b>address-postalcode</b>
* <p>
* Description: <b>A postalCode specified in an address</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.address.postalCode</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.StringClientParam ADDRESS_POSTALCODE = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_ADDRESS_POSTALCODE);
/**
* Search parameter: <b>phone</b>
* <p>
* Description: <b>A value in a phone contact</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.telecom(system=phone)</b><br>
* </p>
*/
@SearchParamDefinition(name="phone", path="Patient.telecom.where(system='phone')", description="A value in a phone contact", type="token" )
public static final String SP_PHONE = "phone";
/**
* <b>Fluent Client</b> search parameter constant for <b>phone</b>
* <p>
* Description: <b>A value in a phone contact</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.telecom(system=phone)</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam PHONE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_PHONE);
/**
* Search parameter: <b>organization</b>
* <p>
* Description: <b>The organization at which this person is a patient</b><br>
* Type: <b>reference</b><br>
* Path: <b>Patient.managingOrganization</b><br>
* </p>
*/
@SearchParamDefinition(name="organization", path="Patient.managingOrganization", description="The organization at which this person is a patient", type="reference", target={Organization.class } )
public static final String SP_ORGANIZATION = "organization";
/**
* <b>Fluent Client</b> search parameter constant for <b>organization</b>
* <p>
* Description: <b>The organization at which this person is a patient</b><br>
* Type: <b>reference</b><br>
* Path: <b>Patient.managingOrganization</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam ORGANIZATION = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_ORGANIZATION);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>Patient:organization</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_ORGANIZATION = new ca.uhn.fhir.model.api.Include("Patient:organization").toLocked();
/**
* Search parameter: <b>name</b>
* <p>
* Description: <b>A server defined search that may match any of the string fields in the HumanName, including family, give, prefix, suffix, suffix, and/or text</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.name</b><br>
* </p>
*/
@SearchParamDefinition(name="name", path="Patient.name", description="A server defined search that may match any of the string fields in the HumanName, including family, give, prefix, suffix, suffix, and/or text", type="string" )
public static final String SP_NAME = "name";
/**
* <b>Fluent Client</b> search parameter constant for <b>name</b>
* <p>
* Description: <b>A server defined search that may match any of the string fields in the HumanName, including family, give, prefix, suffix, suffix, and/or text</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.name</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.StringClientParam NAME = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_NAME);
/**
* Search parameter: <b>address-use</b>
* <p>
* Description: <b>A use code specified in an address</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.address.use</b><br>
* </p>
*/
@SearchParamDefinition(name="address-use", path="Patient.address.use", description="A use code specified in an address", type="token" )
public static final String SP_ADDRESS_USE = "address-use";
/**
* <b>Fluent Client</b> search parameter constant for <b>address-use</b>
* <p>
* Description: <b>A use code specified in an address</b><br>
* Type: <b>token</b><br>
* Path: <b>Patient.address.use</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam ADDRESS_USE = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_ADDRESS_USE);
/**
* Search parameter: <b>family</b>
* <p>
* Description: <b>A portion of the family name of the patient</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.name.family</b><br>
* </p>
*/
@SearchParamDefinition(name="family", path="Patient.name.family", description="A portion of the family name of the patient", type="string" )
public static final String SP_FAMILY = "family";
/**
* <b>Fluent Client</b> search parameter constant for <b>family</b>
* <p>
* Description: <b>A portion of the family name of the patient</b><br>
* Type: <b>string</b><br>
* Path: <b>Patient.name.family</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.StringClientParam FAMILY = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_FAMILY);
}
| apache-2.0 |
forcedotcom/aura | aura/src/main/java/org/auraframework/builder/ClientLibraryDefBuilder.java | 1366 | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.builder;
import java.util.Set;
import org.auraframework.def.ClientLibraryDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.RootDefinition;
import org.auraframework.system.AuraContext;
/**
* Builder for {@link ClientLibraryDef}
*/
public interface ClientLibraryDefBuilder extends DefBuilder<ClientLibraryDef, ClientLibraryDef> {
ClientLibraryDefBuilder setParentDescriptor(DefDescriptor<? extends RootDefinition> parentDescriptor);
ClientLibraryDefBuilder setName(String name);
ClientLibraryDefBuilder setType(ClientLibraryDef.Type type);
ClientLibraryDefBuilder setModes(Set<AuraContext.Mode> modes);
ClientLibraryDefBuilder setShouldPrefetch(boolean shouldPrefetch);
}
| apache-2.0 |
subutai-io/Subutai | management/server/core/peer-manager/peer-manager-impl/src/main/java/io/subutai/core/peer/impl/PeerInitializationError.java | 230 | package io.subutai.core.peer.impl;
public class PeerInitializationError extends RuntimeException
{
public PeerInitializationError( final String message, final Throwable cause )
{
super( message, cause );
}
}
| apache-2.0 |
porcelli-forks/drools-wb | drools-wb-screens/drools-wb-scenario-simulation-editor/drools-wb-scenario-simulation-editor-kogito-client/src/main/java/org/drools/workbench/screens/scenariosimulation/kogito/client/dmn/KogitoDMNService.java | 1412 | /*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.workbench.screens.scenariosimulation.kogito.client.dmn;
import org.drools.workbench.screens.scenariosimulation.model.typedescriptor.FactModelTuple;
import org.jboss.errai.common.client.api.ErrorCallback;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.kie.workbench.common.dmn.webapp.kogito.marshaller.js.model.dmn12.JSITDefinitions;
import org.uberfire.backend.vfs.Path;
/**
* Interface required because <b>runtime</b> and <b>testing</b> environments would
* need/provide different implementations
*/
public interface KogitoDMNService {
void getDMNContent(final Path path, final RemoteCallback<String> remoteCallback, final ErrorCallback<Object> errorCallback);
FactModelTuple getFactModelTuple(final JSITDefinitions jsitDefinitions);
}
| apache-2.0 |
JunhwanPark/TizenRT | external/iotivity/iotivity_1.3-rel/cloud/stack/src/main/java/org/iotivity/cloud/base/protocols/coap/CoapDecoder.java | 9113 | /*
* //******************************************************************
* //
* // Copyright 2016 Samsung Electronics All Rights Reserved.
* //
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
* //
* // Licensed under the Apache License, Version 2.0 (the "License");
* // you may not use this file except in compliance with the License.
* // You may obtain a copy of the License at
* //
* // http://www.apache.org/licenses/LICENSE-2.0
* //
* // Unless required by applicable law or agreed to in writing, software
* // distributed under the License is distributed on an "AS IS" BASIS,
* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* // See the License for the specific language governing permissions and
* // limitations under the License.
* //
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
package org.iotivity.cloud.base.protocols.coap;
import java.util.List;
import org.iotivity.cloud.base.exception.ServerException;
import org.iotivity.cloud.base.protocols.MessageBuilder;
import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
import org.iotivity.cloud.util.Log;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
public class CoapDecoder extends ByteToMessageDecoder {
private enum ParsingState {
SHIM_HEADER, OPTION_PAYLOAD_LENGTH, CODE_TOKEN_OPTION, PAYLOAD, FINISH
}
private ParsingState nextState = ParsingState.SHIM_HEADER;
private int bufferToRead = 1;
private int tokenLength = 0;
private int optionPayloadLength = 0;
private CoapMessage partialMsg = null;
private int websocketLength = -1;
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in,
List<Object> out) {
try {
// TODO: need exceptional case handling
while (in.isReadable(bufferToRead)) {
switch (nextState) {
case SHIM_HEADER:
int shimHeader = in.readByte();
bufferToRead = (shimHeader >>> 4) & 0x0F;
tokenLength = (shimHeader) & 0x0F;
switch (bufferToRead) {
case 13:
bufferToRead = 1;
nextState = ParsingState.OPTION_PAYLOAD_LENGTH;
break;
case 14:
bufferToRead = 2;
nextState = ParsingState.OPTION_PAYLOAD_LENGTH;
break;
case 15:
bufferToRead = 4;
nextState = ParsingState.OPTION_PAYLOAD_LENGTH;
break;
default:
optionPayloadLength = bufferToRead;
bufferToRead += 1 + tokenLength; // code + tkl
nextState = ParsingState.CODE_TOKEN_OPTION;
break;
}
break;
case OPTION_PAYLOAD_LENGTH:
switch (bufferToRead) {
case 1:
optionPayloadLength = 13
+ (in.readByte() & 0xFF);
break;
case 2:
optionPayloadLength = 269
+ (((in.readByte() & 0xFF) << 8)
+ (in.readByte() & 0xFF));
break;
case 4:
optionPayloadLength = 65805
+ (((in.readByte() & 0xFF) << 24)
+ ((in.readByte() & 0xFF) << 16)
+ ((in.readByte() & 0xFF) << 8)
+ (in.readByte() & 0xFF));
break;
}
nextState = ParsingState.CODE_TOKEN_OPTION;
bufferToRead = 1 + tokenLength + optionPayloadLength; // code
// +
// tkl
break;
case CODE_TOKEN_OPTION:
int code = in.readByte() & 0xFF;
if (code <= 31) {
partialMsg = new CoapRequest(code);
} else if (code > 224) {
partialMsg = new CoapSignaling(code);
} else {
partialMsg = new CoapResponse(code);
}
if (tokenLength > 0) {
byte[] token = new byte[tokenLength];
in.readBytes(token);
partialMsg.setToken(token);
}
if (websocketLength != -1) {
optionPayloadLength = websocketLength
- (bufferToRead + 1); // shimheader + code +
// tokenLength
}
if (optionPayloadLength > 0) {
int optionLen = parseOptions(partialMsg, in,
optionPayloadLength);
if (optionPayloadLength > optionLen) {
nextState = ParsingState.PAYLOAD;
bufferToRead = optionPayloadLength - optionLen;
continue;
}
}
nextState = ParsingState.FINISH;
bufferToRead = 0;
break;
case PAYLOAD:
byte[] payload = new byte[bufferToRead];
in.readBytes(payload);
partialMsg.setPayload(payload);
nextState = ParsingState.FINISH;
bufferToRead = 0;
break;
case FINISH:
nextState = ParsingState.SHIM_HEADER;
bufferToRead = 1;
out.add(partialMsg);
break;
default:
break;
}
}
in.discardReadBytes();
} catch (Throwable t) {
ResponseStatus responseStatus = t instanceof ServerException
? ((ServerException) t).getErrorResponse()
: ResponseStatus.INTERNAL_SERVER_ERROR;
Log.f(ctx.channel(), t);
ctx.writeAndFlush(
MessageBuilder.createResponse(partialMsg, responseStatus));
ctx.close();
}
}
public void decode(ByteBuf in, List<Object> out, int length)
throws Exception {
websocketLength = length;
decode(null, in, out);
}
private int parseOptions(CoapMessage coapMessage, ByteBuf byteBuf,
int maxLength) {
int preOptionNum = 0;
int startPos = byteBuf.readerIndex();
int firstByte = byteBuf.readByte() & 0xFF;
while (firstByte != 0xFF && maxLength > 0) {
int optionDelta = (firstByte & 0xF0) >>> 4;
int optionLength = firstByte & 0x0F;
if (optionDelta == 13) {
optionDelta = 13 + byteBuf.readByte() & 0xFF;
} else if (optionDelta == 14) {
optionDelta = 269 + ((byteBuf.readByte() & 0xFF) << 8)
+ (byteBuf.readByte() & 0xFF);
}
if (optionLength == 13) {
optionLength = 13 + byteBuf.readByte() & 0xFF;
} else if (optionLength == 14) {
optionLength = 269 + ((byteBuf.readByte() & 0xFF) << 8)
+ (byteBuf.readByte() & 0xFF);
}
int curOptionNum = preOptionNum + optionDelta;
byte[] optionValue = new byte[optionLength];
byteBuf.readBytes(optionValue);
coapMessage.addOption(curOptionNum, optionValue);
preOptionNum = curOptionNum;
if (maxLength > byteBuf.readerIndex() - startPos) {
firstByte = byteBuf.readByte() & 0xFF;
} else {
break;
}
}
// return option length
return byteBuf.readerIndex() - startPos;
}
}
| apache-2.0 |
PlanetWaves/clockworkengine | trunk/jme3-core/src/plugins/java/com/jme3/shader/plugins/GLSLLoader.java | 8037 | /*
* Copyright (c) 2009-2012 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.shader.plugins;
import com.jme3.asset.AssetInfo;
import com.jme3.asset.AssetKey;
import com.jme3.asset.AssetLoadException;
import com.jme3.asset.AssetLoader;
import com.jme3.asset.AssetManager;
import com.jme3.asset.cache.AssetCache;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.*;
/**
* GLSL File parser that supports #import pre-processor statement
*/
public class GLSLLoader implements AssetLoader {
private AssetManager assetManager;
private Map<String, ShaderDependencyNode> dependCache = new HashMap<String, ShaderDependencyNode>();
/**
* Used to load {@link ShaderDependencyNode}s.
* Asset caching is disabled.
*/
private class ShaderDependencyKey extends AssetKey<Reader> {
public ShaderDependencyKey(String name) {
super(name);
}
@Override
public Class<? extends AssetCache> getCacheType() {
// Disallow caching here
return null;
}
}
/**
* Creates a {@link ShaderDependencyNode} from a stream representing shader code.
*
* @param in The input stream containing shader code
* @param nodeName
* @return
* @throws IOException
*/
private ShaderDependencyNode loadNode(Reader reader, String nodeName) {
ShaderDependencyNode node = new ShaderDependencyNode(nodeName);
StringBuilder sb = new StringBuilder();
StringBuilder sbExt = new StringBuilder();
BufferedReader bufReader = null;
try {
bufReader = new BufferedReader(reader);
String ln;
if (!nodeName.equals("[main]")) {
sb.append("// -- begin import ").append(nodeName).append(" --\n");
}
while ((ln = bufReader.readLine()) != null) {
if (ln.trim().startsWith("#import ")) {
ln = ln.trim().substring(8).trim();
if (ln.startsWith("\"") && ln.endsWith("\"") && ln.length() > 3) {
// import user code
// remove quotes to get filename
ln = ln.substring(1, ln.length() - 1);
if (ln.equals(nodeName)) {
throw new IOException("Node depends on itself.");
}
// check cache first
ShaderDependencyNode dependNode = dependCache.get(ln);
if (dependNode == null) {
Reader dependNodeReader = assetManager.loadAsset(new ShaderDependencyKey(ln));
dependNode = loadNode(dependNodeReader, ln);
}
node.addDependency(sb.length(), dependNode);
}
} else if (ln.trim().startsWith("#extension ")) {
sbExt.append(ln).append('\n');
} else {
sb.append(ln).append('\n');
}
}
if (!nodeName.equals("[main]")) {
sb.append("// -- end import ").append(nodeName).append(" --\n");
}
} catch (IOException ex) {
if (bufReader != null) {
try {
bufReader.close();
} catch (IOException ex1) {
}
}
throw new AssetLoadException("Failed to load shader node: " + nodeName, ex);
}
node.setSource(sb.toString());
node.setExtensions(sbExt.toString());
dependCache.put(nodeName, node);
return node;
}
private ShaderDependencyNode nextIndependentNode() throws IOException {
Collection<ShaderDependencyNode> allNodes = dependCache.values();
if (allNodes == null || allNodes.isEmpty()) {
return null;
}
for (ShaderDependencyNode node : allNodes) {
if (node.getDependOnMe().isEmpty()) {
return node;
}
}
// Circular dependency found..
for (ShaderDependencyNode node : allNodes){
System.out.println(node.getName());
}
throw new IOException("Circular dependency.");
}
private String resolveDependencies(ShaderDependencyNode node, Set<ShaderDependencyNode> alreadyInjectedSet, StringBuilder extensions) {
if (alreadyInjectedSet.contains(node)) {
return "// " + node.getName() + " was already injected at the top.\n";
} else {
alreadyInjectedSet.add(node);
}
if (!node.getExtensions().isEmpty()) {
extensions.append(node.getExtensions());
}
if (node.getDependencies().isEmpty()) {
return node.getSource();
} else {
StringBuilder sb = new StringBuilder(node.getSource());
List<String> resolvedShaderNodes = new ArrayList<String>();
for (ShaderDependencyNode dependencyNode : node.getDependencies()) {
resolvedShaderNodes.add(resolveDependencies(dependencyNode, alreadyInjectedSet, extensions));
}
List<Integer> injectIndices = node.getDependencyInjectIndices();
for (int i = resolvedShaderNodes.size() - 1; i >= 0; i--) {
// Must insert them backwards ..
sb.insert(injectIndices.get(i), resolvedShaderNodes.get(i));
}
return sb.toString();
}
}
public Object load(AssetInfo info) throws IOException {
// The input stream provided is for the vertex shader,
// to retrieve the fragment shader, use the content manager
this.assetManager = info.getManager();
Reader reader = new InputStreamReader(info.openStream());
if (info.getKey().getExtension().equals("glsllib")) {
// NOTE: Loopback, GLSLLIB is loaded by this loader
// and needs data as InputStream
return reader;
} else {
ShaderDependencyNode rootNode = loadNode(reader, "[main]");
StringBuilder extensions = new StringBuilder();
String code = resolveDependencies(rootNode, new HashSet<ShaderDependencyNode>(), extensions);
extensions.append(code);
dependCache.clear();
return extensions.toString();
}
}
}
| apache-2.0 |
tonellotto/nibiru | src/main/java/io/teknek/nibiru/partitioner/Partitioner.java | 737 | /*
* Copyright 2015 Edward Capriolo
*
* 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.teknek.nibiru.partitioner;
import io.teknek.nibiru.Token;
public interface Partitioner {
public Token partition(String in);
}
| apache-2.0 |
rogerchina/activemq-artemis | artemis-server/src/test/java/org/apache/activemq/artemis/tests/util/SimpleStringTest.java | 13390 | /*
* 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.activemq.artemis.tests.util;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
import org.junit.Assert;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.utils.DataConstants;
public class SimpleStringTest extends Assert
{
/**
* Converting back and forth between char and byte requires care as char is unsigned.
* @see SimpleString#getChars(int, int, char[], int)
* @see SimpleString#charAt(int)
* @see SimpleString#split(char)
* @see SimpleString#concat(char)
*/
@Test
public void testGetChar()
{
SimpleString p1 = new SimpleString("foo");
SimpleString p2 = new SimpleString("bar");
for (int i = 0; i < 1 << 16; i++)
{
String msg = "expecting " + i;
char c = (char)i;
SimpleString s = new SimpleString(String.valueOf(c));
// test getChars(...)
char[] c1 = new char[1];
s.getChars(0, 1, c1, 0);
assertEquals(msg, c, c1[0]);
// test charAt(int)
assertEquals(msg, c, s.charAt(0));
// test concat(char)
SimpleString s2 = s.concat(c);
assertEquals(msg, c, s2.charAt(1));
// test splitting with chars
SimpleString sSplit = new SimpleString("foo" + String.valueOf(c) + "bar");
SimpleString[] chunks = sSplit.split(c);
SimpleString[] split1 = p1.split(c);
SimpleString[] split2 = p2.split(c);
assertEquals(split1.length + split2.length, chunks.length);
int j = 0;
for (SimpleString iS : split1)
{
assertEquals(iS.toString(), iS, chunks[j++]);
}
for (SimpleString iS : split2)
{
assertEquals(iS.toString(), iS, chunks[j++]);
}
}
}
@Test
public void testString() throws Exception
{
final String str = "hello123ABC__524`16254`6125!%^$!%$!%$!%$!%!$%!$$!\uA324";
SimpleString s = new SimpleString(str);
Assert.assertEquals(str, s.toString());
Assert.assertEquals(2 * str.length(), s.getData().length);
byte[] data = s.getData();
SimpleString s2 = new SimpleString(data);
Assert.assertEquals(str, s2.toString());
}
@Test
public void testStartsWith() throws Exception
{
SimpleString s1 = new SimpleString("abcdefghi");
Assert.assertTrue(s1.startsWith(new SimpleString("abc")));
Assert.assertTrue(s1.startsWith(new SimpleString("abcdef")));
Assert.assertTrue(s1.startsWith(new SimpleString("abcdefghi")));
Assert.assertFalse(s1.startsWith(new SimpleString("abcdefghijklmn")));
Assert.assertFalse(s1.startsWith(new SimpleString("aardvark")));
Assert.assertFalse(s1.startsWith(new SimpleString("z")));
}
@Test
public void testCharSequence() throws Exception
{
String s = "abcdefghijkl";
SimpleString s1 = new SimpleString(s);
Assert.assertEquals('a', s1.charAt(0));
Assert.assertEquals('b', s1.charAt(1));
Assert.assertEquals('c', s1.charAt(2));
Assert.assertEquals('k', s1.charAt(10));
Assert.assertEquals('l', s1.charAt(11));
try
{
s1.charAt(-1);
Assert.fail("Should throw exception");
}
catch (IndexOutOfBoundsException e)
{
// OK
}
try
{
s1.charAt(-2);
Assert.fail("Should throw exception");
}
catch (IndexOutOfBoundsException e)
{
// OK
}
try
{
s1.charAt(s.length());
Assert.fail("Should throw exception");
}
catch (IndexOutOfBoundsException e)
{
// OK
}
try
{
s1.charAt(s.length() + 1);
Assert.fail("Should throw exception");
}
catch (IndexOutOfBoundsException e)
{
// OK
}
Assert.assertEquals(s.length(), s1.length());
CharSequence ss = s1.subSequence(0, s1.length());
Assert.assertEquals(ss, s1);
ss = s1.subSequence(1, 4);
Assert.assertEquals(ss, new SimpleString("bcd"));
ss = s1.subSequence(5, 10);
Assert.assertEquals(ss, new SimpleString("fghij"));
ss = s1.subSequence(5, 12);
Assert.assertEquals(ss, new SimpleString("fghijkl"));
try
{
s1.subSequence(-1, 2);
Assert.fail("Should throw exception");
}
catch (IndexOutOfBoundsException e)
{
// OK
}
try
{
s1.subSequence(-4, -2);
Assert.fail("Should throw exception");
}
catch (IndexOutOfBoundsException e)
{
// OK
}
try
{
s1.subSequence(0, s1.length() + 1);
Assert.fail("Should throw exception");
}
catch (IndexOutOfBoundsException e)
{
// OK
}
try
{
s1.subSequence(0, s1.length() + 2);
Assert.fail("Should throw exception");
}
catch (IndexOutOfBoundsException e)
{
// OK
}
try
{
s1.subSequence(5, 1);
Assert.fail("Should throw exception");
}
catch (IndexOutOfBoundsException e)
{
// OK
}
}
@Test
public void testEquals() throws Exception
{
Assert.assertFalse(new SimpleString("abcdef").equals(new Object()));
Assert.assertFalse(new SimpleString("abcef").equals(null));
Assert.assertEquals(new SimpleString("abcdef"), new SimpleString("abcdef"));
Assert.assertFalse(new SimpleString("abcdef").equals(new SimpleString("abggcdef")));
Assert.assertFalse(new SimpleString("abcdef").equals(new SimpleString("ghijkl")));
}
@Test
public void testHashcode() throws Exception
{
SimpleString str = new SimpleString("abcdef");
SimpleString sameStr = new SimpleString("abcdef");
SimpleString differentStr = new SimpleString("ghijk");
Assert.assertTrue(str.hashCode() == sameStr.hashCode());
Assert.assertFalse(str.hashCode() == differentStr.hashCode());
}
@Test
public void testUnicode() throws Exception
{
String myString = "abcdef&^*&!^ghijkl\uB5E2\uCAC7\uB2BB\uB7DD\uB7C7\uB3A3\uBCE4\uB5A5";
SimpleString s = new SimpleString(myString);
byte[] data = s.getData();
s = new SimpleString(data);
Assert.assertEquals(myString, s.toString());
}
@Test
public void testUnicodeWithSurrogates() throws Exception
{
String myString = "abcdef&^*&!^ghijkl\uD900\uDD00";
SimpleString s = new SimpleString(myString);
byte[] data = s.getData();
s = new SimpleString(data);
Assert.assertEquals(myString, s.toString());
}
@Test
public void testSizeofString() throws Exception
{
Assert.assertEquals(DataConstants.SIZE_INT, SimpleString.sizeofString(new SimpleString("")));
SimpleString str = new SimpleString(RandomUtil.randomString());
Assert.assertEquals(DataConstants.SIZE_INT + str.getData().length, SimpleString.sizeofString(str));
}
@Test
public void testSizeofNullableString() throws Exception
{
Assert.assertEquals(1, SimpleString.sizeofNullableString(null));
Assert.assertEquals(1 + DataConstants.SIZE_INT, SimpleString.sizeofNullableString(new SimpleString("")));
SimpleString str = new SimpleString(RandomUtil.randomString());
Assert.assertEquals(1 + DataConstants.SIZE_INT + str.getData().length, SimpleString.sizeofNullableString(str));
}
@Test
public void testSplitNoDelimeter() throws Exception
{
SimpleString s = new SimpleString("abcdefghi");
SimpleString[] strings = s.split('.');
Assert.assertNotNull(strings);
Assert.assertEquals(strings.length, 1);
Assert.assertEquals(strings[0], s);
}
@Test
public void testSplit1Delimeter() throws Exception
{
SimpleString s = new SimpleString("abcd.efghi");
SimpleString[] strings = s.split('.');
Assert.assertNotNull(strings);
Assert.assertEquals(strings.length, 2);
Assert.assertEquals(strings[0], new SimpleString("abcd"));
Assert.assertEquals(strings[1], new SimpleString("efghi"));
}
@Test
public void testSplitmanyDelimeters() throws Exception
{
SimpleString s = new SimpleString("abcd.efghi.jklmn.opqrs.tuvw.xyz");
SimpleString[] strings = s.split('.');
Assert.assertNotNull(strings);
Assert.assertEquals(strings.length, 6);
Assert.assertEquals(strings[0], new SimpleString("abcd"));
Assert.assertEquals(strings[1], new SimpleString("efghi"));
Assert.assertEquals(strings[2], new SimpleString("jklmn"));
Assert.assertEquals(strings[3], new SimpleString("opqrs"));
Assert.assertEquals(strings[4], new SimpleString("tuvw"));
Assert.assertEquals(strings[5], new SimpleString("xyz"));
}
@Test
public void testContains()
{
SimpleString simpleString = new SimpleString("abcdefghijklmnopqrst");
Assert.assertFalse(simpleString.contains('.'));
Assert.assertFalse(simpleString.contains('%'));
Assert.assertFalse(simpleString.contains('8'));
Assert.assertFalse(simpleString.contains('.'));
Assert.assertTrue(simpleString.contains('a'));
Assert.assertTrue(simpleString.contains('b'));
Assert.assertTrue(simpleString.contains('c'));
Assert.assertTrue(simpleString.contains('d'));
Assert.assertTrue(simpleString.contains('e'));
Assert.assertTrue(simpleString.contains('f'));
Assert.assertTrue(simpleString.contains('g'));
Assert.assertTrue(simpleString.contains('h'));
Assert.assertTrue(simpleString.contains('i'));
Assert.assertTrue(simpleString.contains('j'));
Assert.assertTrue(simpleString.contains('k'));
Assert.assertTrue(simpleString.contains('l'));
Assert.assertTrue(simpleString.contains('m'));
Assert.assertTrue(simpleString.contains('n'));
Assert.assertTrue(simpleString.contains('o'));
Assert.assertTrue(simpleString.contains('p'));
Assert.assertTrue(simpleString.contains('q'));
Assert.assertTrue(simpleString.contains('r'));
Assert.assertTrue(simpleString.contains('s'));
Assert.assertTrue(simpleString.contains('t'));
}
@Test
public void testConcat()
{
SimpleString start = new SimpleString("abcdefg");
SimpleString middle = new SimpleString("hijklmnop");
SimpleString end = new SimpleString("qrstuvwxyz");
Assert.assertEquals(start.concat(middle).concat(end), new SimpleString("abcdefghijklmnopqrstuvwxyz"));
Assert.assertEquals(start.concat('.').concat(end), new SimpleString("abcdefg.qrstuvwxyz"));
// Testing concat of SimpleString with String
for (int i = 0; i < 10; i++)
{
Assert.assertEquals(new SimpleString("abcdefg-" + i), start.concat("-" + Integer.toString(i)));
}
}
@Test
public void testMultithreadHashCode() throws Exception
{
for (int repeat = 0; repeat < 10; repeat++)
{
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < 100; i++)
{
buffer.append("Some Big String " + i);
}
String strvalue = buffer.toString();
final int initialhash = new SimpleString(strvalue).hashCode();
final SimpleString value = new SimpleString(strvalue);
int nThreads = 100;
final CountDownLatch latch = new CountDownLatch(nThreads);
final CountDownLatch start = new CountDownLatch(1);
class T extends Thread
{
boolean failed = false;
@Override
public void run()
{
try
{
latch.countDown();
start.await();
int newhash = value.hashCode();
if (newhash != initialhash)
{
failed = true;
}
}
catch (Exception e)
{
e.printStackTrace();
failed = true;
}
}
}
T[] x = new T[nThreads];
for (int i = 0; i < nThreads; i++)
{
x[i] = new T();
x[i].start();
}
ActiveMQTestBase.waitForLatch(latch);
start.countDown();
for (T t : x)
{
t.join();
}
for (T t : x)
{
Assert.assertFalse(t.failed);
}
}
}
}
| apache-2.0 |
fnyexx/mybator | src/main/java/org/mybatis/generator/internal/util/HashCodeUtil.java | 2726 | package org.mybatis.generator.internal.util;
import java.lang.reflect.Array;
/**
* This class is from javapractices.com:
*
* http://www.javapractices.com/Topic28.cjp
*
* Collected methods which allow easy implementation of <code>hashCode</code>.
*
* Example use case:
*
* <pre>
* public int hashCode() {
* int result = HashCodeUtil.SEED;
* // collect the contributions of various fields
* result = HashCodeUtil.hash(result, fPrimitive);
* result = HashCodeUtil.hash(result, fObject);
* result = HashCodeUtil.hash(result, fArray);
* return result;
* }
* </pre>
*/
public final class HashCodeUtil {
/**
* An initial value for a <code>hashCode</code>, to which is added
* contributions from fields. Using a non-zero value decreases collisons of
* <code>hashCode</code> values.
*/
public static final int SEED = 23;
/**
* booleans.
*/
public static int hash(int aSeed, boolean aBoolean) {
return firstTerm(aSeed) + (aBoolean ? 1 : 0);
}
/**
* chars.
*/
public static int hash(int aSeed, char aChar) {
return firstTerm(aSeed) + aChar;
}
/**
* ints.
*/
public static int hash(int aSeed, int aInt) {
/*
* Implementation Note Note that byte and short are handled by this
* method, through implicit conversion.
*/
return firstTerm(aSeed) + aInt;
}
/**
* longs.
*/
public static int hash(int aSeed, long aLong) {
return firstTerm(aSeed) + (int) (aLong ^ (aLong >>> 32));
}
/**
* floats.
*/
public static int hash(int aSeed, float aFloat) {
return hash(aSeed, Float.floatToIntBits(aFloat));
}
/**
* doubles.
*/
public static int hash(int aSeed, double aDouble) {
return hash(aSeed, Double.doubleToLongBits(aDouble));
}
/**
* <code>aObject</code> is a possibly-null object field, and possibly an
* array.
*
* If <code>aObject</code> is an array, then each element may be a primitive
* or a possibly-null object.
*/
public static int hash(int aSeed, Object aObject) {
int result = aSeed;
if (aObject == null) {
result = hash(result, 0);
} else if (!isArray(aObject)) {
result = hash(result, aObject.hashCode());
} else {
int length = Array.getLength(aObject);
for (int idx = 0; idx < length; ++idx) {
Object item = Array.get(aObject, idx);
// recursive call!
result = hash(result, item);
}
}
return result;
}
// / PRIVATE ///
private static final int fODD_PRIME_NUMBER = 37;
private static int firstTerm(int aSeed) {
return fODD_PRIME_NUMBER * aSeed;
}
private static boolean isArray(Object aObject) {
return aObject.getClass().isArray();
}
}
| apache-2.0 |
xingguang2013/jbpm-designer | jbpm-designer-backend/src/main/java/org/jbpm/designer/repository/RepositoryManager.java | 1682 | /*
* Copyright 2015 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jbpm.designer.repository;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class RepositoryManager {
private static RepositoryManager instance;
private Map<String, Repository> availableRepositories = new ConcurrentHashMap<String, Repository>();
private RepositoryManager() {
}
public Repository getRepository(String repositoryId) {
return this.availableRepositories.get(repositoryId);
}
public void registerRepository(String repositoryId, Repository repository) {
if (this.availableRepositories.containsKey(repositoryId)) {
return;
}
this.availableRepositories.put(repositoryId, repository);
}
public Repository unregisterRepository(String repositoryId) {
Repository repository = this.availableRepositories.get(repositoryId);
this.availableRepositories.remove(repository);
return repository;
}
public static RepositoryManager getInstance() {
if (instance == null) {
instance = new RepositoryManager();
}
return instance;
}
}
| apache-2.0 |
Grandi/lokki-android | App/src/main/java/cc/softwarefactory/lokki/android/MainApplication.java | 6855 | /*
Copyright (c) 2014-2015 F-Secure
See LICENSE for details
*/
package cc.softwarefactory.lokki.android;
import android.app.Application;
import android.graphics.Bitmap;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.support.v4.util.LruCache;
import android.util.Log;
import com.google.android.gms.maps.GoogleMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import cc.softwarefactory.lokki.android.utilities.AnalyticsUtils;
import cc.softwarefactory.lokki.android.utilities.PreferenceUtils;
public class MainApplication extends Application {
/**
* Indicates whether this is a development or production build
*/
private static final boolean DEVELOPER_MODE = true;
/**
* Debug tag identifying that a log message was caused by the main application
*/
private static final String TAG = "MainApplication";
/**
* Int array enumerating the codes used for different Google Maps map view types
*/
public static final int[] mapTypes = {GoogleMap.MAP_TYPE_NORMAL, GoogleMap.MAP_TYPE_SATELLITE, GoogleMap.MAP_TYPE_HYBRID};
/**
* Currently selected Google Maps map view type.
* TODO: make private with proper accessor methods to disallow values not in mapTypes
*/
public static int mapType = 0;
public static String emailBeingTracked;
/**
* User dashboard JSON object. Format:
* {
* "battery":"",
* "canseeme":["c429003ba3a3c508cba1460607ab7f8cd4a0d450"],
* "icansee":{
* "c429003ba3a3c508cba1460607ab7f8cd4a0d450":{
* "battery":"",
* "location":{},
* "visibility":true
* }
* },
* "idmapping":{
* "a1b2c3d4e5f6g7h8i9j10k11l12m13n14o15p16q":"test@test.com",
* "c429003ba3a3c508cba1460607ab7f8cd4a0d450":"family.member@example.com"
* },
* "location":{},
* "visibility":true
* }
*/
public static JSONObject dashboard = null;
public static String userAccount; // Email
/**
* User's contacts. Format:
* {
* "test.friend@example.com": {
* "id":1,
* "name":"Test Friend"
* },
* "family.member@example.com":{
* "id":2,
* "name":"Family Member"
* },
* "work.buddy@example.com":{
* "id":3,
* "name":"Work Buddy"
* },
* "mapping":{
* "Test Friend":"test.friend@example.com",
* "Family Member":"family.member@example.com",
* "Work Buddy":"work.buddy@example.com"
* }
* }
*/
public static JSONObject contacts;
/**
* Format:
* {
* "Test Friend":"test.friend@example.com",
* "Family Member":"family.member@example.com",
* "Work Buddy":"work.buddy@example.com"
* }
*/
public static JSONObject mapping;
/**
* Contacts that aren't shown on the map. Format:
* {
* "test.friend@example.com":1,
* "family.member@example.com":1
* }
*/
public static JSONObject iDontWantToSee;
public static Boolean visible = true;
public static LruCache<String, Bitmap> avatarCache;
/**
* The user's places. Format:
* {
* "f414af16-e532-49d2-999f-c3bdd160dca4":{
* "lat":11.17839332191203,
* "lon":1.4752149581909178E-5,
* "rad":6207030,
* "name":"1",
* "img":""
* },
* "b0d77236-cdad-4a25-8cca-47b4426d5f1f":{
* "lat":11.17839332191203,
* "lon":1.4752149581909178E-5,
* "rad":6207030,
* "name":"1",
* "img":""
* },
* "1f1a3303-5964-40d5-bd07-3744a0c0d0f7":{
* "lat":11.17839332191203,
* "lon":1.4752149581909178E-5,
* "rad":6207030,
* "name":"3",
* "img":""
* }
* }
*/
public static JSONObject places;
public static boolean locationDisabledPromptShown;
public static JSONArray buzzPlaces;
public static boolean firstTimeZoom = true;
@Override
public void onCreate() {
Log.d(TAG, "Lokki started component");
//Load user settings
loadSetting();
AnalyticsUtils.initAnalytics(getApplicationContext());
locationDisabledPromptShown = false;
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
avatarCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than number of items.
return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024;
}
};
String iDontWantToSeeString = PreferenceUtils.getString(this, PreferenceUtils.KEY_I_DONT_WANT_TO_SEE);
if (!iDontWantToSeeString.isEmpty()) {
try {
MainApplication.iDontWantToSee = new JSONObject(iDontWantToSeeString);
} catch (JSONException e) {
MainApplication.iDontWantToSee = null;
Log.e(TAG, e.getMessage());
}
} else {
MainApplication.iDontWantToSee = new JSONObject();
}
Log.d(TAG, "MainApplication.iDontWantToSee: " + MainApplication.iDontWantToSee);
if (DEVELOPER_MODE) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
buzzPlaces = new JSONArray();
super.onCreate();
}
private void loadSetting() {
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
visible = PreferenceUtils.getBoolean(getApplicationContext(), PreferenceUtils.KEY_SETTING_VISIBILITY);
Log.d(TAG, "Visible: " + visible);
// get mapValue from preferences
try {
mapType = Integer.parseInt(PreferenceUtils.getString(getApplicationContext(), PreferenceUtils.KEY_SETTING_MAP_MODE));
}
catch (NumberFormatException e){
mapType = mapTypes[0];
Log.w(TAG, "Could not parse map type; using default value: " + e);
}
}
}
| apache-2.0 |
nterry/aws-sdk-java | aws-java-sdk-redshift/src/main/java/com/amazonaws/services/redshift/model/transform/ClusterQuotaExceededExceptionUnmarshaller.java | 1589 | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.redshift.model.transform;
import org.w3c.dom.Node;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.util.XpathUtils;
import com.amazonaws.transform.StandardErrorUnmarshaller;
import com.amazonaws.services.redshift.model.ClusterQuotaExceededException;
public class ClusterQuotaExceededExceptionUnmarshaller extends
StandardErrorUnmarshaller {
public ClusterQuotaExceededExceptionUnmarshaller() {
super(ClusterQuotaExceededException.class);
}
@Override
public AmazonServiceException unmarshall(Node node) throws Exception {
// Bail out if this isn't the right error code that this
// marshaller understands
String errorCode = parseErrorCode(node);
if (errorCode == null || !errorCode.equals("ClusterQuotaExceeded"))
return null;
ClusterQuotaExceededException e = (ClusterQuotaExceededException) super
.unmarshall(node);
return e;
}
}
| apache-2.0 |
bindul/junit-helper | junit-helper-derby/src/test/java/org/deventropy/junithelper/derby/SimpleDerbyTest.java | 2114 | /*
* Copyright 2016 Development Entropy (deventropy.org) Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.deventropy.junithelper.derby;
import static org.junit.Assert.assertTrue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.AfterClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TemporaryFolder;
/**
* @author Bindul Bhowmik
*/
public class SimpleDerbyTest {
private TemporaryFolder tempFolder = new TemporaryFolder();
private EmbeddedDerbyResource embeddedDerbyResource =
new EmbeddedDerbyResource(DerbyResourceConfig.buildDefault()
.useDevNullErrorLogging(),
tempFolder);
@Rule
public RuleChain derbyRuleChain = RuleChain.outerRule(tempFolder).around(embeddedDerbyResource);
/**
* Cleanup stuff.
*/
@AfterClass
public static void cleanupDerbySystem () {
// Cleanup for next test
DerbyUtils.shutdownDerbySystemQuitely(true);
}
@Test
public void test () throws SQLException {
final String jdbcUrl = embeddedDerbyResource.getJdbcUrl();
Connection connection = null;
Statement stmt = null;
ResultSet rs = null;
try {
connection = DriverManager.getConnection(jdbcUrl);
// Check a value
stmt = connection.createStatement();
rs = stmt.executeQuery("SELECT 1 FROM SYSIBM.SYSDUMMY1");
assertTrue(rs.next());
} finally {
DerbyUtils.closeQuietly(rs);
DerbyUtils.closeQuietly(stmt);
DerbyUtils.closeQuietly(connection);
}
}
}
| apache-2.0 |
jkandasa/Sundial | src/main/java/org/quartz/plugins/management/ShutdownHookPlugin.java | 3992 | /**
* Copyright 2015 Knowm Inc. (http://knowm.org) and contributors.
* Copyright 2013-2015 Xeiam LLC (http://xeiam.com) and contributors.
* Copyright 2001-2011 Terracotta Inc. (http://terracotta.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.quartz.plugins.management;
import org.quartz.core.Scheduler;
import org.quartz.exceptions.SchedulerConfigException;
import org.quartz.exceptions.SchedulerException;
import org.quartz.plugins.SchedulerPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This plugin catches the event of the JVM terminating (such as upon a CRTL-C) and tells the scheduler to shutdown.
*
* @see org.quartz.core.Scheduler#shutdown(boolean)
* @author James House
*/
public class ShutdownHookPlugin implements SchedulerPlugin {
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Data members.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
private boolean cleanShutdown = true;
private final Logger logger = LoggerFactory.getLogger(getClass());
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Constructors.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
public ShutdownHookPlugin() {
}
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Interface.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/**
* Determine whether or not the plug-in is configured to cause a clean shutdown of the scheduler.
* <p>
* The default value is <code>true</code>.
* </p>
*
* @see org.quartz.core.Scheduler#shutdown(boolean)
*/
public boolean isCleanShutdown() {
return cleanShutdown;
}
/**
* Set whether or not the plug-in is configured to cause a clean shutdown of the scheduler.
* <p>
* The default value is <code>true</code>.
* </p>
*
* @see org.quartz.core.Scheduler#shutdown(boolean)
*/
public void setCleanShutdown(boolean b) {
cleanShutdown = b;
}
/*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SchedulerPlugin Interface.
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
/**
* <p>
* Called during creation of the <code>Scheduler</code> in order to give the <code>SchedulerPlugin</code> a chance to initialize.
* </p>
*
* @throws SchedulerConfigException if there is an error initializing.
*/
@Override
public void initialize(String name, final Scheduler scheduler) throws SchedulerException {
logger.info("Registering Quartz shutdown hook.");
Thread t = new Thread("Quartz Shutdown-Hook") {
@Override
public void run() {
logger.info("Shutting down Quartz...");
try {
scheduler.shutdown(isCleanShutdown());
} catch (SchedulerException e) {
logger.info("Error shutting down Quartz: " + e.getMessage(), e);
}
}
};
Runtime.getRuntime().addShutdownHook(t);
}
@Override
public void start() {
// do nothing.
}
/**
* <p>
* Called in order to inform the <code>SchedulerPlugin</code> that it should free up all of it's resources because the scheduler is shutting down.
* </p>
*/
@Override
public void shutdown() {
// nothing to do in this case (since the scheduler is already shutting
// down)
}
}
| apache-2.0 |
cbaenziger/oozie | core/src/main/java/org/apache/oozie/service/ELService.java | 10251 | /**
* 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.oozie.service;
import org.apache.oozie.util.XLog;
import org.apache.oozie.util.ELEvaluator;
import org.apache.oozie.ErrorCode;
import org.apache.hadoop.conf.Configuration;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* The ELService creates {@link ELEvaluator} instances preconfigured with constants and functions defined in the
* configuration. <p> The following configuration parameters control the EL service: <p> {@link #CONF_CONSTANTS} list
* of constant definitions to be available for EL evaluations. <p> {@link #CONF_FUNCTIONS} list of function definitions
* to be available for EL evalations. <p> Definitions must be separated by a comma, definitions are trimmed. <p> The
* syntax for a constant definition is <code>PREFIX:NAME=CLASS_NAME#CONSTANT_NAME</code>. <p> The syntax for a constant
* definition is <code>PREFIX:NAME=CLASS_NAME#METHOD_NAME</code>.
*/
public class ELService implements Service {
public static final String CONF_PREFIX = Service.CONF_PREFIX + "ELService.";
public static final String CONF_CONSTANTS = CONF_PREFIX + "constants.";
public static final String CONF_EXT_CONSTANTS = CONF_PREFIX + "ext.constants.";
public static final String CONF_FUNCTIONS = CONF_PREFIX + "functions.";
public static final String CONF_EXT_FUNCTIONS = CONF_PREFIX + "ext.functions.";
public static final String CONF_GROUPS = CONF_PREFIX + "groups";
private final XLog log = XLog.getLog(getClass());
//<Group Name>, <List of constants>
private HashMap<String, List<ELConstant>> constants;
//<Group Name>, <List of functions>
private HashMap<String, List<ELFunction>> functions;
private static class ELConstant {
private String name;
private Object value;
private ELConstant(String prefix, String name, Object value) {
if (prefix.length() > 0) {
name = prefix + ":" + name;
}
this.name = name;
this.value = value;
}
}
private static class ELFunction {
private String prefix;
private String name;
private Method method;
private ELFunction(String prefix, String name, Method method) {
this.prefix = prefix;
this.name = name;
this.method = method;
}
}
private List<ELService.ELConstant> extractConstants(Configuration conf, String key) throws ServiceException {
List<ELService.ELConstant> list = new ArrayList<ELService.ELConstant>();
if (conf.get(key, "").trim().length() > 0) {
for (String function : ConfigurationService.getStrings(conf, key)) {
String[] parts = parseDefinition(function);
list.add(new ELConstant(parts[0], parts[1], findConstant(parts[2], parts[3])));
log.trace("Registered prefix:constant[{0}:{1}] for class#field[{2}#{3}]", (Object[]) parts);
}
}
return list;
}
private List<ELService.ELFunction> extractFunctions(Configuration conf, String key) throws ServiceException {
List<ELService.ELFunction> list = new ArrayList<ELService.ELFunction>();
if (conf.get(key, "").trim().length() > 0) {
for (String function : ConfigurationService.getStrings(conf, key)) {
String[] parts = parseDefinition(function);
list.add(new ELFunction(parts[0], parts[1], findMethod(parts[2], parts[3])));
log.trace("Registered prefix:constant[{0}:{1}] for class#field[{2}#{3}]", (Object[]) parts);
}
}
return list;
}
/**
* Initialize the EL service.
*
* @param services services instance.
* @throws ServiceException thrown if the EL service could not be initialized.
*/
@Override
public synchronized void init(Services services) throws ServiceException {
log.trace("Constants and functions registration");
constants = new HashMap<String, List<ELConstant>>();
functions = new HashMap<String, List<ELFunction>>();
//Get the list of group names from configuration file
// defined in the property tag: oozie.service.ELSerice.groups
//String []groupList = services.getConf().get(CONF_GROUPS, "").trim().split(",");
String[] groupList = ConfigurationService.getStrings(services.getConf(), CONF_GROUPS);
//For each group, collect the required functions and constants
// and store it into HashMap
for (String group : groupList) {
List<ELConstant> tmpConstants = new ArrayList<ELConstant>();
tmpConstants.addAll(extractConstants(services.getConf(), CONF_CONSTANTS + group));
tmpConstants.addAll(extractConstants(services.getConf(), CONF_EXT_CONSTANTS + group));
constants.put(group, tmpConstants);
List<ELFunction> tmpFunctions = new ArrayList<ELFunction>();
tmpFunctions.addAll(extractFunctions(services.getConf(), CONF_FUNCTIONS + group));
tmpFunctions.addAll(extractFunctions(services.getConf(), CONF_EXT_FUNCTIONS + group));
functions.put(group, tmpFunctions);
}
}
/**
* Destroy the EL service.
*/
@Override
public void destroy() {
constants = null;
functions = null;
}
/**
* Return the public interface for EL service.
*
* @return {@link ELService}.
*/
@Override
public Class<? extends Service> getInterface() {
return ELService.class;
}
/**
* Return an {@link ELEvaluator} pre-configured with the constants and functions for the specific group of
* EL-functions and variables defined in the configuration. If the group name doesn't exist,
* IllegalArgumentException is thrown
* @param group: Name of the group of required EL Evaluator.
* @return ELEvaluator a preconfigured {@link ELEvaluator}.
*/
public ELEvaluator createEvaluator(String group) {
ELEvaluator.Context context = new ELEvaluator.Context();
boolean groupDefined = false;
if (constants.containsKey(group)) {
for (ELConstant constant : constants.get(group)) {
context.setVariable(constant.name, constant.value);
}
groupDefined = true;
}
if (functions.containsKey(group)) {
for (ELFunction function : functions.get(group)) {
context.addFunction(function.prefix, function.name, function.method);
}
groupDefined = true;
}
if (groupDefined == false) {
throw new IllegalArgumentException("Group " + group + " is not defined");
}
return new ELEvaluator(context);
}
private static String[] parseDefinition(String str) throws ServiceException {
try {
str = str.trim();
if (!str.contains(":")) {
str = ":" + str;
}
String[] parts = str.split(":");
String prefix = parts[0];
parts = parts[1].split("=");
String name = parts[0];
parts = parts[1].split("#");
String klass = parts[0];
String method = parts[1];
return new String[]{prefix, name, klass, method};
}
catch (Exception ex) {
throw new ServiceException(ErrorCode.E0110, str, ex.getMessage(), ex);
}
}
public static Method findMethod(String className, String methodName) throws ServiceException {
Method method = null;
try {
Class klass = Thread.currentThread().getContextClassLoader().loadClass(className);
for (Method m : klass.getMethods()) {
if (m.getName().equals(methodName)) {
method = m;
break;
}
}
if (method == null) {
throw new ServiceException(ErrorCode.E0111, className, methodName);
}
if ((method.getModifiers() & (Modifier.PUBLIC | Modifier.STATIC)) != (Modifier.PUBLIC | Modifier.STATIC)) {
throw new ServiceException(ErrorCode.E0112, className, methodName);
}
}
catch (ClassNotFoundException ex) {
throw new ServiceException(ErrorCode.E0113, className);
}
return method;
}
public static Object findConstant(String className, String constantName) throws ServiceException {
try {
Class klass = Thread.currentThread().getContextClassLoader().loadClass(className);
Field field = klass.getField(constantName);
if ((field.getModifiers() & (Modifier.PUBLIC | Modifier.STATIC)) != (Modifier.PUBLIC | Modifier.STATIC)) {
throw new ServiceException(ErrorCode.E0114, className, constantName);
}
return field.get(null);
}
catch (IllegalAccessException ex) {
throw new IllegalArgumentException(ex);
}
catch (NoSuchFieldException ex) {
throw new ServiceException(ErrorCode.E0115, className, constantName);
}
catch (ClassNotFoundException ex) {
throw new ServiceException(ErrorCode.E0113, className);
}
}
}
| apache-2.0 |
Fabryprog/camel | core/camel-core/src/test/java/org/apache/camel/issues/NotifyBuilderExactlyDoneSplitterWhereSentToIssueTest.java | 1932 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.issues;
import java.util.concurrent.TimeUnit;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Test;
public class NotifyBuilderExactlyDoneSplitterWhereSentToIssueTest extends ContextTestSupport {
@Test
public void testReceiveTiAnalyticsArrayOfJsonEvents() {
NotifyBuilder notifier = new NotifyBuilder(context)
.wereSentTo("stub:direct:somewhere")
.whenExactlyDone(7)
.create();
template.sendBody("direct:split", "A,B,C,D,E,F,G");
assertTrue(notifier.matches(10, TimeUnit.SECONDS));
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:split")
.split(body()).parallelProcessing()
.log("Received: ${body}")
.to("stub:direct:somewhere");
}
};
}
}
| apache-2.0 |
apache/olingo-odata2 | odata2-lib/odata-client-core/src/main/java/org/apache/olingo/odata2/client/core/ep/deserializer/JsonFeedDeserializer.java | 8653 | /*******************************************************************************
* 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.olingo.odata2.client.core.ep.deserializer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.olingo.odata2.api.edm.EdmException;
import org.apache.olingo.odata2.api.ep.EntityProviderException;
import org.apache.olingo.odata2.api.ep.entry.DeletedEntryMetadata;
import org.apache.olingo.odata2.api.ep.entry.ODataEntry;
import org.apache.olingo.odata2.api.ep.feed.ODataDeltaFeed;
import org.apache.olingo.odata2.api.ep.feed.ODataFeed;
import org.apache.olingo.odata2.client.api.ep.DeserializerProperties;
import org.apache.olingo.odata2.core.ep.aggregator.EntityInfoAggregator;
import org.apache.olingo.odata2.core.ep.feed.FeedMetadataImpl;
import org.apache.olingo.odata2.core.ep.feed.JsonFeedEntry;
import org.apache.olingo.odata2.core.ep.feed.ODataDeltaFeedImpl;
import org.apache.olingo.odata2.core.ep.util.FormatJson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
/**
* This class Deserializes JsonFeed payloads
*/
public class JsonFeedDeserializer {
private JsonReader reader;
private EntityInfoAggregator eia;
private DeserializerProperties readProperties;
private List<DeletedEntryMetadata> deletedEntries = new ArrayList<DeletedEntryMetadata>();
private List<ODataEntry> entries = new ArrayList<ODataEntry>();
private FeedMetadataImpl feedMetadata = new FeedMetadataImpl();
private boolean resultsArrayPresent = false;
private static final String JSONFEED = "JsonFeed";
/**
*
* @param reader
* @param eia
* @param readProperties
*/
public JsonFeedDeserializer(final JsonReader reader, final EntityInfoAggregator eia,
final DeserializerProperties readProperties) {
this.reader = reader;
this.eia = eia;
this.readProperties = readProperties;
}
/**
*
* @return ODataDeltaFeed
* @throws EntityProviderException
*/
public ODataDeltaFeed readFeedStandalone() throws EntityProviderException {
try {
readFeed();
if (reader.peek() != JsonToken.END_DOCUMENT) {
throw new EntityProviderException(EntityProviderException.END_DOCUMENT_EXPECTED.addContent(reader.peek()
.toString()));
}
} catch (IOException e) {
throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass()
.getSimpleName()), e);
} catch (EdmException e) {
throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass()
.getSimpleName()), e);
} catch (IllegalStateException e) {
throw new EntityProviderException(EntityProviderException.EXCEPTION_OCCURRED.addContent(e.getClass()
.getSimpleName()), e);
}
return new ODataDeltaFeedImpl(entries, feedMetadata, deletedEntries);
}
/**
*
* @throws IOException
* @throws EdmException
* @throws EntityProviderException
*/
private void readFeed() throws IOException, EdmException, EntityProviderException {
JsonToken peek = reader.peek();
if (peek == JsonToken.BEGIN_ARRAY) {
readArrayContent();
} else {
reader.beginObject();
final String nextName = reader.nextName();
if (FormatJson.D.equals(nextName)) {
if (reader.peek() == JsonToken.BEGIN_ARRAY) {
readArrayContent();
} else {
reader.beginObject();
readFeedContent();
reader.endObject();
}
} else {
handleName(nextName);
readFeedContent();
}
reader.endObject();
}
}
/**
*
* @throws IOException
* @throws EdmException
* @throws EntityProviderException
*/
private void readFeedContent() throws IOException, EdmException, EntityProviderException {
while (reader.hasNext()) {
final String nextName = reader.nextName();
handleName(nextName);
}
if (!resultsArrayPresent) {
throw new EntityProviderException(EntityProviderException.MISSING_RESULTS_ARRAY);
}
}
/**
*
* @param nextName
* @throws IOException
* @throws EdmException
* @throws EntityProviderException
*/
private void handleName(final String nextName) throws IOException, EdmException, EntityProviderException {
if (FormatJson.RESULTS.equals(nextName)) {
resultsArrayPresent = true;
readArrayContent();
} else if (FormatJson.COUNT.equals(nextName)) {
readInlineCount(reader, feedMetadata);
} else if (FormatJson.NEXT.equals(nextName)) {
if (reader.peek() == JsonToken.STRING && feedMetadata.getNextLink() == null) {
String nextLink = reader.nextString();
feedMetadata.setNextLink(nextLink);
} else {
throw new EntityProviderException(EntityProviderException.INVALID_CONTENT.addContent(nextName).addContent(
JSONFEED));
}
} else if (FormatJson.DELTA.equals(nextName)) {
if (reader.peek() == JsonToken.STRING && feedMetadata.getDeltaLink() == null) {
String deltaLink = reader.nextString();
feedMetadata.setDeltaLink(deltaLink);
} else {
throw new EntityProviderException(EntityProviderException.INVALID_CONTENT.addContent(nextName).addContent(
JSONFEED));
}
} else {
throw new EntityProviderException(EntityProviderException.INVALID_CONTENT.addContent(nextName).addContent(
JSONFEED));
}
}
/**
*
* @throws IOException
* @throws EdmException
* @throws EntityProviderException
*/
private void readArrayContent() throws IOException, EdmException, EntityProviderException {
reader.beginArray();
while (reader.hasNext()) {
final JsonFeedEntry entry = new JsonEntryDeserializer(reader, eia, readProperties).readFeedEntry();
if (entry.isODataEntry()) {
entries.add(entry.getODataEntry());
} else {
deletedEntries.add(entry.getDeletedEntryMetadata());
}
}
reader.endArray();
}
/**
*
* @param reader
* @param feedMetadata
* @throws IOException
* @throws EntityProviderException
*/
protected static void readInlineCount(final JsonReader reader, final FeedMetadataImpl feedMetadata)
throws IOException, EntityProviderException {
if (reader.peek() == JsonToken.STRING && feedMetadata.getInlineCount() == null) {
int inlineCount;
try {
inlineCount = reader.nextInt();
} catch (final NumberFormatException e) {
throw new EntityProviderException(EntityProviderException.INLINECOUNT_INVALID.addContent(""), e);
}
if (inlineCount >= 0) {
feedMetadata.setInlineCount(inlineCount);
} else {
throw new EntityProviderException(EntityProviderException.INLINECOUNT_INVALID.addContent(inlineCount));
}
} else {
throw new EntityProviderException(EntityProviderException.INLINECOUNT_INVALID.addContent(reader.peek()));
}
}
/**
*
* @param name
* @return ODataFeed
* @throws EdmException
* @throws EntityProviderException
* @throws IOException
*/
protected ODataFeed readStartedInlineFeed(final String name) throws EdmException, EntityProviderException,
IOException {
// consume the already started content
handleName(name);
// consume the rest of the entry content
readFeedContent();
return new ODataDeltaFeedImpl(entries, feedMetadata);
}
/**
*
* @return ODataFeed
* @throws EdmException
* @throws EntityProviderException
* @throws IOException
*/
protected ODataFeed readInlineFeedStandalone() throws EdmException, EntityProviderException, IOException {
readFeed();
return new ODataDeltaFeedImpl(entries, feedMetadata);
}
}
| apache-2.0 |
janezhango/BigDataMachineLearning | src/main/java/water/api/ExportS3.java | 1889 | package water.api;
import water.*;
import water.H2O.H2OCountedCompleter;
import water.persist.PersistS3Task;
import water.persist.PersistS3;
import water.util.Log;
import com.google.gson.JsonObject;
public class ExportS3 extends Request {
protected class BucketArg extends TypeaheadInputText<String> {
public BucketArg(String name) {
super(TypeaheadS3BucketRequest.class, name, true);
}
@Override
protected String parse(String input) throws IllegalArgumentException {
PersistS3.getClient();
return input;
}
@Override
protected String queryDescription() {
return "S3 Bucket";
}
@Override
protected String defaultValue() {
return null;
}
}
protected final H2OExistingKey _source = new H2OExistingKey(SOURCE_KEY);
protected final BucketArg _bucket = new BucketArg(BUCKET);
protected final Str _object = new Str(OBJECT, "");
public ExportS3() {
_requestHelp = "Exports a key to Amazon S3. All nodes in the "
+ "cloud must have permission to access the Amazon object.";
_bucket._requestHelp = "Target Amazon S3 Bucket.";
}
@Override
protected Response serve() {
final Value value = _source.value();
final String bucket = _bucket.value();
final String object = _object.value();
try {
final Key dest = PersistS3Task.init(value);
H2O.submitTask(new H2OCountedCompleter() {
@Override public void compute2() {
PersistS3Task.run(dest, value, bucket, object);
}
});
JsonObject response = new JsonObject();
response.addProperty(RequestStatics.DEST_KEY, dest.toString());
Response r = ExportS3Progress.redirect(response, dest);
r.setBuilder(RequestStatics.DEST_KEY, new KeyElementBuilder());
return r;
} catch( Throwable e ) {
return Response.error(e);
}
}
}
| apache-2.0 |
apache/jena | jena-tdb/src/test/java/org/apache/jena/tdb/base/file/TestBlockAccessMapped.java | 1566 | /*
* 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.jena.tdb.base.file;
import org.apache.jena.atlas.lib.FileOps ;
import org.apache.jena.tdb.ConfigTest ;
import org.junit.AfterClass ;
public class TestBlockAccessMapped extends AbstractTestBlockAccessFixedSize
{
static String filename = ConfigTest.getTestingDir()+"/test-file-access-mapped" ;
static final int BlockSize = 64 ;
public TestBlockAccessMapped()
{
super(BlockSize) ;
}
@AfterClass public static void cleanup() { FileOps.deleteSilent(filename) ; }
static int counter = 0 ;
@Override
protected BlockAccess make()
{
String fn = filename + "-"+(counter++) ;
FileOps.deleteSilent(fn) ;
return new BlockAccessMapped(fn, BlockSize) ;
}
}
| apache-2.0 |
jmartisk/hibernate-validator | engine/src/test/java/org/hibernate/validator/test/internal/constraintvalidators/FutureValidatorForDateTest.java | 1901 | /*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hibernate.validator.test.internal.constraintvalidators;
import java.util.Date;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.hibernate.validator.internal.constraintvalidators.FutureValidatorForDate;
public class FutureValidatorForDateTest {
private static FutureValidatorForDate constraint;
@BeforeClass
public static void init() {
constraint = new FutureValidatorForDate();
}
@Test
public void testIsValid() {
Date futureDate = getFutureDate();
Date pastDate = getPastDate();
assertTrue( constraint.isValid( null, null ) );
assertTrue( constraint.isValid( futureDate, null ) );
assertFalse( constraint.isValid( pastDate, null ) );
}
private Date getFutureDate() {
Date date = new Date();
long timeStamp = date.getTime();
date.setTime( timeStamp + 31557600000L );
return date;
}
private Date getPastDate() {
Date date = new Date();
long timeStamp = date.getTime();
date.setTime( timeStamp - 31557600000L );
return date;
}
}
| apache-2.0 |
apache/solr | solr/core/src/test/org/apache/solr/cloud/DistribJoinFromCollectionTest.java | 9690 | /*
* 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.solr.cloud;
import static org.hamcrest.CoreMatchers.not;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.BaseHttpSolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.QueryRequest;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.ZkStateReader;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Tests using fromIndex that points to a collection in SolrCloud mode. */
public class DistribJoinFromCollectionTest extends SolrCloudTestCase {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private static final String[] scoreModes = {"avg", "max", "min", "total"};
// resetExceptionIgnores();
private static String toColl = "to_2x2";
private static String fromColl = "from_1x4";
private static String toDocId;
@BeforeClass
public static void setupCluster() throws Exception {
final Path configDir = TEST_COLL1_CONF();
String configName = "solrCloudCollectionConfig";
int nodeCount = 5;
configureCluster(nodeCount).addConfig(configName, configDir).configure();
Map<String, String> collectionProperties = new HashMap<>();
collectionProperties.put("config", "solrconfig-tlog.xml");
collectionProperties.put("schema", "schema.xml");
// create a collection holding data for the "to" side of the JOIN
int shards = 2;
int replicas = 2;
CollectionAdminRequest.createCollection(toColl, configName, shards, replicas)
.setProperties(collectionProperties)
.process(cluster.getSolrClient());
// get the set of nodes where replicas for the "to" collection exist
Set<String> nodeSet = new HashSet<>();
ZkStateReader zkStateReader = cluster.getSolrClient().getZkStateReader();
ClusterState cs = zkStateReader.getClusterState();
for (Slice slice : cs.getCollection(toColl).getActiveSlices())
for (Replica replica : slice.getReplicas()) nodeSet.add(replica.getNodeName());
assertTrue(nodeSet.size() > 0);
// deploy the "from" collection to all nodes where the "to" collection exists
CollectionAdminRequest.createCollection(fromColl, configName, 1, 4)
.setCreateNodeSet(String.join(",", nodeSet))
.setProperties(collectionProperties)
.process(cluster.getSolrClient());
toDocId = indexDoc(toColl, 1001, "a", null, "b");
indexDoc(fromColl, 2001, "a", "c", null);
Thread.sleep(1000); // so the commits fire
}
@Test
public void testScore() throws Exception {
// without score
testJoins(toColl, fromColl, toDocId, true);
}
@Test
public void testNoScore() throws Exception {
// with score
testJoins(toColl, fromColl, toDocId, false);
}
@AfterClass
public static void shutdown() {
log.info(
"DistribJoinFromCollectionTest logic complete ... deleting the {} and {} collections",
toColl,
fromColl);
// try to clean up
for (String c : new String[] {toColl, fromColl}) {
try {
CollectionAdminRequest.Delete req = CollectionAdminRequest.deleteCollection(c);
req.process(cluster.getSolrClient());
} catch (Exception e) {
// don't fail the test
log.warn("Could not delete collection {} after test completed due to:", c, e);
}
}
log.info("DistribJoinFromCollectionTest succeeded ... shutting down now!");
}
private void testJoins(String toColl, String fromColl, String toDocId, boolean isScoresTest)
throws SolrServerException, IOException, InterruptedException {
// verify the join with fromIndex works
final String fromQ = "match_s:c^2";
CloudSolrClient client = cluster.getSolrClient();
{
final String joinQ =
"{!join "
+ anyScoreMode(isScoresTest)
+ "from=join_s fromIndex="
+ fromColl
+ " to=join_s}"
+ fromQ;
QueryRequest qr =
new QueryRequest(params("collection", toColl, "q", joinQ, "fl", "id,get_s,score"));
QueryResponse rsp = new QueryResponse(client.request(qr), client);
SolrDocumentList hits = rsp.getResults();
assertTrue("Expected 1 doc, got " + hits, hits.getNumFound() == 1);
SolrDocument doc = hits.get(0);
assertEquals(toDocId, doc.getFirstValue("id"));
assertEquals("b", doc.getFirstValue("get_s"));
assertScore(isScoresTest, doc);
}
// negative test before creating an alias
checkAbsentFromIndex(fromColl, toColl, isScoresTest);
// create an alias for the fromIndex and then query through the alias
String alias = fromColl + "Alias";
CollectionAdminRequest.createAlias(alias, fromColl).process(client);
{
final String joinQ =
"{!join "
+ anyScoreMode(isScoresTest)
+ "from=join_s fromIndex="
+ alias
+ " to=join_s}"
+ fromQ;
final QueryRequest qr =
new QueryRequest(params("collection", toColl, "q", joinQ, "fl", "id,get_s,score"));
final QueryResponse rsp = new QueryResponse(client.request(qr), client);
final SolrDocumentList hits = rsp.getResults();
assertTrue("Expected 1 doc", hits.getNumFound() == 1);
SolrDocument doc = hits.get(0);
assertEquals(toDocId, doc.getFirstValue("id"));
assertEquals("b", doc.getFirstValue("get_s"));
assertScore(isScoresTest, doc);
}
// negative test after creating an alias
checkAbsentFromIndex(fromColl, toColl, isScoresTest);
{
// verify join doesn't work if no match in the "from" index
final String joinQ =
"{!join "
+ (anyScoreMode(isScoresTest))
+ "from=join_s fromIndex="
+ fromColl
+ " to=join_s}match_s:d";
final QueryRequest qr =
new QueryRequest(params("collection", toColl, "q", joinQ, "fl", "id,get_s,score"));
final QueryResponse rsp = new QueryResponse(client.request(qr), client);
final SolrDocumentList hits = rsp.getResults();
assertTrue("Expected no hits", hits.getNumFound() == 0);
}
}
private void assertScore(boolean isScoresTest, SolrDocument doc) {
if (isScoresTest) {
assertThat(
"score join doesn't return 1.0", doc.getFirstValue("score").toString(), not("1.0"));
} else {
assertEquals("Solr join has constant score", "1.0", doc.getFirstValue("score").toString());
}
}
private String anyScoreMode(boolean isScoresTest) {
return isScoresTest ? "score=" + (scoreModes[random().nextInt(scoreModes.length)]) + " " : "";
}
private void checkAbsentFromIndex(String fromColl, String toColl, boolean isScoresTest)
throws SolrServerException, IOException {
final String wrongName = fromColl + "WrongName";
final String joinQ =
"{!join "
+ (anyScoreMode(isScoresTest))
+ "from=join_s fromIndex="
+ wrongName
+ " to=join_s}match_s:c";
final QueryRequest qr =
new QueryRequest(params("collection", toColl, "q", joinQ, "fl", "id,get_s,score"));
BaseHttpSolrClient.RemoteSolrException ex =
assertThrows(
BaseHttpSolrClient.RemoteSolrException.class,
() -> cluster.getSolrClient().request(qr));
assertEquals(SolrException.ErrorCode.BAD_REQUEST.code, ex.code());
assertTrue(ex.getMessage().contains(wrongName));
}
protected static String indexDoc(
String collection, int id, String joinField, String matchField, String getField)
throws Exception {
UpdateRequest up = new UpdateRequest();
up.setCommitWithin(50);
up.setParam("collection", collection);
SolrInputDocument doc = new SolrInputDocument();
String docId = "" + id;
doc.addField("id", docId);
doc.addField("join_s", joinField);
if (matchField != null) doc.addField("match_s", matchField);
if (getField != null) doc.addField("get_s", getField);
up.add(doc);
cluster.getSolrClient().request(up);
return docId;
}
}
| apache-2.0 |
morimekta/thrift-j2 | providence-testing/src/test/java/net/morimekta/providence/testing/EqualToMessageTest.java | 5573 | package net.morimekta.providence.testing;
import net.morimekta.test.providence.testing.calculator.Operand;
import net.morimekta.test.providence.testing.calculator.Operation;
import net.morimekta.test.providence.testing.calculator.Operator;
import net.morimekta.test.providence.testing.number.Imaginary;
import org.hamcrest.Description;
import org.hamcrest.StringDescription;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* @author Stein Eldar Johnsen
* @since 21.01.16.
*/
public class EqualToMessageTest {
private EqualToMessage matcher;
private Operation expected;
private Operation matches;
private Operation not_matches;
@Before
public void setUp() {
expected = Operation.builder()
.setOperator(Operator.MULTIPLY)
.addToOperands(Operand.builder()
.setOperation(Operation.builder()
.setOperator(Operator.ADD)
.addToOperands(Operand.withNumber(1234))
.addToOperands(Operand.withNumber(
4.321))
.build())
.build())
.addToOperands(Operand.withImaginary(Imaginary.builder()
.setV(1.7)
.setI(-2.0)
.build()))
.build();
// Same constructor again to make sure all objects are not the same, but equal.
matches = Operation.builder()
.setOperator(Operator.MULTIPLY)
.addToOperands(Operand.builder()
.setOperation(Operation.builder()
.setOperator(Operator.ADD)
.addToOperands(Operand.withNumber(1234))
.addToOperands(Operand.withNumber(4.321))
.build())
.build())
.addToOperands(Operand.withImaginary(Imaginary.builder()
.setV(1.7)
.setI(-2.0)
.build()))
.build();
not_matches = Operation.builder()
.setOperator(Operator.MULTIPLY)
.addToOperands(Operand.builder()
.setOperation(Operation.builder()
.setOperator(Operator.ADD)
.addToOperands(Operand.withNumber(1234))
.addToOperands(Operand.withNumber(4.321))
.build())
.build())
.addToOperands(Operand.withImaginary(Imaginary.builder()
.setV(1.8)
.setI(-2.0)
.build()))
.build();
matcher = new EqualToMessage<>(expected);
}
@Test
public void testMatches() {
assertTrue(matcher.matches(expected));
assertTrue(matcher.matches(matches));
assertFalse(matcher.matches(not_matches));
}
@Test
public void testDescribeTo() {
Description description = new StringDescription();
matcher.describeTo(description);
assertThat(description.toString(), is(equalTo(
"equals({operator:MULTIPLY,operands:[{operation:{operator:ADD,operands:[{number:1234},{number:4.321}]}},{imaginary:{v:...})")));
}
@Test
public void testDescribeMismatch() {
Description description = new StringDescription();
matcher.describeMismatch(not_matches, description);
assertThat(description.toString(), is(equalTo(
"operands[1].imaginary.v was 1.8, expected 1.7")));
}
}
| apache-2.0 |
Gaduo/hapi-fhir | hapi-fhir-structures-dstu3/src/main/java/org/hl7/fhir/dstu3/model/codesystems/PaymentStatus.java | 3286 | package org.hl7.fhir.dstu3.model.codesystems;
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Tue, Dec 6, 2016 09:42-0500 for FHIR v1.8.0
import org.hl7.fhir.exceptions.FHIRException;
public enum PaymentStatus {
/**
* The payment has been sent physically or electronically.
*/
PAID,
/**
* The payment has been received by the payee.
*/
CLEARED,
/**
* added to help the parsers
*/
NULL;
public static PaymentStatus fromCode(String codeString) throws FHIRException {
if (codeString == null || "".equals(codeString))
return null;
if ("paid".equals(codeString))
return PAID;
if ("cleared".equals(codeString))
return CLEARED;
throw new FHIRException("Unknown PaymentStatus code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case PAID: return "paid";
case CLEARED: return "cleared";
default: return "?";
}
}
public String getSystem() {
return "http://hl7.org/fhir/paymentstatus";
}
public String getDefinition() {
switch (this) {
case PAID: return "The payment has been sent physically or electronically.";
case CLEARED: return "The payment has been received by the payee.";
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case PAID: return "Paid";
case CLEARED: return "Cleared";
default: return "?";
}
}
}
| apache-2.0 |
JFixby/RedTriplane | red-triplane-physics-red/src/com/jfixby/r3/physics/BodyDynamicsImpl.java | 1305 |
package com.jfixby.r3.physics;
import com.jfixby.r3.api.physics.Body;
import com.jfixby.r3.api.physics.BodyDynamicsListener;
import com.jfixby.r3.api.physics.BodyMass;
import com.jfixby.r3.api.physics.BodyPosition;
import com.jfixby.r3.api.physics.ForcesApplicator;
import com.jfixby.r3.physics.body.BodyImpl;
public class BodyDynamicsImpl implements ForcesApplicator {
final private BodyImpl master;
public BodyDynamicsImpl (final BodyImpl body) {
this.master = body;
}
public void applyForcesIfNeeded () {
if (this.dynamics_listener != null) {
this.dynamics_listener.onApplyForcesCallBack(this);
}
}
private BodyDynamicsListener dynamics_listener;
public void setDynamicsListener (final BodyDynamicsListener dynamics_listener) {
this.dynamics_listener = dynamics_listener;
}
@Override
public BodyPosition getBodyPosition () {
return this.master.warpingData();
}
@Override
public BodyMass getBodyMassValues () {
return this.master.mass();
}
@Override
public void applyForce (final double force_x, final double force_y) {
this.master.body_avatar.applyForce(force_x, force_y);
}
@Override
public boolean isBody (final Body body) {
return this.master == body;
}
public BodyDynamicsListener getDynamicsListener () {
return this.dynamics_listener;
}
}
| apache-2.0 |
botelhojp/apache-jmeter-2.10 | src/core/org/apache/jmeter/gui/JMeterGUIComponent.java | 6888 | /*
* 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.jmeter.gui;
import java.util.Collection;
import javax.swing.JPopupMenu;
import org.apache.jmeter.testelement.TestElement;
/**
* Implementing this interface indicates that the class is a JMeter GUI
* Component. A JMeter GUI Component is essentially the GUI display code
* associated with a JMeter Test Element. The writer of the component must take
* care to make the component be consistent with the rest of JMeter's GUI look
* and feel and behavior. Use of the provided abstract classes is highly
* recommended to make this task easier.
*
* @see AbstractJMeterGuiComponent
* @see org.apache.jmeter.config.gui.AbstractConfigGui
* @see org.apache.jmeter.assertions.gui.AbstractAssertionGui
* @see org.apache.jmeter.control.gui.AbstractControllerGui
* @see org.apache.jmeter.timers.gui.AbstractTimerGui
* @see org.apache.jmeter.visualizers.gui.AbstractVisualizer
* @see org.apache.jmeter.samplers.gui.AbstractSamplerGui
*
*/
public interface JMeterGUIComponent extends ClearGui {
/**
* Sets the name of the JMeter GUI Component. The name of the component is
* used in the Test Tree as the name of the tree node.
*
* @param name
* the name of the component
*/
void setName(String name);
/**
* Gets the name of the JMeter GUI component. The name of the component is
* used in the Test Tree as the name of the tree node.
*
* @return the name of the component
*/
String getName();
/**
* Get the component's label. This label is used in drop down lists that
* give the user the option of choosing one type of component in a list of
* many. It should therefore be a descriptive name for the end user to see.
* It must be unique to the class.
*
* It is also used by Help to find the appropriate location in the
* documentation.
*
* Normally getLabelResource() should be overridden instead of
* this method; the definition of this method in AbstractJMeterGuiComponent
* is intended for general use.
*
* @see #getLabelResource()
* @return GUI label for the component.
*/
String getStaticLabel();
/**
* Get the component's resource name, which getStaticLabel uses to derive
* the component's label in the local language. The resource name is fixed,
* and does not vary with the selected language.
*
* Normally this method should be overriden in preference to overriding
* getStaticLabel(). However where the resource name is not available or required,
* getStaticLabel() may be overridden instead.
*
* @return the resource name
*/
String getLabelResource();
/**
* Get the component's document anchor name. Used by Help to find the
* appropriate location in the documentation
*
* @return Document anchor (#ref) for the component.
*/
String getDocAnchor();
/**
* JMeter test components are separated into a model and a GUI
* representation. The model holds the data and the GUI displays it. The GUI
* class is responsible for knowing how to create and initialize with data
* the model class that it knows how to display, and this method is called
* when new test elements are created.
*
* @return the Test Element object that the GUI component represents.
*/
TestElement createTestElement();
/**
* GUI components are responsible for populating TestElements they create
* with the data currently held in the GUI components. This method should
* overwrite whatever data is currently in the TestElement as it is called
* after a user has filled out the form elements in the gui with new
* information.
*
* @param element
* the TestElement to modify
*/
void modifyTestElement(TestElement element);
/**
* Test GUI elements can be disabled, in which case they do not become part
* of the test when run.
*
* @return true if the element should be part of the test run, false
* otherwise
*/
boolean isEnabled();
/**
* Set whether this component is enabled.
*
* @param enabled
* true for enabled, false for disabled.
*/
void setEnabled(boolean enabled);
/**
* When a user right-clicks on the component in the test tree, or selects
* the edit menu when the component is selected, the component will be asked
* to return a JPopupMenu that provides all the options available to the
* user from this component.
*
* @return a JPopupMenu appropriate for the component.
*/
JPopupMenu createPopupMenu();
/**
* The GUI must be able to extract the data from the TestElement and update
* all GUI fields to represent those data. This method is called to allow
* JMeter to show the user the GUI that represents the test element's data.
*
* @param element
* the TestElement to configure
*/
void configure(TestElement element);
/**
* This is the list of add menu categories this gui component will be
* available under. For instance, if this represents a Controller, then the
* MenuFactory.CONTROLLERS category should be in the returned collection.
* When a user right-clicks on a tree element and looks through the "add"
* menu, which category your GUI component shows up in is determined by
* which categories are returned by this method. Most GUI's belong to only
* one category, but it is possible for a component to exist in multiple
* categories.
*
* @return a Collection of Strings, where each element is one of the
* constants defined in MenuFactory
*
* @see org.apache.jmeter.gui.util.MenuFactory
*/
Collection<String> getMenuCategories();
}
| apache-2.0 |
massakam/pulsar | pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authentication/utils/AuthTokenUtils.java | 4890 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.broker.authentication.utils;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.DecodingException;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.Key;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
import java.util.Optional;
import javax.crypto.SecretKey;
import lombok.experimental.UtilityClass;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.pulsar.client.api.url.URL;
@UtilityClass
public class AuthTokenUtils {
public static SecretKey createSecretKey(SignatureAlgorithm signatureAlgorithm) {
return Keys.secretKeyFor(signatureAlgorithm);
}
public static SecretKey decodeSecretKey(byte[] secretKey) {
return Keys.hmacShaKeyFor(secretKey);
}
public static PrivateKey decodePrivateKey(byte[] key, SignatureAlgorithm algType) throws IOException {
try {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(key);
KeyFactory kf = KeyFactory.getInstance(keyTypeForSignatureAlgorithm(algType));
return kf.generatePrivate(spec);
} catch (Exception e) {
throw new IOException("Failed to decode private key", e);
}
}
public static PublicKey decodePublicKey(byte[] key, SignatureAlgorithm algType) throws IOException {
try {
X509EncodedKeySpec spec = new X509EncodedKeySpec(key);
KeyFactory kf = KeyFactory.getInstance(keyTypeForSignatureAlgorithm(algType));
return kf.generatePublic(spec);
} catch (Exception e) {
throw new IOException("Failed to decode public key", e);
}
}
private static String keyTypeForSignatureAlgorithm(SignatureAlgorithm alg) {
if (alg.getFamilyName().equals("RSA")) {
return "RSA";
} else if (alg.getFamilyName().equals("ECDSA")) {
return "EC";
} else {
String msg = "The " + alg.name() + " algorithm does not support Key Pairs.";
throw new IllegalArgumentException(msg);
}
}
public static String encodeKeyBase64(Key key) {
return Encoders.BASE64.encode(key.getEncoded());
}
public static String createToken(Key signingKey, String subject, Optional<Date> expiryTime) {
JwtBuilder builder = Jwts.builder()
.setSubject(subject)
.signWith(signingKey);
expiryTime.ifPresent(builder::setExpiration);
return builder.compact();
}
public static byte[] readKeyFromUrl(String keyConfUrl) throws IOException {
if (keyConfUrl.startsWith("data:") || keyConfUrl.startsWith("file:")) {
try {
return IOUtils.toByteArray(URL.createURL(keyConfUrl));
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e);
}
} else if (Files.exists(Paths.get(keyConfUrl))) {
// Assume the key content was passed in a valid file path
return Files.readAllBytes(Paths.get(keyConfUrl));
} else if (Base64.isBase64(keyConfUrl.getBytes())) {
// Assume the key content was passed in base64
try {
return Decoders.BASE64.decode(keyConfUrl);
} catch (DecodingException e) {
String msg = "Illegal base64 character or Key file " + keyConfUrl + " doesn't exist";
throw new IOException(msg, e);
}
} else {
String msg = "Secret/Public Key file " + keyConfUrl + " doesn't exist";
throw new IllegalArgumentException(msg);
}
}
}
| apache-2.0 |
jtulach/teavm | tests/src/test/java/org/teavm/dependency/DependencyTest.java | 10483 | /*
* Copyright 2017 Alexey Andreev.
*
* 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.teavm.dependency;
import com.carrotsearch.hppc.IntOpenHashSet;
import com.carrotsearch.hppc.IntSet;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.teavm.backend.javascript.JavaScriptTarget;
import org.teavm.common.DisjointSet;
import org.teavm.diagnostics.Problem;
import org.teavm.model.BasicBlock;
import org.teavm.model.ClassHolderSource;
import org.teavm.model.Instruction;
import org.teavm.model.MethodHolder;
import org.teavm.model.MethodReference;
import org.teavm.model.Program;
import org.teavm.model.TextLocation;
import org.teavm.model.ValueType;
import org.teavm.model.analysis.ClassInference;
import org.teavm.model.instructions.AbstractInstructionVisitor;
import org.teavm.model.instructions.AssignInstruction;
import org.teavm.model.instructions.ClassConstantInstruction;
import org.teavm.model.instructions.InvokeInstruction;
import org.teavm.model.instructions.PutElementInstruction;
import org.teavm.model.instructions.UnwrapArrayInstruction;
import org.teavm.parsing.ClasspathClassHolderSource;
import org.teavm.vm.TeaVM;
import org.teavm.vm.TeaVMBuilder;
import org.teavm.vm.TeaVMPhase;
import org.teavm.vm.TeaVMProgressFeedback;
import org.teavm.vm.TeaVMProgressListener;
public class DependencyTest {
@Rule
public final TestName testName = new TestName();
private static ClassHolderSource classSource;
@BeforeClass
public static void prepare() {
classSource = new ClasspathClassHolderSource(DependencyTest.class.getClassLoader());
}
@AfterClass
public static void cleanup() {
classSource = null;
}
@Test
public void virtualCall() {
doTest();
}
@Test
public void instanceOf() {
doTest();
}
@Test
public void catchException() {
doTest();
}
@Test
public void propagateException() {
doTest();
}
@Test
public void arrays() {
doTest();
}
@Test
public void arraysPassed() {
doTest();
}
@Test
public void arraysRetrieved() {
doTest();
}
private void doTest() {
TeaVM vm = new TeaVMBuilder(new JavaScriptTarget())
.setClassLoader(DependencyTest.class.getClassLoader())
.setClassSource(classSource)
.build();
vm.setProgressListener(new TeaVMProgressListener() {
@Override
public TeaVMProgressFeedback phaseStarted(TeaVMPhase phase, int count) {
return phase == TeaVMPhase.DEPENDENCY_CHECKING
? TeaVMProgressFeedback.CONTINUE
: TeaVMProgressFeedback.CANCEL;
}
@Override
public TeaVMProgressFeedback progressReached(int progress) {
return TeaVMProgressFeedback.CONTINUE;
}
});
vm.installPlugins();
MethodReference testMethod = new MethodReference(DependencyTestData.class,
testName.getMethodName(), void.class);
vm.entryPoint(testMethod).withValue(0, DependencyTestData.class.getName());
vm.build(fileName -> new ByteArrayOutputStream(), "out");
List<Problem> problems = vm.getProblemProvider().getSevereProblems();
if (!problems.isEmpty()) {
Problem problem = problems.get(0);
Assert.fail("Error at " + problem.getLocation().getSourceLocation() + ": " + problem.getText());
}
MethodHolder method = classSource.get(testMethod.getClassName()).getMethod(testMethod.getDescriptor());
List<Assertion> assertions = collectAssertions(method);
processAssertions(assertions, vm.getDependencyInfo().getMethod(testMethod), vm.getDependencyInfo(),
method.getProgram());
}
private void processAssertions(List<Assertion> assertions, MethodDependencyInfo methodDep,
DependencyInfo dependencyInfo, Program program) {
ClassInference classInference = new ClassInference(dependencyInfo);
classInference.infer(program, methodDep.getReference());
for (Assertion assertion : assertions) {
ValueDependencyInfo valueDep = methodDep.getVariable(assertion.value);
String[] actualTypes = valueDep.getTypes();
String[] expectedTypes = assertion.expectedTypes.clone();
Arrays.sort(actualTypes);
Arrays.sort(expectedTypes);
Assert.assertArrayEquals("Assertion at " + assertion.location, expectedTypes, actualTypes);
actualTypes = classInference.classesOf(assertion.value);
Arrays.sort(actualTypes);
Assert.assertArrayEquals("Assertion at " + assertion.location + " (class inference)",
expectedTypes, actualTypes);
}
}
private List<Assertion> collectAssertions(MethodHolder method) {
Program program = method.getProgram();
AliasCollector aliasCollector = new AliasCollector(program.variableCount());
for (BasicBlock block : program.getBasicBlocks()) {
for (Instruction instruction : block) {
instruction.acceptVisitor(aliasCollector);
}
}
int[] aliases = aliasCollector.disjointSet.pack(program.variableCount());
AssertionCollector assertionCollector = new AssertionCollector(aliases);
for (BasicBlock block : program.getBasicBlocks()) {
for (Instruction instruction : block) {
instruction.acceptVisitor(assertionCollector);
}
}
assertionCollector.postProcess();
return assertionCollector.assertions;
}
static class AliasCollector extends AbstractInstructionVisitor {
DisjointSet disjointSet = new DisjointSet();
AliasCollector(int variableCount) {
for (int i = 0; i < variableCount; ++i) {
disjointSet.create();
}
}
@Override
public void visit(AssignInstruction insn) {
disjointSet.union(insn.getReceiver().getIndex(), insn.getAssignee().getIndex());
}
@Override
public void visit(UnwrapArrayInstruction insn) {
disjointSet.union(insn.getReceiver().getIndex(), insn.getArray().getIndex());
}
}
static class AssertionCollector extends AbstractInstructionVisitor {
static final MethodReference assertionMethod = new MethodReference(MetaAssertions.class,
"assertTypes", Object.class, Class[].class, void.class);
int[] aliases;
List<Assertion> assertions = new ArrayList<>();
IntSet[] arrayContent;
ValueType[] classConstants;
AssertionCollector(int[] aliases) {
this.aliases = aliases;
classConstants = new ValueType[aliases.length];
arrayContent = new IntSet[aliases.length];
}
void postProcess() {
int[] aliasInstances = new int[aliases.length];
Arrays.fill(aliasInstances, -1);
for (int i = 0; i < aliases.length; ++i) {
int alias = aliases[i];
if (aliasInstances[alias] < 0) {
aliasInstances[alias] = i;
}
}
for (Assertion assertion : assertions) {
IntSet items = arrayContent[assertion.array];
if (items != null) {
Set<String> expectedClasses = new HashSet<>();
for (int item : items.toArray()) {
ValueType constant = classConstants[item];
if (constant != null) {
String expectedClass;
if (constant instanceof ValueType.Object) {
expectedClass = ((ValueType.Object) constant).getClassName();
} else {
expectedClass = constant.toString();
}
expectedClasses.add(expectedClass);
}
}
assertion.expectedTypes = expectedClasses.toArray(new String[0]);
} else {
assertion.expectedTypes = new String[0];
}
assertion.value = aliasInstances[assertion.value];
}
}
@Override
public void visit(InvokeInstruction insn) {
if (insn.getMethod().equals(assertionMethod)) {
Assertion assertion = new Assertion();
assertion.value = aliases[insn.getArguments().get(0).getIndex()];
assertion.array = aliases[insn.getArguments().get(1).getIndex()];
assertion.location = insn.getLocation();
assertions.add(assertion);
}
}
@Override
public void visit(ClassConstantInstruction insn) {
classConstants[aliases[insn.getReceiver().getIndex()]] = insn.getConstant();
}
@Override
public void visit(PutElementInstruction insn) {
int array = aliases[insn.getArray().getIndex()];
int value = aliases[insn.getValue().getIndex()];
IntSet items = arrayContent[array];
if (items == null) {
items = new IntOpenHashSet();
arrayContent[array] = items;
}
items.add(value);
}
}
private static class Assertion {
int value;
int array;
TextLocation location;
String[] expectedTypes;
}
}
| apache-2.0 |
CloudSlang/cs-actions | cs-amazon/src/main/java/io/cloudslang/content/amazon/factory/LoadBalancingQueryParamsMapBuilder.java | 2183 | /*
* (c) Copyright 2019 EntIT Software LLC, a Micro Focus company, L.P.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available 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.cloudslang.content.amazon.factory;
import io.cloudslang.content.amazon.entities.inputs.InputsWrapper;
import io.cloudslang.content.amazon.factory.helpers.LoadBalancingUtils;
import java.util.Map;
import static io.cloudslang.content.amazon.entities.constants.Constants.LoadBalancingQueryApiActions.CREATE_LOAD_BALANCER;
import static io.cloudslang.content.amazon.entities.constants.Constants.LoadBalancingQueryApiActions.DELETE_LOAD_BALANCER;
import static io.cloudslang.content.amazon.entities.constants.Constants.LoadBalancingQueryApiActions.DESCRIBE_LOAD_BALANCERS;
import static io.cloudslang.content.amazon.entities.constants.Constants.ErrorMessages.UNSUPPORTED_QUERY_API;
/**
* Created by TusaM
* 11/10/2016.
*/
class LoadBalancingQueryParamsMapBuilder {
private LoadBalancingQueryParamsMapBuilder() {
// prevent instantiation
}
static Map<String, String> getLoadBalancingQueryParamsMap(InputsWrapper wrapper) {
switch (wrapper.getCommonInputs().getAction()) {
case CREATE_LOAD_BALANCER:
return new LoadBalancingUtils().getCreateLoadBalancerQueryParamsMap(wrapper);
case DELETE_LOAD_BALANCER:
return new LoadBalancingUtils().getDeleteLoadBalancerQueryParamsMap(wrapper);
case DESCRIBE_LOAD_BALANCERS:
return new LoadBalancingUtils().getDescribeLoadBalancersQueryParamsMap(wrapper);
default:
throw new RuntimeException(UNSUPPORTED_QUERY_API);
}
}
}
| apache-2.0 |
SciGaP/SEAGrid-Desktop-GUI | src/main/java/nanocad/dipole.java | 2104 | /***************************************
*dipole.java
*Andrew Knox 6/27/01
*
*This class was written as a way to hold information about dipoles
*for estaticterm.java. I'm not sure how usefull it would be as an
*actual model of a dipole.
*/
package nanocad;
public class dipole
{
private atom firstAtom, secondAtom;
private double chargeConst;
private double distribution;
private boolean valid;
public dipole(atom first, atom second, double charge, double dist)
{
if (first.isBondedWith(second) == true)
{
firstAtom = first;
secondAtom = second;
chargeConst = charge;
distribution = dist;
valid = true;
}
else
valid = false;
if (charge == 0.0 || dist == 0.0)
valid = false;
}
public dipole(atom first, atom second)
{
if (first.isBondedWith(second) == true)
{
firstAtom = first;
secondAtom = second;
}
chargeConst = 0.0;
distribution = 0.0;
valid = false;
}
public dipole()
{
valid = false;
}
public boolean isValid()
{
return valid;
}
public void setConst(double charge, double dist)
{
chargeConst = charge;
distribution = dist;
valid = true;
}
public double getChargeConst()
{
return chargeConst;
}
public double getDistribution()
{
return distribution;
}
public boolean isSameDipole(atom a, atom b)
{
if ((a == firstAtom && b == secondAtom) || (a == secondAtom && b == firstAtom))
return true;
else
return false;
}
public boolean isSameDipole(dipole d)
{
if ((firstAtom == d.firstAtom && secondAtom == d.secondAtom) ||
(firstAtom == d.secondAtom && secondAtom == d.firstAtom))
return true;
else
return false;
}
public boolean sharesAtomWith(dipole d)
{
if (firstAtom == d.firstAtom || firstAtom == d.secondAtom
|| secondAtom == d.firstAtom || secondAtom == d.secondAtom)
return true;
else
return false;
}
public atom getFirst()
{
return firstAtom;
}
public atom getSecond()
{
return secondAtom;
}
}
| apache-2.0 |
finmath/finmath-lib | src/main/java8/net/finmath/montecarlo/interestrate/products/indices/DateIndex.java | 2386 | /*
* (c) Copyright Christian P. Fries, Germany. Contact: email@christian-fries.de.
*
* Created on 14.06.2015
*/
package net.finmath.montecarlo.interestrate.products.indices;
import java.time.LocalDate;
import java.util.Set;
import net.finmath.exception.CalculationException;
import net.finmath.montecarlo.interestrate.TermStructureMonteCarloSimulationModel;
import net.finmath.stochastic.RandomVariable;
/**
* An index whose value is a function of the fixing date, for example the DAY, MONTH or NUMBER_OF_DAYS_IN_MONTH.
* This index is useful in building date based interpolation formulas using other indices.
*
* @author Christian Fries
* @version 1.0
*/
public class DateIndex extends AbstractIndex {
private static final long serialVersionUID = 7457336500162149869L;
public enum DateIndexType {
DAY,
MONTH,
YEAR,
NUMBER_OF_DAYS_IN_MONTH
}
private final DateIndexType dateIndexType;
/**
* Construct a date index.
*
* @param name Name of this index.
* @param currency Currency (if any - in natural situations this index is a scalar).
* @param dateIndexType The date index type.
*/
public DateIndex(final String name, final String currency, final DateIndexType dateIndexType) {
super(name, currency);
this.dateIndexType = dateIndexType;
}
/**
* Construct a date index.
*
* @param name Name of this index.
* @param dateIndexType The date index type.
*/
public DateIndex(final String name, final DateIndexType dateIndexType) {
super(name);
this.dateIndexType = dateIndexType;
}
@Override
public RandomVariable getValue(final double fixingTime, final TermStructureMonteCarloSimulationModel model) throws CalculationException {
final LocalDate referenceDate = model.getModel().getForwardRateCurve().getReferenceDate()
.plusDays((int)Math.round(fixingTime*365));
double value = 0;
switch(dateIndexType) {
case DAY:
value = referenceDate.getDayOfMonth();
break;
case MONTH:
value = referenceDate.getMonthValue();
break;
case YEAR:
value = referenceDate.getYear();
break;
case NUMBER_OF_DAYS_IN_MONTH:
value = referenceDate.lengthOfMonth();
break;
default:
throw new IllegalArgumentException("Unknown dateIndexType " + dateIndexType + ".");
}
return model.getRandomVariableForConstant(value);
}
@Override
public Set<String> queryUnderlyings() {
return null;
}
}
| apache-2.0 |
vimond/dropwizard | dropwizard-migrations/src/main/java/io/dropwizard/migrations/DbDumpCommand.java | 7326 | package io.dropwizard.migrations;
import com.google.common.base.Charsets;
import io.dropwizard.Configuration;
import io.dropwizard.db.DatabaseConfiguration;
import liquibase.Liquibase;
import liquibase.diff.DiffGeneratorFactory;
import liquibase.diff.DiffResult;
import liquibase.diff.compare.CompareControl;
import liquibase.diff.output.DiffOutputControl;
import liquibase.diff.output.changelog.DiffToChangeLog;
import liquibase.structure.DatabaseObject;
import liquibase.structure.core.*;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.ArgumentGroup;
import net.sourceforge.argparse4j.inf.Namespace;
import net.sourceforge.argparse4j.inf.Subparser;
import java.io.PrintStream;
import java.util.HashSet;
import java.util.Set;
public class DbDumpCommand<T extends Configuration> extends AbstractLiquibaseCommand<T> {
public DbDumpCommand(DatabaseConfiguration<T> strategy, Class<T> configurationClass) {
super("dump",
"Generate a dump of the existing database state.",
strategy,
configurationClass);
}
@Override
public void configure(Subparser subparser) {
super.configure(subparser);
subparser.addArgument("-o", "--output")
.dest("output")
.help("Write output to <file> instead of stdout");
final ArgumentGroup tables = subparser.addArgumentGroup("Tables");
tables.addArgument("--tables")
.action(Arguments.storeTrue())
.dest("tables")
.help("Check for added or removed tables (default)");
tables.addArgument("--ignore-tables")
.action(Arguments.storeFalse())
.dest("tables")
.help("Ignore tables");
final ArgumentGroup columns = subparser.addArgumentGroup("Columns");
columns.addArgument("--columns")
.action(Arguments.storeTrue())
.dest("columns")
.help("Check for added, removed, or modified tables (default)");
columns.addArgument("--ignore-columns")
.action(Arguments.storeFalse())
.dest("columns")
.help("Ignore columns");
final ArgumentGroup views = subparser.addArgumentGroup("Views");
views.addArgument("--views")
.action(Arguments.storeTrue())
.dest("views")
.help("Check for added, removed, or modified views (default)");
views.addArgument("--ignore-views")
.action(Arguments.storeFalse())
.dest("views")
.help("Ignore views");
final ArgumentGroup primaryKeys = subparser.addArgumentGroup("Primary Keys");
primaryKeys.addArgument("--primary-keys")
.action(Arguments.storeTrue())
.dest("primary-keys")
.help("Check for changed primary keys (default)");
primaryKeys.addArgument("--ignore-primary-keys")
.action(Arguments.storeFalse())
.dest("primary-keys")
.help("Ignore primary keys");
final ArgumentGroup uniqueConstraints = subparser.addArgumentGroup("Unique Constraints");
uniqueConstraints.addArgument("--unique-constraints")
.action(Arguments.storeTrue())
.dest("unique-constraints")
.help("Check for changed unique constraints (default)");
uniqueConstraints.addArgument("--ignore-unique-constraints")
.action(Arguments.storeFalse())
.dest("unique-constraints")
.help("Ignore unique constraints");
final ArgumentGroup indexes = subparser.addArgumentGroup("Indexes");
indexes.addArgument("--indexes")
.action(Arguments.storeTrue())
.dest("indexes")
.help("Check for changed indexes (default)");
indexes.addArgument("--ignore-indexes")
.action(Arguments.storeFalse())
.dest("indexes")
.help("Ignore indexes");
final ArgumentGroup foreignKeys = subparser.addArgumentGroup("Foreign Keys");
foreignKeys.addArgument("--foreign-keys")
.action(Arguments.storeTrue())
.dest("foreign-keys")
.help("Check for changed foreign keys (default)");
foreignKeys.addArgument("--ignore-foreign-keys")
.action(Arguments.storeFalse())
.dest("foreign-keys")
.help("Ignore foreign keys");
final ArgumentGroup sequences = subparser.addArgumentGroup("Sequences");
sequences.addArgument("--sequences")
.action(Arguments.storeTrue())
.dest("sequences")
.help("Check for changed sequences (default)");
sequences.addArgument("--ignore-sequences")
.action(Arguments.storeFalse())
.dest("sequences")
.help("Ignore foreign keys");
final ArgumentGroup data = subparser.addArgumentGroup("Data");
data.addArgument("--data")
.action(Arguments.storeTrue())
.dest("data")
.help("Check for changed data")
.setDefault(Boolean.FALSE);
data.addArgument("--ignore-data")
.action(Arguments.storeFalse())
.dest("data")
.help("Ignore data (default)")
.setDefault(Boolean.FALSE);
}
@Override
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public void run(Namespace namespace, Liquibase liquibase) throws Exception {
final Set<Class<? extends DatabaseObject>> compareTypes = new HashSet<>();
if (namespace.getBoolean("columns")) {
compareTypes.add(Column.class);
}
if (namespace.getBoolean("data")) {
compareTypes.add(Data.class);
}
if (namespace.getBoolean("foreign-keys")) {
compareTypes.add(ForeignKey.class);
}
if (namespace.getBoolean("indexes")) {
compareTypes.add(Index.class);
}
if (namespace.getBoolean("primary-keys")) {
compareTypes.add(PrimaryKey.class);
}
if (namespace.getBoolean("sequences")) {
compareTypes.add(Sequence.class);
}
if (namespace.getBoolean("tables")) {
compareTypes.add(Table.class);
}
if (namespace.getBoolean("unique-constraints")) {
compareTypes.add(UniqueConstraint.class);
}
if (namespace.getBoolean("views")) {
compareTypes.add(View.class);
}
final DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(
liquibase.getDatabase(), null, new CompareControl(compareTypes));
final DiffToChangeLog diffToChangeLog = new DiffToChangeLog(diffResult, new DiffOutputControl());
final String filename = namespace.getString("output");
if (filename != null) {
try (PrintStream file = new PrintStream(filename, Charsets.UTF_8.name())) {
diffToChangeLog.print(file);
}
} else {
diffToChangeLog.print(System.out);
}
}
}
| apache-2.0 |
alien4cloud/alien4cloud | alien4cloud-tosca/src/main/java/org/alien4cloud/tosca/exceptions/ConstraintTechnicalException.java | 524 | package org.alien4cloud.tosca.exceptions;
import alien4cloud.exception.TechnicalException;
/**
* Base class for all constraint related exceptions
*
* @author mkv
*
*/
public class ConstraintTechnicalException extends TechnicalException {
private static final long serialVersionUID = 5829360730980521567L;
public ConstraintTechnicalException(String message, Throwable cause) {
super(message, cause);
}
public ConstraintTechnicalException(String message) {
super(message);
}
}
| apache-2.0 |
zhangminglei/flink | flink-core/src/main/java/org/apache/flink/configuration/SecurityOptions.java | 11882 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.configuration;
import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.annotation.docs.ConfigGroup;
import org.apache.flink.annotation.docs.ConfigGroups;
import org.apache.flink.annotation.docs.Documentation;
import org.apache.flink.configuration.description.Description;
import static org.apache.flink.configuration.ConfigOptions.key;
import static org.apache.flink.configuration.description.LinkElement.link;
/**
* The set of configuration options relating to security.
*/
@PublicEvolving
@ConfigGroups(groups = {
@ConfigGroup(name = "Kerberos", keyPrefix = "security.kerberos"),
@ConfigGroup(name = "ZooKeeper", keyPrefix = "zookeeper")
})
public class SecurityOptions {
// ------------------------------------------------------------------------
// Kerberos Options
// ------------------------------------------------------------------------
public static final ConfigOption<String> KERBEROS_LOGIN_PRINCIPAL =
key("security.kerberos.login.principal")
.noDefaultValue()
.withDeprecatedKeys("security.principal")
.withDescription("Kerberos principal name associated with the keytab.");
public static final ConfigOption<String> KERBEROS_LOGIN_KEYTAB =
key("security.kerberos.login.keytab")
.noDefaultValue()
.withDeprecatedKeys("security.keytab")
.withDescription("Absolute path to a Kerberos keytab file that contains the user credentials.");
public static final ConfigOption<Boolean> KERBEROS_LOGIN_USETICKETCACHE =
key("security.kerberos.login.use-ticket-cache")
.defaultValue(true)
.withDescription("Indicates whether to read from your Kerberos ticket cache.");
public static final ConfigOption<String> KERBEROS_LOGIN_CONTEXTS =
key("security.kerberos.login.contexts")
.noDefaultValue()
.withDescription("A comma-separated list of login contexts to provide the Kerberos credentials to" +
" (for example, `Client,KafkaClient` to use the credentials for ZooKeeper authentication and for" +
" Kafka authentication)");
// ------------------------------------------------------------------------
// ZooKeeper Security Options
// ------------------------------------------------------------------------
public static final ConfigOption<Boolean> ZOOKEEPER_SASL_DISABLE =
key("zookeeper.sasl.disable")
.defaultValue(false);
public static final ConfigOption<String> ZOOKEEPER_SASL_SERVICE_NAME =
key("zookeeper.sasl.service-name")
.defaultValue("zookeeper");
public static final ConfigOption<String> ZOOKEEPER_SASL_LOGIN_CONTEXT_NAME =
key("zookeeper.sasl.login-context-name")
.defaultValue("Client");
// ------------------------------------------------------------------------
// SSL Security Options
// ------------------------------------------------------------------------
/**
* Enable SSL for internal (rpc, data transport, blob server) and external (HTTP/REST) communication.
*
* @deprecated Use {@link #SSL_INTERNAL_ENABLED} and {@link #SSL_REST_ENABLED} instead.
*/
@Deprecated
public static final ConfigOption<Boolean> SSL_ENABLED =
key("security.ssl.enabled")
.defaultValue(false)
.withDescription("Turns on SSL for internal and external network communication." +
"This can be overridden by 'security.ssl.internal.enabled', 'security.ssl.external.enabled'. " +
"Specific internal components (rpc, data transport, blob server) may optionally override " +
"this through their own settings.");
/**
* Enable SSL for internal communication (akka rpc, netty data transport, blob server).
*/
@Documentation.CommonOption(position = Documentation.CommonOption.POSITION_SECURITY)
public static final ConfigOption<Boolean> SSL_INTERNAL_ENABLED =
key("security.ssl.internal.enabled")
.defaultValue(false)
.withDescription("Turns on SSL for internal network communication. " +
"Optionally, specific components may override this through their own settings " +
"(rpc, data transport, REST, etc).");
/**
* Enable SSL for external REST endpoints.
*/
@Documentation.CommonOption(position = Documentation.CommonOption.POSITION_SECURITY)
public static final ConfigOption<Boolean> SSL_REST_ENABLED =
key("security.ssl.rest.enabled")
.defaultValue(false)
.withDescription("Turns on SSL for external communication via the REST endpoints.");
// ----------------- certificates (internal + external) -------------------
/**
* The Java keystore file containing the flink endpoint key and certificate.
*/
public static final ConfigOption<String> SSL_KEYSTORE =
key("security.ssl.keystore")
.noDefaultValue()
.withDescription("The Java keystore file to be used by the flink endpoint for its SSL Key and Certificate.");
/**
* Secret to decrypt the keystore file.
*/
public static final ConfigOption<String> SSL_KEYSTORE_PASSWORD =
key("security.ssl.keystore-password")
.noDefaultValue()
.withDescription("The secret to decrypt the keystore file.");
/**
* Secret to decrypt the server key.
*/
public static final ConfigOption<String> SSL_KEY_PASSWORD =
key("security.ssl.key-password")
.noDefaultValue()
.withDescription("The secret to decrypt the server key in the keystore.");
/**
* The truststore file containing the public CA certificates to verify the ssl peers.
*/
public static final ConfigOption<String> SSL_TRUSTSTORE =
key("security.ssl.truststore")
.noDefaultValue()
.withDescription("The truststore file containing the public CA certificates to be used by flink endpoints" +
" to verify the peer’s certificate.");
/**
* Secret to decrypt the truststore.
*/
public static final ConfigOption<String> SSL_TRUSTSTORE_PASSWORD =
key("security.ssl.truststore-password")
.noDefaultValue()
.withDescription("The secret to decrypt the truststore.");
// ----------------------- certificates (internal) ------------------------
/**
* For internal SSL, the Java keystore file containing the private key and certificate.
*/
public static final ConfigOption<String> SSL_INTERNAL_KEYSTORE =
key("security.ssl.internal.keystore")
.noDefaultValue()
.withDescription("The Java keystore file with SSL Key and Certificate, " +
"to be used Flink's internal endpoints (rpc, data transport, blob server).");
/**
* For internal SSL, the password to decrypt the keystore file containing the certificate.
*/
public static final ConfigOption<String> SSL_INTERNAL_KEYSTORE_PASSWORD =
key("security.ssl.internal.keystore-password")
.noDefaultValue()
.withDescription("The secret to decrypt the keystore file for Flink's " +
"for Flink's internal endpoints (rpc, data transport, blob server).");
/**
* For internal SSL, the password to decrypt the private key.
*/
public static final ConfigOption<String> SSL_INTERNAL_KEY_PASSWORD =
key("security.ssl.internal.key-password")
.noDefaultValue()
.withDescription("The secret to decrypt the key in the keystore " +
"for Flink's internal endpoints (rpc, data transport, blob server).");
/**
* For internal SSL, the truststore file containing the public CA certificates to verify the ssl peers.
*/
public static final ConfigOption<String> SSL_INTERNAL_TRUSTSTORE =
key("security.ssl.internal.truststore")
.noDefaultValue()
.withDescription("The truststore file containing the public CA certificates to verify the peer " +
"for Flink's internal endpoints (rpc, data transport, blob server).");
/**
* For internal SSL, the secret to decrypt the truststore.
*/
public static final ConfigOption<String> SSL_INTERNAL_TRUSTSTORE_PASSWORD =
key("security.ssl.internal.truststore-password")
.noDefaultValue()
.withDescription("The password to decrypt the truststore " +
"for Flink's internal endpoints (rpc, data transport, blob server).");
// ----------------------- certificates (external) ------------------------
/**
* For external (REST) SSL, the Java keystore file containing the private key and certificate.
*/
public static final ConfigOption<String> SSL_REST_KEYSTORE =
key("security.ssl.rest.keystore")
.noDefaultValue()
.withDescription("The Java keystore file with SSL Key and Certificate, " +
"to be used Flink's external REST endpoints.");
/**
* For external (REST) SSL, the password to decrypt the keystore file containing the certificate.
*/
public static final ConfigOption<String> SSL_REST_KEYSTORE_PASSWORD =
key("security.ssl.rest.keystore-password")
.noDefaultValue()
.withDescription("The secret to decrypt the keystore file for Flink's " +
"for Flink's external REST endpoints.");
/**
* For external (REST) SSL, the password to decrypt the private key.
*/
public static final ConfigOption<String> SSL_REST_KEY_PASSWORD =
key("security.ssl.rest.key-password")
.noDefaultValue()
.withDescription("The secret to decrypt the key in the keystore " +
"for Flink's external REST endpoints.");
/**
* For external (REST) SSL, the truststore file containing the public CA certificates to verify the ssl peers.
*/
public static final ConfigOption<String> SSL_REST_TRUSTSTORE =
key("security.ssl.rest.truststore")
.noDefaultValue()
.withDescription("The truststore file containing the public CA certificates to verify the peer " +
"for Flink's external REST endpoints.");
/**
* For external (REST) SSL, the secret to decrypt the truststore.
*/
public static final ConfigOption<String> SSL_REST_TRUSTSTORE_PASSWORD =
key("security.ssl.rest.truststore-password")
.noDefaultValue()
.withDescription("The password to decrypt the truststore " +
"for Flink's external REST endpoints.");
// ------------------------ ssl parameters --------------------------------
/**
* SSL protocol version to be supported.
*/
public static final ConfigOption<String> SSL_PROTOCOL =
key("security.ssl.protocol")
.defaultValue("TLSv1.2")
.withDescription("The SSL protocol version to be supported for the ssl transport. Note that it doesn’t" +
" support comma separated list.");
/**
* The standard SSL algorithms to be supported.
*
* <p>More options here - http://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#ciphersuites
*/
public static final ConfigOption<String> SSL_ALGORITHMS =
key("security.ssl.algorithms")
.defaultValue("TLS_RSA_WITH_AES_128_CBC_SHA")
.withDescription(Description.builder()
.text("The comma separated list of standard SSL algorithms to be supported. Read more %s",
link(
"http://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#ciphersuites",
"here"))
.build());
/**
* Flag to enable/disable hostname verification for the ssl connections.
*/
public static final ConfigOption<Boolean> SSL_VERIFY_HOSTNAME =
key("security.ssl.verify-hostname")
.defaultValue(true)
.withDescription("Flag to enable peer’s hostname verification during ssl handshake.");
}
| apache-2.0 |
igorng/alien4cloud | alien4cloud-security/src/test/java/alien4cloud/security/LdapAuthenticationProviderTest.java | 2840 | package alien4cloud.security;
import java.util.List;
import javax.annotation.Resource;
import javax.naming.NamingException;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.mockito.Mockito;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import alien4cloud.ldap.LdapAuthenticationProvider;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:ldap-authentication-provider-security-test.xml")
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class LdapAuthenticationProviderTest extends AbstractLdapTest {
@Resource
private IAlienUserDao alienUserDao;
@Resource
private LdapTemplate ldapTemplate;
@Resource
private LdapAuthenticationProvider ldapAuthenticationProvider;
@Test
public void testLdapUserImport() throws NamingException {
Mockito.when(ldapTemplate.getContextSource()).thenReturn(Mockito.mock(ContextSource.class));
int userCount = 10;
List<User> users = prepareGetAllUserMock(userCount);
// for each user we should check if it exists in the user repository and only if not then we add it.
for (int i = 0; i < users.size(); i++) {
User user = users.get(i);
if (i % 2 == 0) {
user.setLastName("test");
Mockito.when(alienUserDao.find(user.getUsername())).thenReturn(user);
} else {
Mockito.when(alienUserDao.find(user.getUsername())).thenReturn(user);
}
}
ldapAuthenticationProvider.importLdapUsers();
Mockito.verify(alienUserDao, Mockito.times(users.size())).save(Mockito.any(User.class));
}
@Test
public void testAuthenticate() {
String userName = "admin";
String password = "admin";
Mockito.when(ldapTemplate.authenticate("", getUserIdKey() + "=" + userName, password)).thenReturn(true);
ldapAuthenticationProvider.authenticate(new UsernamePasswordAuthenticationToken(userName, password));
}
@Test(expected = BadCredentialsException.class)
public void testAuthenticateShouldFailIfWrontPassword() {
String userName = "admin";
String password = "admin";
Mockito.when(ldapTemplate.authenticate("", getUserIdKey() + "=" + userName, password)).thenReturn(false);
ldapAuthenticationProvider.authenticate(new UsernamePasswordAuthenticationToken(userName, password));
}
}
| apache-2.0 |
knifewine/cassandra | test/unit/org/apache/cassandra/index/CustomIndexTest.java | 33520 | package org.apache.cassandra.index;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.junit.Test;
import org.apache.cassandra.Util;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.cql3.CQLTester;
import org.apache.cassandra.cql3.ColumnIdentifier;
import org.apache.cassandra.cql3.restrictions.IndexRestrictions;
import org.apache.cassandra.cql3.statements.IndexTarget;
import org.apache.cassandra.cql3.statements.ModificationStatement;
import org.apache.cassandra.cql3.statements.SelectStatement;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.ReadCommand;
import org.apache.cassandra.db.ReadExecutionController;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.Int32Type;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.db.partitions.UnfilteredPartitionIterator;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.schema.IndexMetadata;
import org.apache.cassandra.schema.Indexes;
import org.apache.cassandra.utils.FBUtilities;
import static org.apache.cassandra.Util.throwAssert;
import static org.apache.cassandra.cql3.statements.IndexTarget.CUSTOM_INDEX_OPTION_NAME;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class CustomIndexTest extends CQLTester
{
@Test
public void testInsertsOnCfsBackedIndex() throws Throwable
{
// test to ensure that we don't deadlock when flushing CFS backed custom indexers
// see CASSANDRA-10181
createTable("CREATE TABLE %s (a int, b int, c int, d int, PRIMARY KEY (a, b))");
createIndex("CREATE CUSTOM INDEX myindex ON %s(c) USING 'org.apache.cassandra.index.internal.CustomCassandraIndex'");
execute("INSERT INTO %s (a, b, c, d) VALUES (?, ?, ?, ?)", 0, 0, 0, 2);
execute("INSERT INTO %s (a, b, c, d) VALUES (?, ?, ?, ?)", 0, 1, 0, 1);
execute("INSERT INTO %s (a, b, c, d) VALUES (?, ?, ?, ?)", 0, 2, 0, 0);
}
@Test
public void indexControlsIfIncludedInBuildOnNewSSTables() throws Throwable
{
createTable("CREATE TABLE %s (a int, b int, PRIMARY KEY (a))");
String toInclude = "include";
String toExclude = "exclude";
createIndex(String.format("CREATE CUSTOM INDEX %s ON %%s(b) USING '%s'",
toInclude, IndexIncludedInBuild.class.getName()));
createIndex(String.format("CREATE CUSTOM INDEX %s ON %%s(b) USING '%s'",
toExclude, IndexExcludedFromBuild.class.getName()));
execute("INSERT INTO %s (a, b) VALUES (?, ?)", 0, 0);
execute("INSERT INTO %s (a, b) VALUES (?, ?)", 1, 1);
execute("INSERT INTO %s (a, b) VALUES (?, ?)", 2, 2);
flush();
SecondaryIndexManager indexManager = getCurrentColumnFamilyStore().indexManager;
IndexIncludedInBuild included = (IndexIncludedInBuild)indexManager.getIndexByName(toInclude);
included.reset();
assertTrue(included.rowsInserted.isEmpty());
IndexExcludedFromBuild excluded = (IndexExcludedFromBuild)indexManager.getIndexByName(toExclude);
excluded.reset();
assertTrue(excluded.rowsInserted.isEmpty());
indexManager.buildAllIndexesBlocking(getCurrentColumnFamilyStore().getLiveSSTables());
assertEquals(3, included.rowsInserted.size());
assertTrue(excluded.rowsInserted.isEmpty());
}
@Test
public void indexReceivesWriteTimeDeletionsCorrectly() throws Throwable
{
createTable("CREATE TABLE %s (a int, b int, c int, d int, PRIMARY KEY (a, b, c))");
String indexName = "test_index";
createIndex(String.format("CREATE CUSTOM INDEX %s ON %%s(d) USING '%s'",
indexName, StubIndex.class.getName()));
execute("INSERT INTO %s (a, b, c, d) VALUES (?, ?, ?, ?)", 0, 0, 0, 0);
execute("INSERT INTO %s (a, b, c, d) VALUES (?, ?, ?, ?)", 0, 0, 1, 1);
execute("INSERT INTO %s (a, b, c, d) VALUES (?, ?, ?, ?)", 0, 0, 2, 2);
execute("INSERT INTO %s (a, b, c, d) VALUES (?, ?, ?, ?)", 0, 1, 3, 3);
SecondaryIndexManager indexManager = getCurrentColumnFamilyStore().indexManager;
StubIndex index = (StubIndex)indexManager.getIndexByName(indexName);
assertEquals(4, index.rowsInserted.size());
assertTrue(index.partitionDeletions.isEmpty());
assertTrue(index.rangeTombstones.isEmpty());
execute("DELETE FROM %s WHERE a=0 AND b=0");
assertTrue(index.partitionDeletions.isEmpty());
assertEquals(1, index.rangeTombstones.size());
execute("DELETE FROM %s WHERE a=0");
assertEquals(1, index.partitionDeletions.size());
assertEquals(1, index.rangeTombstones.size());
}
@Test
public void nonCustomIndexesRequireExactlyOneTargetColumn() throws Throwable
{
createTable("CREATE TABLE %s(k int, c int, v1 int, v2 int, PRIMARY KEY (k,c))");
assertInvalidMessage("Only CUSTOM indexes support multiple columns", "CREATE INDEX multi_idx on %s(v1,v2)");
assertInvalidMessage("Only CUSTOM indexes can be created without specifying a target column",
"CREATE INDEX no_targets on %s()");
createIndex(String.format("CREATE CUSTOM INDEX multi_idx ON %%s(v1, v2) USING '%s'", StubIndex.class.getName()));
assertIndexCreated("multi_idx", "v1", "v2");
}
@Test
public void rejectDuplicateColumnsInTargetList() throws Throwable
{
createTable("CREATE TABLE %s(k int, c int, v1 int, v2 int, PRIMARY KEY (k,c))");
assertInvalidMessage("Duplicate column v1 in index target list",
String.format("CREATE CUSTOM INDEX ON %%s(v1, v1) USING '%s'",
StubIndex.class.getName()));
assertInvalidMessage("Duplicate column v1 in index target list",
String.format("CREATE CUSTOM INDEX ON %%s(v1, v1, c, c) USING '%s'",
StubIndex.class.getName()));
}
@Test
public void requireFullQualifierForFrozenCollectionTargets() throws Throwable
{
// this is really just to prove that we require the full modifier on frozen collection
// targets whether the index is multicolumn or not
createTable("CREATE TABLE %s(" +
" k int," +
" c int," +
" fmap frozen<map<int, text>>," +
" flist frozen<list<int>>," +
" fset frozen<set<int>>," +
" PRIMARY KEY(k,c))");
assertInvalidMessage("Cannot create keys() index on frozen column fmap. " +
"Frozen collections only support full() indexes",
String.format("CREATE CUSTOM INDEX ON %%s(c, keys(fmap)) USING'%s'",
StubIndex.class.getName()));
assertInvalidMessage("Cannot create entries() index on frozen column fmap. " +
"Frozen collections only support full() indexes",
String.format("CREATE CUSTOM INDEX ON %%s(c, entries(fmap)) USING'%s'",
StubIndex.class.getName()));
assertInvalidMessage("Cannot create values() index on frozen column fmap. " +
"Frozen collections only support full() indexes",
String.format("CREATE CUSTOM INDEX ON %%s(c, fmap) USING'%s'", StubIndex.class.getName()));
assertInvalidMessage("Cannot create keys() index on frozen column flist. " +
"Frozen collections only support full() indexes",
String.format("CREATE CUSTOM INDEX ON %%s(c, keys(flist)) USING'%s'",
StubIndex.class.getName()));
assertInvalidMessage("Cannot create entries() index on frozen column flist. " +
"Frozen collections only support full() indexes",
String.format("CREATE CUSTOM INDEX ON %%s(c, entries(flist)) USING'%s'",
StubIndex.class.getName()));
assertInvalidMessage("Cannot create values() index on frozen column flist. " +
"Frozen collections only support full() indexes",
String.format("CREATE CUSTOM INDEX ON %%s(c, flist) USING'%s'", StubIndex.class.getName()));
assertInvalidMessage("Cannot create keys() index on frozen column fset. " +
"Frozen collections only support full() indexes",
String.format("CREATE CUSTOM INDEX ON %%s(c, keys(fset)) USING'%s'",
StubIndex.class.getName()));
assertInvalidMessage("Cannot create entries() index on frozen column fset. " +
"Frozen collections only support full() indexes",
String.format("CREATE CUSTOM INDEX ON %%s(c, entries(fset)) USING'%s'",
StubIndex.class.getName()));
assertInvalidMessage("Cannot create values() index on frozen column fset. " +
"Frozen collections only support full() indexes",
String.format("CREATE CUSTOM INDEX ON %%s(c, fset) USING'%s'", StubIndex.class.getName()));
createIndex(String.format("CREATE CUSTOM INDEX ON %%s(c, full(fmap)) USING'%s'", StubIndex.class.getName()));
createIndex(String.format("CREATE CUSTOM INDEX ON %%s(c, full(flist)) USING'%s'", StubIndex.class.getName()));
createIndex(String.format("CREATE CUSTOM INDEX ON %%s(c, full(fset)) USING'%s'", StubIndex.class.getName()));
}
@Test
public void defaultIndexNameContainsTargetColumns() throws Throwable
{
createTable("CREATE TABLE %s(k int, c int, v1 int, v2 int, PRIMARY KEY(k,c))");
createIndex(String.format("CREATE CUSTOM INDEX ON %%s(v1, v2) USING '%s'", StubIndex.class.getName()));
assertEquals(1, getCurrentColumnFamilyStore().metadata.getIndexes().size());
assertIndexCreated(currentTable() + "_idx", "v1", "v2");
createIndex(String.format("CREATE CUSTOM INDEX ON %%s(c, v1, v2) USING '%s'", StubIndex.class.getName()));
assertEquals(2, getCurrentColumnFamilyStore().metadata.getIndexes().size());
assertIndexCreated(currentTable() + "_idx_1", "c", "v1", "v2");
createIndex(String.format("CREATE CUSTOM INDEX ON %%s(c, v2) USING '%s'", StubIndex.class.getName()));
assertEquals(3, getCurrentColumnFamilyStore().metadata.getIndexes().size());
assertIndexCreated(currentTable() + "_idx_2", "c", "v2");
// duplicate the previous index with some additional options and check the name is generated as expected
createIndex(String.format("CREATE CUSTOM INDEX ON %%s(c, v2) USING '%s' WITH OPTIONS = {'foo':'bar'}",
StubIndex.class.getName()));
assertEquals(4, getCurrentColumnFamilyStore().metadata.getIndexes().size());
Map<String, String> options = new HashMap<>();
options.put("foo", "bar");
assertIndexCreated(currentTable() + "_idx_3", options, "c", "v2");
}
@Test
public void createMultiColumnIndexes() throws Throwable
{
// smoke test for various permutations of multicolumn indexes
createTable("CREATE TABLE %s (" +
" pk1 int," +
" pk2 int," +
" c1 int," +
" c2 int," +
" v1 int," +
" v2 int," +
" mval map<text, int>," +
" lval list<int>," +
" sval set<int>," +
" fmap frozen<map<text,int>>," +
" flist frozen<list<int>>," +
" fset frozen<set<int>>," +
" PRIMARY KEY ((pk1, pk2), c1, c2))");
testCreateIndex("idx_1", "pk1", "pk2");
testCreateIndex("idx_2", "pk1", "c1");
testCreateIndex("idx_3", "pk1", "c2");
testCreateIndex("idx_4", "c1", "c2");
testCreateIndex("idx_5", "c2", "v1");
testCreateIndex("idx_6", "v1", "v2");
testCreateIndex("idx_7", "pk2", "c2", "v2");
testCreateIndex("idx_8", "pk1", "c1", "v1", "mval", "sval", "lval");
createIndex(String.format("CREATE CUSTOM INDEX inc_frozen ON %%s(" +
" pk2, c2, v2, full(fmap), full(fset), full(flist)" +
") USING '%s'",
StubIndex.class.getName()));
assertIndexCreated("inc_frozen",
new HashMap<>(),
ImmutableList.of(indexTarget("pk2", IndexTarget.Type.VALUES),
indexTarget("c2", IndexTarget.Type.VALUES),
indexTarget("v2", IndexTarget.Type.VALUES),
indexTarget("fmap", IndexTarget.Type.FULL),
indexTarget("fset", IndexTarget.Type.FULL),
indexTarget("flist", IndexTarget.Type.FULL)));
createIndex(String.format("CREATE CUSTOM INDEX all_teh_things ON %%s(" +
" pk1, pk2, c1, c2, v1, v2, keys(mval), lval, sval, full(fmap), full(fset), full(flist)" +
") USING '%s'",
StubIndex.class.getName()));
assertIndexCreated("all_teh_things",
new HashMap<>(),
ImmutableList.of(indexTarget("pk1", IndexTarget.Type.VALUES),
indexTarget("pk2", IndexTarget.Type.VALUES),
indexTarget("c1", IndexTarget.Type.VALUES),
indexTarget("c2", IndexTarget.Type.VALUES),
indexTarget("v1", IndexTarget.Type.VALUES),
indexTarget("v2", IndexTarget.Type.VALUES),
indexTarget("mval", IndexTarget.Type.KEYS),
indexTarget("lval", IndexTarget.Type.VALUES),
indexTarget("sval", IndexTarget.Type.VALUES),
indexTarget("fmap", IndexTarget.Type.FULL),
indexTarget("fset", IndexTarget.Type.FULL),
indexTarget("flist", IndexTarget.Type.FULL)));
}
@Test
public void createMultiColumnIndexIncludingUserTypeColumn() throws Throwable
{
String myType = KEYSPACE + '.' + createType("CREATE TYPE %s (a int, b int)");
createTable("CREATE TABLE %s (k int PRIMARY KEY, v1 int, v2 frozen<" + myType + ">)");
testCreateIndex("udt_idx", "v1", "v2");
Indexes indexes = getCurrentColumnFamilyStore().metadata.getIndexes();
IndexMetadata expected = IndexMetadata.fromIndexTargets(getCurrentColumnFamilyStore().metadata,
ImmutableList.of(indexTarget("v1", IndexTarget.Type.VALUES),
indexTarget("v2", IndexTarget.Type.VALUES)),
"udt_idx",
IndexMetadata.Kind.CUSTOM,
ImmutableMap.of(CUSTOM_INDEX_OPTION_NAME,
StubIndex.class.getName()));
IndexMetadata actual = indexes.get("udt_idx").orElseThrow(throwAssert("Index udt_idx not found"));
assertEquals(expected, actual);
}
@Test
public void createIndexWithoutTargets() throws Throwable
{
createTable("CREATE TABLE %s(k int, c int, v1 int, v2 int, PRIMARY KEY(k,c))");
// only allowed for CUSTOM indexes
assertInvalidMessage("Only CUSTOM indexes can be created without specifying a target column",
"CREATE INDEX ON %s()");
// parentheses are mandatory
assertInvalidSyntax("CREATE CUSTOM INDEX ON %%s USING '%s'", StubIndex.class.getName());
createIndex(String.format("CREATE CUSTOM INDEX no_targets ON %%s() USING '%s'", StubIndex.class.getName()));
assertIndexCreated("no_targets", new HashMap<>());
}
@Test
public void testCustomIndexExpressionSyntax() throws Throwable
{
Object[] row = row(0, 0, 0, 0);
createTable("CREATE TABLE %s (a int, b int, c int, d int, PRIMARY KEY (a, b))");
execute("INSERT INTO %s (a, b, c, d) VALUES (?, ?, ?, ?)", row);
assertInvalidMessage(String.format(IndexRestrictions.INDEX_NOT_FOUND, "custom_index", keyspace(), currentTable()),
"SELECT * FROM %s WHERE expr(custom_index, 'foo bar baz')");
createIndex(String.format("CREATE CUSTOM INDEX custom_index ON %%s(c) USING '%s'", StubIndex.class.getName()));
assertInvalidMessage(String.format(IndexRestrictions.INDEX_NOT_FOUND, "no_such_index", keyspace(), currentTable()),
"SELECT * FROM %s WHERE expr(no_such_index, 'foo bar baz ')");
// simple case
assertRows(execute("SELECT * FROM %s WHERE expr(custom_index, 'foo bar baz')"), row);
assertRows(execute("SELECT * FROM %s WHERE expr(\"custom_index\", 'foo bar baz')"), row);
assertRows(execute("SELECT * FROM %s WHERE expr(custom_index, $$foo \" ~~~ bar Baz$$)"), row);
// multiple expressions on the same index
assertInvalidMessage(IndexRestrictions.MULTIPLE_EXPRESSIONS,
"SELECT * FROM %s WHERE expr(custom_index, 'foo') AND expr(custom_index, 'bar')");
// multiple expressions on different indexes
createIndex(String.format("CREATE CUSTOM INDEX other_custom_index ON %%s(d) USING '%s'", StubIndex.class.getName()));
assertInvalidMessage(IndexRestrictions.MULTIPLE_EXPRESSIONS,
"SELECT * FROM %s WHERE expr(custom_index, 'foo') AND expr(other_custom_index, 'bar')");
assertInvalidMessage(SelectStatement.REQUIRES_ALLOW_FILTERING_MESSAGE,
"SELECT * FROM %s WHERE expr(custom_index, 'foo') AND d=0");
assertRows(execute("SELECT * FROM %s WHERE expr(custom_index, 'foo') AND d=0 ALLOW FILTERING"), row);
}
@Test
public void customIndexDoesntSupportCustomExpressions() throws Throwable
{
createTable("CREATE TABLE %s (a int, b int, c int, d int, PRIMARY KEY (a, b))");
createIndex(String.format("CREATE CUSTOM INDEX custom_index ON %%s(c) USING '%s'",
NoCustomExpressionsIndex.class.getName()));
assertInvalidMessage(String.format( IndexRestrictions.CUSTOM_EXPRESSION_NOT_SUPPORTED, "custom_index"),
"SELECT * FROM %s WHERE expr(custom_index, 'foo bar baz')");
}
@Test
public void customIndexRejectsExpressionSyntax() throws Throwable
{
createTable("CREATE TABLE %s (a int, b int, c int, d int, PRIMARY KEY (a, b))");
createIndex(String.format("CREATE CUSTOM INDEX custom_index ON %%s(c) USING '%s'",
ExpressionRejectingIndex.class.getName()));
assertInvalidMessage("None shall pass", "SELECT * FROM %s WHERE expr(custom_index, 'foo bar baz')");
}
@Test
public void customExpressionsMustTargetCustomIndex() throws Throwable
{
createTable("CREATE TABLE %s (a int, b int, c int, d int, PRIMARY KEY (a, b))");
createIndex("CREATE INDEX non_custom_index ON %s(c)");
assertInvalidMessage(String.format(IndexRestrictions.NON_CUSTOM_INDEX_IN_EXPRESSION, "non_custom_index"),
"SELECT * FROM %s WHERE expr(non_custom_index, 'c=0')");
}
@Test
public void customExpressionsDisallowedInModifications() throws Throwable
{
createTable("CREATE TABLE %s (a int, b int, c int, d int, PRIMARY KEY (a, b))");
createIndex(String.format("CREATE CUSTOM INDEX custom_index ON %%s(c) USING '%s'", StubIndex.class.getName()));
assertInvalidMessage(ModificationStatement.CUSTOM_EXPRESSIONS_NOT_ALLOWED,
"DELETE FROM %s WHERE expr(custom_index, 'foo bar baz ')");
assertInvalidMessage(ModificationStatement.CUSTOM_EXPRESSIONS_NOT_ALLOWED,
"UPDATE %s SET d=0 WHERE expr(custom_index, 'foo bar baz ')");
}
@Test
public void indexSelectionPrefersMostSelectiveIndex() throws Throwable
{
createTable("CREATE TABLE %s(a int, b int, c int, PRIMARY KEY (a))");
createIndex(String.format("CREATE CUSTOM INDEX more_selective ON %%s(b) USING '%s'",
SettableSelectivityIndex.class.getName()));
createIndex(String.format("CREATE CUSTOM INDEX less_selective ON %%s(c) USING '%s'",
SettableSelectivityIndex.class.getName()));
SettableSelectivityIndex moreSelective =
(SettableSelectivityIndex)getCurrentColumnFamilyStore().indexManager.getIndexByName("more_selective");
SettableSelectivityIndex lessSelective =
(SettableSelectivityIndex)getCurrentColumnFamilyStore().indexManager.getIndexByName("less_selective");
assertEquals(0, moreSelective.searchersProvided);
assertEquals(0, lessSelective.searchersProvided);
// the more selective index should be chosen
moreSelective.setEstimatedResultRows(1);
lessSelective.setEstimatedResultRows(1000);
execute("SELECT * FROM %s WHERE b=0 AND c=0 ALLOW FILTERING");
assertEquals(1, moreSelective.searchersProvided);
assertEquals(0, lessSelective.searchersProvided);
// and adjusting the selectivity should have an observable effect
moreSelective.setEstimatedResultRows(10000);
execute("SELECT * FROM %s WHERE b=0 AND c=0 ALLOW FILTERING");
assertEquals(1, moreSelective.searchersProvided);
assertEquals(1, lessSelective.searchersProvided);
}
@Test
public void customExpressionForcesIndexSelection() throws Throwable
{
createTable("CREATE TABLE %s(a int, b int, c int, PRIMARY KEY (a))");
createIndex(String.format("CREATE CUSTOM INDEX more_selective ON %%s(b) USING '%s'",
SettableSelectivityIndex.class.getName()));
createIndex(String.format("CREATE CUSTOM INDEX less_selective ON %%s(c) USING '%s'",
SettableSelectivityIndex.class.getName()));
SettableSelectivityIndex moreSelective =
(SettableSelectivityIndex)getCurrentColumnFamilyStore().indexManager.getIndexByName("more_selective");
SettableSelectivityIndex lessSelective =
(SettableSelectivityIndex)getCurrentColumnFamilyStore().indexManager.getIndexByName("less_selective");
assertEquals(0, moreSelective.searchersProvided);
assertEquals(0, lessSelective.searchersProvided);
// without a custom expression, the more selective index should be chosen
moreSelective.setEstimatedResultRows(1);
lessSelective.setEstimatedResultRows(1000);
execute("SELECT * FROM %s WHERE b=0 AND c=0 ALLOW FILTERING");
assertEquals(1, moreSelective.searchersProvided);
assertEquals(0, lessSelective.searchersProvided);
// when a custom expression is present, its target index should be preferred
execute("SELECT * FROM %s WHERE b=0 AND expr(less_selective, 'expression') ALLOW FILTERING");
assertEquals(1, moreSelective.searchersProvided);
assertEquals(1, lessSelective.searchersProvided);
}
@Test
public void testCustomExpressionValueType() throws Throwable
{
// verify that the type of the expression value is determined by Index::customExpressionValueType
createTable("CREATE TABLE %s (k int, v1 uuid, v2 blob, PRIMARY KEY(k))");
createIndex(String.format("CREATE CUSTOM INDEX int_index ON %%s() USING '%s'",
Int32ExpressionIndex.class.getName()));
createIndex(String.format("CREATE CUSTOM INDEX text_index ON %%s() USING '%s'",
UTF8ExpressionIndex.class.getName()));
execute("SELECT * FROM %s WHERE expr(text_index, 'foo')");
assertInvalidMessage("Invalid INTEGER constant (99) for \"custom index expression\" of type text",
"SELECT * FROM %s WHERE expr(text_index, 99)");
execute("SELECT * FROM %s WHERE expr(int_index, 99)");
assertInvalidMessage("Invalid STRING constant (foo) for \"custom index expression\" of type int",
"SELECT * FROM %s WHERE expr(int_index, 'foo')");
}
@Test
public void reloadIndexMetadataOnBaseCfsReload() throws Throwable
{
// verify that whenever the base table CFMetadata is reloaded, a reload of the index
// metadata is performed
createTable("CREATE TABLE %s (k int, v1 int, PRIMARY KEY(k))");
createIndex(String.format("CREATE CUSTOM INDEX reload_counter ON %%s() USING '%s'",
CountMetadataReloadsIndex.class.getName()));
ColumnFamilyStore cfs = getCurrentColumnFamilyStore();
CountMetadataReloadsIndex index = (CountMetadataReloadsIndex)cfs.indexManager.getIndexByName("reload_counter");
assertEquals(0, index.reloads.get());
// reloading the CFS, even without any metadata changes invokes the index's metadata reload task
cfs.reload();
assertEquals(1, index.reloads.get());
}
@Test
public void notifyIndexersOfPartitionAndRowRemovalDuringCleanup() throws Throwable
{
createTable("CREATE TABLE %s (k int, c int, v int, PRIMARY KEY (k,c))");
createIndex(String.format("CREATE CUSTOM INDEX cleanup_index ON %%s() USING '%s'", StubIndex.class.getName()));
ColumnFamilyStore cfs = getCurrentColumnFamilyStore();
StubIndex index = (StubIndex)cfs.indexManager.getIndexByName("cleanup_index");
execute("INSERT INTO %s (k, c, v) VALUES (?, ?, ?)", 0, 0, 0);
execute("INSERT INTO %s (k, c, v) VALUES (?, ?, ?)", 0, 1, 1);
execute("INSERT INTO %s (k, c, v) VALUES (?, ?, ?)", 0, 2, 2);
execute("INSERT INTO %s (k, c, v) VALUES (?, ?, ?)", 3, 3, 3);
assertEquals(4, index.rowsInserted.size());
assertEquals(0, index.partitionDeletions.size());
ReadCommand cmd = Util.cmd(cfs, 0).build();
try (ReadExecutionController executionController = cmd.executionController();
UnfilteredPartitionIterator iterator = cmd.executeLocally(executionController))
{
assertTrue(iterator.hasNext());
cfs.indexManager.deletePartition(iterator.next(), FBUtilities.nowInSeconds());
}
assertEquals(1, index.partitionDeletions.size());
assertEquals(3, index.rowsDeleted.size());
for (int i = 0; i < 3; i++)
assertEquals(index.rowsDeleted.get(i).clustering(), index.rowsInserted.get(i).clustering());
}
private void testCreateIndex(String indexName, String... targetColumnNames) throws Throwable
{
createIndex(String.format("CREATE CUSTOM INDEX %s ON %%s(%s) USING '%s'",
indexName,
Arrays.stream(targetColumnNames).collect(Collectors.joining(",")),
StubIndex.class.getName()));
assertIndexCreated(indexName, targetColumnNames);
}
private void assertIndexCreated(String name, String... targetColumnNames)
{
assertIndexCreated(name, new HashMap<>(), targetColumnNames);
}
private void assertIndexCreated(String name, Map<String, String> options, String... targetColumnNames)
{
List<IndexTarget> targets = Arrays.stream(targetColumnNames)
.map(s -> new IndexTarget(ColumnIdentifier.getInterned(s, true),
IndexTarget.Type.VALUES))
.collect(Collectors.toList());
assertIndexCreated(name, options, targets);
}
private void assertIndexCreated(String name, Map<String, String> options, List<IndexTarget> targets)
{
// all tests here use StubIndex as the custom index class,
// so add that to the map of options
options.put(CUSTOM_INDEX_OPTION_NAME, StubIndex.class.getName());
CFMetaData cfm = getCurrentColumnFamilyStore().metadata;
IndexMetadata expected = IndexMetadata.fromIndexTargets(cfm, targets, name, IndexMetadata.Kind.CUSTOM, options);
Indexes indexes = getCurrentColumnFamilyStore().metadata.getIndexes();
for (IndexMetadata actual : indexes)
if (actual.equals(expected))
return;
fail(String.format("Index %s not found in CFMetaData", expected));
}
private static IndexTarget indexTarget(String name, IndexTarget.Type type)
{
return new IndexTarget(ColumnIdentifier.getInterned(name, true), type);
}
public static final class CountMetadataReloadsIndex extends StubIndex
{
private final AtomicInteger reloads = new AtomicInteger(0);
public CountMetadataReloadsIndex(ColumnFamilyStore baseCfs, IndexMetadata metadata)
{
super(baseCfs, metadata);
}
public void reset()
{
super.reset();
reloads.set(0);
}
public Callable<?> getMetadataReloadTask(IndexMetadata indexMetadata)
{
return reloads::incrementAndGet;
}
}
public static final class IndexIncludedInBuild extends StubIndex
{
public IndexIncludedInBuild(ColumnFamilyStore baseCfs, IndexMetadata metadata)
{
super(baseCfs, metadata);
}
public boolean shouldBuildBlocking()
{
return true;
}
}
public static final class UTF8ExpressionIndex extends StubIndex
{
public UTF8ExpressionIndex(ColumnFamilyStore baseCfs, IndexMetadata metadata)
{
super(baseCfs, metadata);
}
public AbstractType<?> customExpressionValueType()
{
return UTF8Type.instance;
}
}
public static final class Int32ExpressionIndex extends StubIndex
{
public Int32ExpressionIndex(ColumnFamilyStore baseCfs, IndexMetadata metadata)
{
super(baseCfs, metadata);
}
public AbstractType<?> customExpressionValueType()
{
return Int32Type.instance;
}
}
public static final class SettableSelectivityIndex extends StubIndex
{
private int searchersProvided = 0;
private long estimatedResultRows = 0;
public SettableSelectivityIndex(ColumnFamilyStore baseCfs, IndexMetadata metadata)
{
super(baseCfs, metadata);
}
public void setEstimatedResultRows(long estimate)
{
estimatedResultRows = estimate;
}
public long getEstimatedResultRows()
{
return estimatedResultRows;
}
public Searcher searcherFor(ReadCommand command)
{
searchersProvided++;
return super.searcherFor(command);
}
}
public static final class IndexExcludedFromBuild extends StubIndex
{
public IndexExcludedFromBuild(ColumnFamilyStore baseCfs, IndexMetadata metadata)
{
super(baseCfs, metadata);
}
public boolean shouldBuildBlocking()
{
return false;
}
}
public static final class NoCustomExpressionsIndex extends StubIndex
{
public NoCustomExpressionsIndex(ColumnFamilyStore baseCfs, IndexMetadata metadata)
{
super(baseCfs, metadata);
}
public AbstractType<?> customExpressionValueType()
{
return null;
}
}
public static final class ExpressionRejectingIndex extends StubIndex
{
public ExpressionRejectingIndex(ColumnFamilyStore baseCfs, IndexMetadata metadata)
{
super(baseCfs, metadata);
}
public Searcher searcherFor(ReadCommand command) throws InvalidRequestException
{
throw new InvalidRequestException("None shall pass");
}
}
}
| apache-2.0 |
ChrisCanCompute/assertj-core | src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isBetween_with_String_parameters_Test.java | 2198 | /**
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2017 the original author or authors.
*/
package org.assertj.core.api.offsetdatetime;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.Mockito.verify;
import java.time.OffsetDateTime;
import java.time.format.DateTimeParseException;
import org.assertj.core.api.OffsetDateTimeAssert;
import org.junit.Test;
public class OffsetDateTimeAssert_isBetween_with_String_parameters_Test
extends org.assertj.core.api.OffsetDateTimeAssertBaseTest {
private OffsetDateTime before = now.minusSeconds(1);
private OffsetDateTime after = now.plusSeconds(1);
@Override
protected OffsetDateTimeAssert invoke_api_method() {
return assertions.isBetween(before.toString(), after.toString());
}
@Override
protected void verify_internal_effects() {
verify(comparables).assertIsBetween(getInfo(assertions), getActual(assertions), before, after, true, true);
}
@Test
public void should_throw_a_DateTimeParseException_if_start_String_parameter_cant_be_converted() {
// GIVEN
String abc = "abc";
// WHEN
Throwable thrown = catchThrowable(() -> assertions.isBetween(abc, after.toString()));
// THEN
assertThat(thrown).isInstanceOf(DateTimeParseException.class);
}
@Test
public void should_throw_a_DateTimeParseException_if_end_String_parameter_cant_be_converted() {
// GIVEN
String abc = "abc";
// WHEN
Throwable thrown = catchThrowable(() -> assertions.isBetween(before.toString(), abc));
// THEN
assertThat(thrown).isInstanceOf(DateTimeParseException.class);
}
}
| apache-2.0 |
majinkai/pinpoint | profiler/src/main/java/com/navercorp/pinpoint/profiler/instrument/JavassistMethod.java | 23027 | /*
* Copyright 2014 NAVER Corp.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.navercorp.pinpoint.profiler.instrument;
import java.lang.reflect.Method;
import com.navercorp.pinpoint.bootstrap.instrument.*;
import com.navercorp.pinpoint.bootstrap.interceptor.scope.InterceptorScope;
import com.navercorp.pinpoint.profiler.instrument.interceptor.*;
import com.navercorp.pinpoint.profiler.metadata.ApiMetaDataService;
import com.navercorp.pinpoint.profiler.objectfactory.ObjectBinderFactory;
import javassist.CannotCompileException;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtMethod;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.BadBytecode;
import javassist.bytecode.Bytecode;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.CodeIterator;
import javassist.bytecode.ConstPool;
import javassist.bytecode.Descriptor;
import javassist.compiler.CompileError;
import javassist.compiler.Javac;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.navercorp.pinpoint.bootstrap.context.MethodDescriptor;
import com.navercorp.pinpoint.bootstrap.interceptor.Interceptor;
import com.navercorp.pinpoint.bootstrap.interceptor.scope.ExecutionPolicy;
import com.navercorp.pinpoint.bootstrap.interceptor.registry.InterceptorRegistry;
import com.navercorp.pinpoint.common.util.Assert;
import com.navercorp.pinpoint.profiler.context.DefaultMethodDescriptor;
import com.navercorp.pinpoint.profiler.interceptor.factory.AnnotatedInterceptorFactory;
import com.navercorp.pinpoint.profiler.interceptor.registry.InterceptorRegistryBinder;
import com.navercorp.pinpoint.profiler.util.JavaAssistUtils;
public class JavassistMethod implements InstrumentMethod {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final boolean isDebug = logger.isDebugEnabled();
private final ObjectBinderFactory objectBinderFactory;
private final InstrumentContext pluginContext;
private final InterceptorRegistryBinder interceptorRegistryBinder;
private final ApiMetaDataService apiMetaDataService;
private final CtBehavior behavior;
private final InstrumentClass declaringClass;
private final MethodDescriptor descriptor;
// TODO fix inject InterceptorDefinitionFactory
private static final InterceptorDefinitionFactory interceptorDefinitionFactory = new InterceptorDefinitionFactory();
// TODO fix inject ScopeFactory
private static final ScopeFactory scopeFactory = new ScopeFactory();
public JavassistMethod(ObjectBinderFactory objectBinderFactory, InstrumentContext pluginContext, InterceptorRegistryBinder interceptorRegistryBinder, ApiMetaDataService apiMetaDataService, InstrumentClass declaringClass, CtBehavior behavior) {
if (objectBinderFactory == null) {
throw new NullPointerException("objectBinderFactory must not be null");
}
if (pluginContext == null) {
throw new NullPointerException("pluginContext must not be null");
}
this.objectBinderFactory = objectBinderFactory;
this.pluginContext = pluginContext;
this.interceptorRegistryBinder = interceptorRegistryBinder;
this.apiMetaDataService = apiMetaDataService;
this.behavior = behavior;
this.declaringClass = declaringClass;
String[] parameterVariableNames = JavaAssistUtils.getParameterVariableName(behavior);
int lineNumber = JavaAssistUtils.getLineNumber(behavior);
DefaultMethodDescriptor descriptor = new DefaultMethodDescriptor(behavior.getDeclaringClass().getName(), behavior.getName(), getParameterTypes(), parameterVariableNames);
descriptor.setLineNumber(lineNumber);
this.descriptor = descriptor;
}
@Override
public String getName() {
return behavior.getName();
}
@Override
public String[] getParameterTypes() {
return JavaAssistUtils.parseParameterSignature(behavior.getSignature());
}
@Override
public String getReturnType() {
if (behavior instanceof CtMethod) {
try {
return ((CtMethod) behavior).getReturnType().getName();
} catch (NotFoundException e) {
return null;
}
}
return null;
}
@Override
public int getModifiers() {
return behavior.getModifiers();
}
@Override
public boolean isConstructor() {
return behavior instanceof CtConstructor;
}
@Override
public MethodDescriptor getDescriptor() {
return descriptor;
}
@Override
public int addInterceptor(String interceptorClassName) throws InstrumentException {
Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null");
return addInterceptor0(interceptorClassName, null, null, null);
}
@Override
public int addInterceptor(String interceptorClassName, Object[] constructorArgs) throws InstrumentException {
Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null");
Assert.requireNonNull(constructorArgs, "constructorArgs must not be null");
return addInterceptor0(interceptorClassName, constructorArgs, null, null);
}
@Override
public int addScopedInterceptor(String interceptorClassName, String scopeName) throws InstrumentException {
Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null");
Assert.requireNonNull(scopeName, "scopeName must not be null");
final InterceptorScope interceptorScope = this.pluginContext.getInterceptorScope(scopeName);
return addInterceptor0(interceptorClassName, null, interceptorScope, null);
}
@Override
public int addScopedInterceptor(String interceptorClassName, InterceptorScope scope) throws InstrumentException {
Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null");
Assert.requireNonNull(scope, "scope must not be null");
return addInterceptor0(interceptorClassName, null, scope, null);
}
@Override
public int addScopedInterceptor(String interceptorClassName, String scopeName, ExecutionPolicy executionPolicy) throws InstrumentException {
Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null");
Assert.requireNonNull(scopeName, "scopeName must not be null");
Assert.requireNonNull(executionPolicy, "executionPolicy must not be null");
final InterceptorScope interceptorScope = this.pluginContext.getInterceptorScope(scopeName);
return addInterceptor0(interceptorClassName, null, interceptorScope, executionPolicy);
}
@Override
public int addScopedInterceptor(String interceptorClassName, InterceptorScope scope, ExecutionPolicy executionPolicy) throws InstrumentException {
Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null");
Assert.requireNonNull(scope, "scope must not be null");
Assert.requireNonNull(executionPolicy, "executionPolicy must not be null");
return addInterceptor0(interceptorClassName, null, scope, executionPolicy);
}
@Override
public int addScopedInterceptor(String interceptorClassName, Object[] constructorArgs, String scopeName) throws InstrumentException {
Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null");
Assert.requireNonNull(constructorArgs, "constructorArgs must not be null");
Assert.requireNonNull(scopeName, "scopeName must not be null");
final InterceptorScope interceptorScope = this.pluginContext.getInterceptorScope(scopeName);
return addInterceptor0(interceptorClassName, constructorArgs, interceptorScope, null);
}
@Override
public int addScopedInterceptor(String interceptorClassName, Object[] constructorArgs, InterceptorScope scope) throws InstrumentException {
Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null");
Assert.requireNonNull(constructorArgs, "constructorArgs must not be null");
Assert.requireNonNull(scope, "scope");
return addInterceptor0(interceptorClassName, constructorArgs, scope, null);
}
@Override
public int addScopedInterceptor(String interceptorClassName, Object[] constructorArgs, String scopeName, ExecutionPolicy executionPolicy) throws InstrumentException {
Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null");
Assert.requireNonNull(constructorArgs, "constructorArgs must not be null");
Assert.requireNonNull(scopeName, "scopeName must not be null");
Assert.requireNonNull(executionPolicy, "executionPolicy must not be null");
final InterceptorScope interceptorScope = this.pluginContext.getInterceptorScope(scopeName);
return addInterceptor0(interceptorClassName, constructorArgs, interceptorScope, executionPolicy);
}
@Override
public int addScopedInterceptor(String interceptorClassName, Object[] constructorArgs, InterceptorScope scope, ExecutionPolicy executionPolicy) throws InstrumentException {
Assert.requireNonNull(interceptorClassName, "interceptorClassName must not be null");
Assert.requireNonNull(constructorArgs, "constructorArgs must not be null");
Assert.requireNonNull(scope, "scope must not be null");
Assert.requireNonNull(executionPolicy, "executionPolicy must not be null");
return addInterceptor0(interceptorClassName, constructorArgs, scope, executionPolicy);
}
@Override
public void addInterceptor(int interceptorId) throws InstrumentException {
Interceptor interceptor = InterceptorRegistry.getInterceptor(interceptorId);
try {
addInterceptor0(interceptor, interceptorId);
} catch (Exception e) {
throw new InstrumentException("Failed to add interceptor " + interceptor.getClass().getName() + " to " + behavior.getLongName(), e);
}
}
// for internal api
int addInterceptorInternal(String interceptorClassName, Object[] constructorArgs, InterceptorScope scope, ExecutionPolicy executionPolicy) throws InstrumentException {
if (interceptorClassName == null) {
throw new NullPointerException("interceptorClassName must not be null");
}
return addInterceptor0(interceptorClassName, constructorArgs, scope, executionPolicy);
}
private int addInterceptor0(String interceptorClassName, Object[] constructorArgs, InterceptorScope scope, ExecutionPolicy executionPolicy) throws InstrumentException {
try {
final ClassLoader classLoader = declaringClass.getClassLoader();
final ScopeInfo scopeInfo = scopeFactory.newScopeInfo(classLoader, pluginContext, interceptorClassName, scope, executionPolicy);
Interceptor interceptor = createInterceptor(classLoader, interceptorClassName, scopeInfo, constructorArgs);
int interceptorId = interceptorRegistryBinder.getInterceptorRegistryAdaptor().addInterceptor(interceptor);
addInterceptor0(interceptor, interceptorId);
return interceptorId;
} catch (CannotCompileException ccex) {
throw new InstrumentException("Failed to add interceptor " + interceptorClassName + " to " + behavior.getLongName(), ccex);
} catch (NotFoundException nex) {
throw new InstrumentException("Failed to add interceptor " + interceptorClassName + " to " + behavior.getLongName(), nex);
}
}
private Interceptor createInterceptor(ClassLoader classLoader, String interceptorClassName, ScopeInfo scopeInfo, Object[] constructorArgs) {
AnnotatedInterceptorFactory factory = objectBinderFactory.newAnnotatedInterceptorFactory(pluginContext);
Interceptor interceptor = factory.getInterceptor(classLoader, interceptorClassName, constructorArgs, scopeInfo, declaringClass, this);
return interceptor;
}
private void addInterceptor0(Interceptor interceptor, int interceptorId) throws CannotCompileException, NotFoundException {
if (interceptor == null) {
throw new NullPointerException("interceptor must not be null");
}
final InterceptorDefinition interceptorDefinition = interceptorDefinitionFactory.createInterceptorDefinition(interceptor.getClass());
final String localVariableName = initializeLocalVariable(interceptorId);
int originalCodeOffset = insertBefore(-1, localVariableName);
boolean localVarsInitialized = false;
final int offset = addBeforeInterceptor(interceptorDefinition, interceptorId, originalCodeOffset);
if (offset != -1) {
localVarsInitialized = true;
originalCodeOffset = offset;
}
addAfterInterceptor(interceptorDefinition, interceptorId, localVarsInitialized, originalCodeOffset);
}
private String initializeLocalVariable(int interceptorId) throws CannotCompileException, NotFoundException {
final String interceptorInstanceVar = InvokeCodeGenerator.getInterceptorVar(interceptorId);
addLocalVariable(interceptorInstanceVar, Interceptor.class);
final StringBuilder initVars = new StringBuilder();
initVars.append(interceptorInstanceVar);
initVars.append(" = null;");
return initVars.toString();
}
private void addAfterInterceptor(InterceptorDefinition interceptorDefinition, int interceptorId, boolean localVarsInitialized, int originalCodeOffset) throws NotFoundException, CannotCompileException {
final Class<?> interceptorClass = interceptorDefinition.getInterceptorClass();
final CaptureType captureType = interceptorDefinition.getCaptureType();
if (!isAfterInterceptor(captureType)) {
return;
}
final Method interceptorMethod = interceptorDefinition.getAfterMethod();
if (interceptorMethod == null) {
if (isDebug) {
logger.debug("Skip adding after interceptor because the interceptor doesn't have after method: {}", interceptorClass.getName());
}
return;
}
InvokeAfterCodeGenerator catchGenerator = new InvokeAfterCodeGenerator(interceptorId, interceptorDefinition, declaringClass, this, apiMetaDataService, localVarsInitialized, true);
String catchCode = catchGenerator.generate();
if (isDebug) {
logger.debug("addAfterInterceptor catch behavior:{} code:{}", behavior.getLongName(), catchCode);
}
CtClass throwable = behavior.getDeclaringClass().getClassPool().get("java.lang.Throwable");
insertCatch(originalCodeOffset, catchCode, throwable, "$e");
InvokeAfterCodeGenerator afterGenerator = new InvokeAfterCodeGenerator(interceptorId, interceptorDefinition, declaringClass, this, apiMetaDataService, localVarsInitialized, false);
final String afterCode = afterGenerator.generate();
if (isDebug) {
logger.debug("addAfterInterceptor after behavior:{} code:{}", behavior.getLongName(), afterCode);
}
behavior.insertAfter(afterCode);
}
private boolean isAfterInterceptor(CaptureType captureType) {
return CaptureType.AFTER == captureType || CaptureType.AROUND == captureType;
}
private int addBeforeInterceptor(InterceptorDefinition interceptorDefinition, int interceptorId, int pos) throws CannotCompileException, NotFoundException {
final Class<?> interceptorClass = interceptorDefinition.getInterceptorClass();
final CaptureType captureType = interceptorDefinition.getCaptureType();
if (!isBeforeInterceptor(captureType)) {
return -1;
}
final Method interceptorMethod = interceptorDefinition.getBeforeMethod();
if (interceptorMethod == null) {
if (isDebug) {
logger.debug("Skip adding before interceptorDefinition because the interceptorDefinition doesn't have before method: {}", interceptorClass.getName());
}
return -1;
}
final InvokeBeforeCodeGenerator generator = new InvokeBeforeCodeGenerator(interceptorId, interceptorDefinition, declaringClass, this, apiMetaDataService);
final String beforeCode = generator.generate();
if (isDebug) {
logger.debug("addBeforeInterceptor before behavior:{} code:{}", behavior.getLongName(), beforeCode);
}
return insertBefore(pos, beforeCode);
}
private boolean isBeforeInterceptor(CaptureType captureType) {
return CaptureType.BEFORE == captureType || CaptureType.AROUND == captureType;
}
private void addLocalVariable(String name, Class<?> type) throws CannotCompileException, NotFoundException {
final String interceptorClassName = type.getName();
final CtClass interceptorCtClass = behavior.getDeclaringClass().getClassPool().get(interceptorClassName);
behavior.addLocalVariable(name, interceptorCtClass);
}
private int insertBefore(int pos, String src) throws CannotCompileException {
if (isConstructor()) {
return insertBeforeConstructor(pos, src);
} else {
return insertBeforeMethod(pos, src);
}
}
private int insertBeforeMethod(int pos, String src) throws CannotCompileException {
CtClass cc = behavior.getDeclaringClass();
CodeAttribute ca = behavior.getMethodInfo().getCodeAttribute();
if (ca == null)
throw new CannotCompileException("no method body");
CodeIterator iterator = ca.iterator();
Javac jv = new Javac(cc);
try {
int nvars = jv.recordParams(behavior.getParameterTypes(), Modifier.isStatic(getModifiers()));
jv.recordParamNames(ca, nvars);
jv.recordLocalVariables(ca, 0);
jv.recordType(getReturnType0());
jv.compileStmnt(src);
Bytecode b = jv.getBytecode();
int stack = b.getMaxStack();
int locals = b.getMaxLocals();
if (stack > ca.getMaxStack())
ca.setMaxStack(stack);
if (locals > ca.getMaxLocals())
ca.setMaxLocals(locals);
if (pos != -1) {
iterator.insertEx(pos, b.get());
} else {
pos = iterator.insertEx(b.get());
}
iterator.insert(b.getExceptionTable(), pos);
behavior.getMethodInfo().rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
return pos + b.length();
} catch (NotFoundException e) {
throw new CannotCompileException(e);
} catch (CompileError e) {
throw new CannotCompileException(e);
} catch (BadBytecode e) {
throw new CannotCompileException(e);
}
}
private int insertBeforeConstructor(int pos, String src) throws CannotCompileException {
CtClass cc = behavior.getDeclaringClass();
CodeAttribute ca = behavior.getMethodInfo().getCodeAttribute();
CodeIterator iterator = ca.iterator();
Bytecode b = new Bytecode(behavior.getMethodInfo().getConstPool(),
ca.getMaxStack(), ca.getMaxLocals());
b.setStackDepth(ca.getMaxStack());
Javac jv = new Javac(b, cc);
try {
jv.recordParams(behavior.getParameterTypes(), false);
jv.recordLocalVariables(ca, 0);
jv.compileStmnt(src);
ca.setMaxStack(b.getMaxStack());
ca.setMaxLocals(b.getMaxLocals());
iterator.skipConstructor();
if (pos != -1) {
iterator.insertEx(pos, b.get());
} else {
pos = iterator.insertEx(b.get());
}
iterator.insert(b.getExceptionTable(), pos);
behavior.getMethodInfo().rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
return pos + b.length();
}
catch (NotFoundException e) {
throw new CannotCompileException(e);
}
catch (CompileError e) {
throw new CannotCompileException(e);
}
catch (BadBytecode e) {
throw new CannotCompileException(e);
}
}
private void insertCatch(int from, String src, CtClass exceptionType, String exceptionName) throws CannotCompileException {
CtClass cc = behavior.getDeclaringClass();
ConstPool cp = behavior.getMethodInfo().getConstPool();
CodeAttribute ca = behavior.getMethodInfo().getCodeAttribute();
CodeIterator iterator = ca.iterator();
Bytecode b = new Bytecode(cp, ca.getMaxStack(), ca.getMaxLocals());
b.setStackDepth(1);
Javac jv = new Javac(b, cc);
try {
jv.recordParams(behavior.getParameterTypes(), Modifier.isStatic(getModifiers()));
jv.recordLocalVariables(ca, from);
int var = jv.recordVariable(exceptionType, exceptionName);
b.addAstore(var);
jv.compileStmnt(src);
int stack = b.getMaxStack();
int locals = b.getMaxLocals();
if (stack > ca.getMaxStack())
ca.setMaxStack(stack);
if (locals > ca.getMaxLocals())
ca.setMaxLocals(locals);
int len = iterator.getCodeLength();
int pos = iterator.append(b.get());
ca.getExceptionTable().add(from, len, len, cp.addClassInfo(exceptionType));
iterator.append(b.getExceptionTable(), pos);
behavior.getMethodInfo().rebuildStackMapIf6(cc.getClassPool(), cc.getClassFile2());
} catch (NotFoundException e) {
throw new CannotCompileException(e);
} catch (CompileError e) {
throw new CannotCompileException(e);
} catch (BadBytecode e) {
throw new CannotCompileException(e);
}
}
private CtClass getReturnType0() throws NotFoundException {
return Descriptor.getReturnType(behavior.getMethodInfo().getDescriptor(),
behavior.getDeclaringClass().getClassPool());
}
}
| apache-2.0 |
objectiser/camel | components/camel-olingo4/camel-olingo4-api/src/main/java/org/apache/camel/component/olingo4/api/impl/Olingo4AppImpl.java | 52209 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.olingo4.api.impl;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Consumer;
import org.apache.camel.component.olingo4.api.Olingo4App;
import org.apache.camel.component.olingo4.api.Olingo4ResponseHandler;
import org.apache.camel.component.olingo4.api.batch.Olingo4BatchChangeRequest;
import org.apache.camel.component.olingo4.api.batch.Olingo4BatchQueryRequest;
import org.apache.camel.component.olingo4.api.batch.Olingo4BatchRequest;
import org.apache.camel.component.olingo4.api.batch.Olingo4BatchResponse;
import org.apache.camel.component.olingo4.api.batch.Operation;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.ObjectHelper;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.HttpVersion;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.DecompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.config.MessageConstraints;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultHttpResponseParser;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.impl.io.SessionInputBufferImpl;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.message.BasicLineParser;
import org.apache.olingo.client.api.ODataBatchConstants;
import org.apache.olingo.client.api.ODataClient;
import org.apache.olingo.client.api.communication.request.ODataStreamer;
import org.apache.olingo.client.api.communication.request.batch.ODataBatchLineIterator;
import org.apache.olingo.client.api.domain.ClientEntity;
import org.apache.olingo.client.api.domain.ClientPrimitiveValue;
import org.apache.olingo.client.api.domain.ClientProperty;
import org.apache.olingo.client.api.serialization.ODataReader;
import org.apache.olingo.client.api.serialization.ODataWriter;
import org.apache.olingo.client.api.uri.SegmentType;
import org.apache.olingo.client.core.ODataClientFactory;
import org.apache.olingo.client.core.communication.request.batch.ODataBatchController;
import org.apache.olingo.client.core.communication.request.batch.ODataBatchLineIteratorImpl;
import org.apache.olingo.client.core.communication.request.batch.ODataBatchUtilities;
import org.apache.olingo.client.core.http.HttpMerge;
import org.apache.olingo.commons.api.Constants;
import org.apache.olingo.commons.api.edm.Edm;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeKind;
import org.apache.olingo.commons.api.edm.EdmReturnType;
import org.apache.olingo.commons.api.edm.constants.ODataServiceVersion;
import org.apache.olingo.commons.api.ex.ODataException;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.api.http.HttpHeader;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.UriInfoKind;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceFunction;
import org.apache.olingo.server.api.uri.UriResourceKind;
import org.apache.olingo.server.core.uri.parser.Parser;
import static org.apache.camel.component.olingo4.api.impl.Olingo4Helper.getContentTypeHeader;
/**
* Application API used by Olingo4 Component.
*/
public final class Olingo4AppImpl implements Olingo4App {
private static final String SEPARATOR = "/";
private static final String BOUNDARY_PREFIX = "batch_";
private static final String BOUNDARY_PARAMETER = "; boundary=";
private static final String BOUNDARY_DOUBLE_DASH = "--";
private static final String MULTIPART_MIME_TYPE = "multipart/";
private static final String CONTENT_ID_HEADER = "Content-ID";
private static final String CLIENT_ENTITY_FAKE_MARKER = "('X')";
private static final ContentType DEFAULT_CONTENT_TYPE = ContentType.create(ContentType.APPLICATION_JSON, ContentType.PARAMETER_CHARSET, Constants.UTF8);
private static final ContentType METADATA_CONTENT_TYPE = ContentType.create(ContentType.APPLICATION_XML, ContentType.PARAMETER_CHARSET, Constants.UTF8);
private static final ContentType TEXT_PLAIN_WITH_CS_UTF_8 = ContentType.create(ContentType.TEXT_PLAIN, ContentType.PARAMETER_CHARSET, Constants.UTF8);
private static final ContentType SERVICE_DOCUMENT_CONTENT_TYPE = ContentType.APPLICATION_JSON;
private static final ContentType BATCH_CONTENT_TYPE = ContentType.MULTIPART_MIXED;
/**
* Reference to CloseableHttpAsyncClient (default) or CloseableHttpClient
*/
private final Closeable client;
/**
* Reference to ODataClient reader and writer
*/
private final ODataClient odataClient = ODataClientFactory.getClient();
private final ODataReader odataReader = odataClient.getReader();
private final ODataWriter odataWriter = odataClient.getWriter();
private String serviceUri;
private ContentType contentType;
private Map<String, String> httpHeaders;
/**
* Create Olingo4 Application with default HTTP configuration.
*/
public Olingo4AppImpl(String serviceUri) {
// By default create HTTP asynchronous client
this(serviceUri, (HttpClientBuilder)null);
}
/**
* Create Olingo4 Application with custom HTTP Asynchronous client builder.
*
* @param serviceUri Service Application base URI.
* @param builder custom HTTP client builder.
*/
public Olingo4AppImpl(String serviceUri, HttpAsyncClientBuilder builder) {
setServiceUri(serviceUri);
CloseableHttpAsyncClient asyncClient;
if (builder == null) {
asyncClient = HttpAsyncClients.createDefault();
} else {
asyncClient = builder.build();
}
asyncClient.start();
this.client = asyncClient;
this.contentType = DEFAULT_CONTENT_TYPE;
}
/**
* Create Olingo4 Application with custom HTTP Synchronous client builder.
*
* @param serviceUri Service Application base URI.
* @param builder Custom HTTP Synchronous client builder.
*/
public Olingo4AppImpl(String serviceUri, HttpClientBuilder builder) {
setServiceUri(serviceUri);
if (builder == null) {
this.client = HttpClients.createDefault();
} else {
this.client = builder.build();
}
this.contentType = DEFAULT_CONTENT_TYPE;
}
@Override
public void setServiceUri(String serviceUri) {
if (serviceUri == null || serviceUri.isEmpty()) {
throw new IllegalArgumentException("serviceUri is not set");
}
this.serviceUri = serviceUri.endsWith(SEPARATOR) ? serviceUri.substring(0, serviceUri.length() - 1) : serviceUri;
}
@Override
public String getServiceUri() {
return serviceUri;
}
@Override
public Map<String, String> getHttpHeaders() {
return httpHeaders;
}
@Override
public void setHttpHeaders(Map<String, String> httpHeaders) {
this.httpHeaders = httpHeaders;
}
@Override
public String getContentType() {
return contentType.toContentTypeString();
}
@Override
public void setContentType(String contentType) {
this.contentType = ContentType.parse(contentType);
}
@Override
public void close() {
IOHelper.close(client);
}
@Override
public <T> void read(final Edm edm, final String resourcePath, final Map<String, String> queryParams, final Map<String, String> endpointHttpHeaders,
final Olingo4ResponseHandler<T> responseHandler) {
final String queryOptions = concatQueryParams(queryParams);
final UriInfo uriInfo = parseUri(edm, resourcePath, queryOptions, serviceUri);
execute(new HttpGet(createUri(resourcePath, queryOptions)), getResourceContentType(uriInfo), endpointHttpHeaders, new AbstractFutureCallback<T>(responseHandler) {
@Override
public void onCompleted(HttpResponse result) throws IOException {
readContent(uriInfo, result.getEntity() != null ? result.getEntity().getContent() : null, headersToMap(result.getAllHeaders()), responseHandler);
}
});
}
@Override
public void uread(final Edm edm, final String resourcePath, final Map<String, String> queryParams, final Map<String, String> endpointHttpHeaders,
final Olingo4ResponseHandler<InputStream> responseHandler) {
final String queryOptions = concatQueryParams(queryParams);
final UriInfo uriInfo = parseUri(edm, resourcePath, queryOptions, serviceUri);
execute(new HttpGet(createUri(resourcePath, queryOptions)), getResourceContentType(uriInfo), endpointHttpHeaders, new AbstractFutureCallback<InputStream>(responseHandler) {
@Override
public void onCompleted(HttpResponse result) throws IOException {
InputStream responseStream = result.getEntity() != null ? result.getEntity().getContent() : null;
if (responseStream != null && result.getEntity() instanceof DecompressingEntity) {
// In case of GZIP compression it's necessary to create
// InputStream from the source byte array
responseHandler.onResponse(new ByteArrayInputStream(IOUtils.toByteArray(responseStream)), headersToMap(result.getAllHeaders()));
} else {
responseHandler.onResponse(responseStream, headersToMap(result.getAllHeaders()));
}
}
});
}
@Override
public <T> void create(final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data,
final Olingo4ResponseHandler<T> responseHandler) {
final UriInfo uriInfo = parseUri(edm, resourcePath, null, serviceUri);
writeContent(edm, new HttpPost(createUri(resourcePath, null)), uriInfo, data, endpointHttpHeaders, responseHandler);
}
@Override
public <T> void update(final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data,
final Olingo4ResponseHandler<T> responseHandler) {
final UriInfo uriInfo = parseUri(edm, resourcePath, null, serviceUri);
augmentWithETag(edm, resourcePath, endpointHttpHeaders, new HttpPut(createUri(resourcePath, null)),
request -> writeContent(edm, (HttpPut)request, uriInfo, data, endpointHttpHeaders, responseHandler), responseHandler);
}
@Override
public void delete(final String resourcePath, final Map<String, String> endpointHttpHeaders, final Olingo4ResponseHandler<HttpStatusCode> responseHandler) {
HttpDelete deleteRequest = new HttpDelete(createUri(resourcePath));
Consumer<HttpRequestBase> deleteFunction = request -> {
execute(request, contentType, endpointHttpHeaders, new AbstractFutureCallback<HttpStatusCode>(responseHandler) {
@Override
public void onCompleted(HttpResponse result) {
final StatusLine statusLine = result.getStatusLine();
responseHandler.onResponse(HttpStatusCode.fromStatusCode(statusLine.getStatusCode()), headersToMap(result.getAllHeaders()));
}
});
};
augmentWithETag(null, resourcePath, endpointHttpHeaders, deleteRequest, deleteFunction, responseHandler);
}
@Override
public <T> void patch(final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data,
final Olingo4ResponseHandler<T> responseHandler) {
final UriInfo uriInfo = parseUri(edm, resourcePath, null, serviceUri);
augmentWithETag(edm, resourcePath, endpointHttpHeaders, new HttpPatch(createUri(resourcePath, null)),
request -> writeContent(edm, (HttpPatch)request, uriInfo, data, endpointHttpHeaders, responseHandler), responseHandler);
}
@Override
public <T> void merge(final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data,
final Olingo4ResponseHandler<T> responseHandler) {
final UriInfo uriInfo = parseUri(edm, resourcePath, null, serviceUri);
augmentWithETag(edm, resourcePath, endpointHttpHeaders, new HttpMerge(createUri(resourcePath, null)),
request -> writeContent(edm, (HttpMerge)request, uriInfo, data, endpointHttpHeaders, responseHandler), responseHandler);
}
@Override
public void batch(final Edm edm, final Map<String, String> endpointHttpHeaders, final Object data, final Olingo4ResponseHandler<List<Olingo4BatchResponse>> responseHandler) {
final UriInfo uriInfo = parseUri(edm, SegmentType.BATCH.getValue(), null, serviceUri);
writeContent(edm, new HttpPost(createUri(SegmentType.BATCH.getValue(), null)), uriInfo, data, endpointHttpHeaders, responseHandler);
}
@Override
public <T> void action(final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final Object data,
final Olingo4ResponseHandler<T> responseHandler) {
final UriInfo uriInfo = parseUri(edm, resourcePath, null, serviceUri);
writeContent(edm, new HttpPost(createUri(resourcePath, null)), uriInfo, data, endpointHttpHeaders, responseHandler);
}
private ContentType getResourceContentType(UriInfo uriInfo) {
ContentType resourceContentType;
switch (uriInfo.getKind()) {
case service:
// service document
resourceContentType = SERVICE_DOCUMENT_CONTENT_TYPE;
break;
case metadata:
// metadata
resourceContentType = METADATA_CONTENT_TYPE;
break;
case resource:
List<UriResource> listResource = uriInfo.getUriResourceParts();
UriResourceKind lastResourceKind = listResource.get(listResource.size() - 1).getKind();
// is it a $value or $count URI??
if (lastResourceKind == UriResourceKind.count || lastResourceKind == UriResourceKind.value) {
resourceContentType = TEXT_PLAIN_WITH_CS_UTF_8;
} else {
resourceContentType = contentType;
}
break;
default:
resourceContentType = contentType;
}
return resourceContentType;
}
/**
* On occasion, some resources are protected with Optimistic Concurrency via
* the use of eTags. This will first conduct a read on the given entity
* resource, find its eTag then perform the given delegate request function,
* augmenting the request with the eTag, if appropriate. Since read
* operations may be asynchronous, it is necessary to chain together the
* methods via the use of a {@link Consumer} function. Only when the
* response from the read returns will this delegate function be executed.
*
* @param edm the Edm object to be interrogated
* @param resourcePath the resource path of the entity to be operated on
* @param endpointHttpHeaders the headers provided from the endpoint which
* may be required for the read operation
* @param httpRequest the request to be updated, if appropriate, with the
* eTag and provided to the delegate request function
* @param delegateRequestFn the function to be invoked in response to the
* read operation
* @param delegateResponseHandler the response handler to respond if any
* errors occur during the read operation
*/
private <T> void augmentWithETag(final Edm edm, final String resourcePath, final Map<String, String> endpointHttpHeaders, final HttpRequestBase httpRequest,
final Consumer<HttpRequestBase> delegateRequestFn, final Olingo4ResponseHandler<T> delegateResponseHandler) {
if (edm == null) {
// Can be the case if calling a delete then need to do a metadata
// call first
final Olingo4ResponseHandler<Edm> edmResponseHandler = new Olingo4ResponseHandler<Edm>() {
@Override
public void onResponse(Edm response, Map<String, String> responseHeaders) {
//
// Call this method again with an intact edm object
//
augmentWithETag(response, resourcePath, endpointHttpHeaders, httpRequest, delegateRequestFn, delegateResponseHandler);
}
@Override
public void onException(Exception ex) {
delegateResponseHandler.onException(ex);
}
@Override
public void onCanceled() {
delegateResponseHandler.onCanceled();
}
};
//
// Reads the metadata to establish an Edm object
// then the response handler invokes this method again with the new
// edm object
//
read(null, Constants.METADATA, null, null, edmResponseHandler);
} else {
//
// The handler that responds to the read operation and supplies an
// ETag if necessary
// and invokes the delegate request function
//
Olingo4ResponseHandler<T> eTagReadHandler = new Olingo4ResponseHandler<T>() {
@Override
public void onResponse(T response, Map<String, String> responseHeaders) {
if (response instanceof ClientEntity) {
ClientEntity e = (ClientEntity)response;
Optional.ofNullable(e.getETag()).ifPresent(v -> httpRequest.addHeader("If-Match", v));
}
// Invoke the delegate request function providing the
// modified request
delegateRequestFn.accept(httpRequest);
}
@Override
public void onException(Exception ex) {
delegateResponseHandler.onException(ex);
}
@Override
public void onCanceled() {
delegateResponseHandler.onCanceled();
}
};
read(edm, resourcePath, null, endpointHttpHeaders, eTagReadHandler);
}
}
private <T> void readContent(UriInfo uriInfo, InputStream content, Map<String, String> endpointHttpHeaders, Olingo4ResponseHandler<T> responseHandler) {
try {
responseHandler.onResponse(this.<T> readContent(uriInfo, content), endpointHttpHeaders);
} catch (Exception e) {
responseHandler.onException(e);
} catch (Error e) {
responseHandler.onException(new ODataException("Runtime Error Occurred", e));
}
}
@SuppressWarnings("unchecked")
private <T> T readContent(UriInfo uriInfo, InputStream content) throws ODataException {
T response = null;
switch (uriInfo.getKind()) {
case service:
// service document
response = (T)odataReader.readServiceDocument(content, SERVICE_DOCUMENT_CONTENT_TYPE);
break;
case metadata:
// $metadata
response = (T)odataReader.readMetadata(content);
break;
case resource:
// any resource entity
List<UriResource> listResource = uriInfo.getUriResourceParts();
UriResourceKind lastResourceKind = listResource.get(listResource.size() - 1).getKind();
switch (lastResourceKind) {
case entitySet:
UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet)listResource.get(listResource.size() - 1);
List<UriParameter> keyPredicates = uriResourceEntitySet.getKeyPredicates();
// Check result type: single Entity or EntitySet based
// on key predicate detection
if (keyPredicates.size() == 1) {
response = (T)odataReader.readEntity(content, getResourceContentType(uriInfo));
} else {
response = (T)odataReader.readEntitySet(content, getResourceContentType(uriInfo));
}
break;
case count:
String stringCount = null;
try {
stringCount = IOUtils.toString(content, Consts.UTF_8);
response = (T)Long.valueOf(stringCount);
} catch (IOException e) {
throw new ODataException("Error during $count value deserialization", e);
} catch (NumberFormatException e) {
throw new ODataException("Error during $count value conversion: " + stringCount, e);
}
break;
case value:
try {
ClientPrimitiveValue value = odataClient.getObjectFactory().newPrimitiveValueBuilder().setType(EdmPrimitiveTypeKind.String)
.setValue(IOUtils.toString(content, Consts.UTF_8)).build();
response = (T)value;
} catch (IOException e) {
throw new ODataException("Error during $value deserialization", e);
}
break;
case primitiveProperty:
case complexProperty:
ClientProperty property = odataReader.readProperty(content, getResourceContentType(uriInfo));
if (property.hasPrimitiveValue()) {
response = (T)property.getPrimitiveValue();
} else if (property.hasComplexValue()) {
response = (T)property.getComplexValue();
} else if (property.hasCollectionValue()) {
response = (T)property.getCollectionValue();
} else {
throw new ODataException("Unsupported property: " + property.getName());
}
break;
case function:
UriResourceFunction uriResourceFunction = (UriResourceFunction)listResource.get(listResource.size() - 1);
EdmReturnType functionReturnType = uriResourceFunction.getFunction().getReturnType();
switch (functionReturnType.getType().getKind()) {
case ENTITY:
if (functionReturnType.isCollection()) {
response = (T)odataReader.readEntitySet(content, getResourceContentType(uriInfo));
} else {
response = (T)odataReader.readEntity(content, getResourceContentType(uriInfo));
}
break;
case PRIMITIVE:
case COMPLEX:
ClientProperty functionProperty = odataReader.readProperty(content, getResourceContentType(uriInfo));
if (functionProperty.hasPrimitiveValue()) {
response = (T)functionProperty.getPrimitiveValue();
} else if (functionProperty.hasComplexValue()) {
response = (T)functionProperty.getComplexValue();
} else if (functionProperty.hasCollectionValue()) {
response = (T)functionProperty.getCollectionValue();
} else {
throw new ODataException("Unsupported property: " + functionProperty.getName());
}
break;
default:
throw new ODataException("Unsupported function return type " + uriInfo.getKind().name());
}
break;
default:
throw new ODataException("Unsupported resource type: " + lastResourceKind.name());
}
break;
default:
throw new ODataException("Unsupported resource type " + uriInfo.getKind().name());
}
return response;
}
private <T> void writeContent(final Edm edm, HttpEntityEnclosingRequestBase httpEntityRequest, final UriInfo uriInfo, final Object content,
final Map<String, String> endpointHttpHeaders, final Olingo4ResponseHandler<T> responseHandler) {
try {
httpEntityRequest.setEntity(writeContent(edm, uriInfo, content));
final Header requestContentTypeHeader = httpEntityRequest.getEntity().getContentType();
final ContentType requestContentType = requestContentTypeHeader != null ? ContentType.parse(requestContentTypeHeader.getValue()) : contentType;
execute(httpEntityRequest, requestContentType, endpointHttpHeaders, new AbstractFutureCallback<T>(responseHandler) {
@SuppressWarnings("unchecked")
@Override
public void onCompleted(HttpResponse result) throws IOException, ODataException {
// if a entity is created (via POST request) the response
// body contains the new created entity
HttpStatusCode statusCode = HttpStatusCode.fromStatusCode(result.getStatusLine().getStatusCode());
// look for no content, or no response body!!!
final boolean noEntity = result.getEntity() == null || result.getEntity().getContentLength() == 0;
if (statusCode == HttpStatusCode.NO_CONTENT || noEntity) {
responseHandler.onResponse((T)HttpStatusCode.fromStatusCode(result.getStatusLine().getStatusCode()), headersToMap(result.getAllHeaders()));
} else {
if (uriInfo.getKind() == UriInfoKind.resource) {
List<UriResource> listResource = uriInfo.getUriResourceParts();
UriResourceKind lastResourceKind = listResource.get(listResource.size() - 1).getKind();
switch (lastResourceKind) {
case action:
case entitySet:
ClientEntity entity = odataReader.readEntity(result.getEntity().getContent(), ContentType.parse(result.getEntity().getContentType().getValue()));
responseHandler.onResponse((T)entity, headersToMap(result.getAllHeaders()));
break;
default:
break;
}
} else if (uriInfo.getKind() == UriInfoKind.batch) {
List<Olingo4BatchResponse> batchResponse = parseBatchResponse(edm, result, (List<Olingo4BatchRequest>)content);
responseHandler.onResponse((T)batchResponse, headersToMap(result.getAllHeaders()));
} else {
throw new ODataException("Unsupported resource type: " + uriInfo.getKind().name());
}
}
}
});
} catch (Exception e) {
responseHandler.onException(e);
} catch (Error e) {
responseHandler.onException(new ODataException("Runtime Error Occurred", e));
}
}
private AbstractHttpEntity writeContent(final Edm edm, final UriInfo uriInfo, final Object content) throws ODataException {
AbstractHttpEntity httpEntity;
if (uriInfo.getKind() == UriInfoKind.resource) {
// any resource entity
List<UriResource> listResource = uriInfo.getUriResourceParts();
UriResourceKind lastResourceKind = listResource.get(listResource.size() - 1).getKind();
switch (lastResourceKind) {
case action:
if (content == null) { // actions may have no input
httpEntity = new ByteArrayEntity(new byte[0]);
} else {
httpEntity = writeContent(uriInfo, content);
}
break;
case entitySet:
httpEntity = writeContent(uriInfo, content);
break;
default:
throw new ODataException("Unsupported resource type: " + lastResourceKind);
}
} else if (uriInfo.getKind() == UriInfoKind.batch) {
final String boundary = BOUNDARY_PREFIX + UUID.randomUUID();
final String contentHeader = BATCH_CONTENT_TYPE + BOUNDARY_PARAMETER + boundary;
final List<Olingo4BatchRequest> batchParts = (List<Olingo4BatchRequest>)content;
final InputStream requestStream = serializeBatchRequest(edm, batchParts, BOUNDARY_DOUBLE_DASH + boundary);
httpEntity = writeContent(requestStream);
httpEntity.setContentType(contentHeader);
} else {
throw new ODataException("Unsupported resource type: " + uriInfo.getKind().name());
}
return httpEntity;
}
private AbstractHttpEntity writeContent(UriInfo uriInfo, Object content) throws ODataException {
AbstractHttpEntity httpEntity;
if (content instanceof ClientEntity) {
final InputStream requestStream = odataWriter.writeEntity((ClientEntity)content, getResourceContentType(uriInfo));
httpEntity = writeContent(requestStream);
} else if (content instanceof String) {
httpEntity = new StringEntity((String)content, org.apache.http.entity.ContentType.APPLICATION_JSON);
} else {
throw new ODataException("Unsupported content type: " + content);
}
httpEntity.setChunked(false);
return httpEntity;
}
private AbstractHttpEntity writeContent(InputStream inputStream) throws ODataException {
AbstractHttpEntity httpEntity;
try {
httpEntity = new ByteArrayEntity(IOUtils.toByteArray(inputStream));
} catch (IOException e) {
throw new ODataException("Error during converting input stream to byte array", e);
}
httpEntity.setChunked(false);
return httpEntity;
}
private InputStream serializeBatchRequest(final Edm edm, final List<Olingo4BatchRequest> batchParts, String boundary) throws ODataException {
final ByteArrayOutputStream batchRequestHeaderOutputStream = new ByteArrayOutputStream();
try {
batchRequestHeaderOutputStream.write(boundary.getBytes(Constants.UTF8));
batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
for (Olingo4BatchRequest batchPart : batchParts) {
writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_HTTP.toContentTypeString());
writeHttpHeader(batchRequestHeaderOutputStream, ODataBatchConstants.ITEM_TRANSFER_ENCODING_LINE, null);
if (batchPart instanceof Olingo4BatchQueryRequest) {
final Olingo4BatchQueryRequest batchQueryPart = (Olingo4BatchQueryRequest)batchPart;
final String batchQueryUri = createUri(StringUtils.isBlank(batchQueryPart.getResourceUri()) ? serviceUri : batchQueryPart.getResourceUri(),
batchQueryPart.getResourcePath(), concatQueryParams(batchQueryPart.getQueryParams()));
final UriInfo uriInfo = parseUri(edm, batchQueryPart.getResourcePath(), concatQueryParams(batchQueryPart.getQueryParams()), serviceUri);
batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
batchRequestHeaderOutputStream.write((HttpGet.METHOD_NAME + " " + batchQueryUri + " " + HttpVersion.HTTP_1_1).getBytes(Constants.UTF8));
batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
final ContentType acceptType = getResourceContentType(uriInfo);
final String acceptCharset = acceptType.getParameter(ContentType.PARAMETER_CHARSET);
writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.ACCEPT, contentType.getType().toLowerCase() + "/" + contentType.getSubtype().toLowerCase());
if (null != acceptCharset) {
writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.ACCEPT_CHARSET, acceptCharset.toLowerCase());
}
batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
batchRequestHeaderOutputStream.write(boundary.getBytes(Constants.UTF8));
batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
} else if (batchPart instanceof Olingo4BatchChangeRequest) {
final Olingo4BatchChangeRequest batchChangePart = (Olingo4BatchChangeRequest)batchPart;
final String batchChangeUri = createUri(StringUtils.isBlank(batchChangePart.getResourceUri()) ? serviceUri : batchChangePart.getResourceUri(),
batchChangePart.getResourcePath(), null);
final UriInfo uriInfo = parseUri(edm, batchChangePart.getResourcePath(), null, serviceUri);
if (batchChangePart.getOperation() != Operation.DELETE) {
writeHttpHeader(batchRequestHeaderOutputStream, CONTENT_ID_HEADER, batchChangePart.getContentId());
}
batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
batchRequestHeaderOutputStream
.write((batchChangePart.getOperation().getHttpMethod() + " " + batchChangeUri + " " + HttpVersion.HTTP_1_1).getBytes(Constants.UTF8));
batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
writeHttpHeader(batchRequestHeaderOutputStream, HttpHeader.ODATA_VERSION, ODataServiceVersion.V40.toString());
final ContentType acceptType = getResourceContentType(uriInfo);
final String acceptCharset = acceptType.getParameter(ContentType.PARAMETER_CHARSET);
writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.ACCEPT, contentType.getType().toLowerCase() + "/" + contentType.getSubtype().toLowerCase());
if (null != acceptCharset) {
writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.ACCEPT_CHARSET, acceptCharset.toLowerCase());
}
writeHttpHeader(batchRequestHeaderOutputStream, HttpHeaders.CONTENT_TYPE, acceptType.toContentTypeString());
if (batchChangePart.getOperation() != Operation.DELETE) {
batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
AbstractHttpEntity httpEnity = writeContent(edm, uriInfo, batchChangePart.getBody());
batchRequestHeaderOutputStream.write(IOUtils.toByteArray(httpEnity.getContent()));
batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
} else {
batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
}
batchRequestHeaderOutputStream.write(boundary.getBytes(Constants.UTF8));
batchRequestHeaderOutputStream.write(ODataStreamer.CRLF);
} else {
throw new ODataException("Unsupported batch part request object type: " + batchPart);
}
}
} catch (Exception e) {
throw new ODataException("Error during batch request serialization", e);
}
return new ByteArrayInputStream(batchRequestHeaderOutputStream.toByteArray());
}
private void writeHttpHeader(ByteArrayOutputStream headerOutputStream, String headerName, String headerValue) throws IOException {
headerOutputStream.write(createHttpHeader(headerName, headerValue).getBytes(Constants.UTF8));
headerOutputStream.write(ODataStreamer.CRLF);
}
private String createHttpHeader(String headerName, String headerValue) {
return headerName + (StringUtils.isBlank(headerValue) ? "" : (": " + headerValue));
}
private List<Olingo4BatchResponse> parseBatchResponse(final Edm edm, HttpResponse response, List<Olingo4BatchRequest> batchRequest) throws ODataException {
List<Olingo4BatchResponse> batchResponse = new <Olingo4BatchResponse> ArrayList();
try {
final Header[] contentHeaders = response.getHeaders(HttpHeader.CONTENT_TYPE);
final ODataBatchLineIterator batchLineIterator = new ODataBatchLineIteratorImpl(IOUtils.lineIterator(response.getEntity().getContent(), Constants.UTF8));
final String batchBoundary = ODataBatchUtilities.getBoundaryFromHeader(getHeadersCollection(contentHeaders));
final ODataBatchController batchController = new ODataBatchController(batchLineIterator, batchBoundary);
batchController.getBatchLineIterator().next();
int batchRequestIndex = 0;
while (batchController.getBatchLineIterator().hasNext()) {
OutputStream os = new ByteArrayOutputStream();
ODataBatchUtilities.readBatchPart(batchController, os, false);
Object content = null;
final Olingo4BatchRequest batchPartRequest = batchRequest.get(batchRequestIndex);
final HttpResponse batchPartHttpResponse = constructBatchPartHttpResponse(new ByteArrayInputStream(((ByteArrayOutputStream)os).toByteArray()));
final StatusLine batchPartStatusLine = batchPartHttpResponse.getStatusLine();
final int batchPartLineStatusCode = batchPartStatusLine.getStatusCode();
Map<String, String> batchPartHeaders = getHeadersValueMap(batchPartHttpResponse.getAllHeaders());
if (batchPartRequest instanceof Olingo4BatchQueryRequest) {
Olingo4BatchQueryRequest batchPartQueryRequest = (Olingo4BatchQueryRequest)batchPartRequest;
final UriInfo uriInfo = parseUri(edm, batchPartQueryRequest.getResourcePath(), null, serviceUri);
if (HttpStatusCode.BAD_REQUEST.getStatusCode() <= batchPartLineStatusCode && batchPartLineStatusCode <= AbstractFutureCallback.NETWORK_CONNECT_TIMEOUT_ERROR) {
final ContentType responseContentType = getContentTypeHeader(batchPartHttpResponse);
content = odataReader.readError(batchPartHttpResponse.getEntity().getContent(), responseContentType);
} else if (batchPartLineStatusCode == HttpStatusCode.NO_CONTENT.getStatusCode()) {
// nothing to do if NO_CONTENT returning
} else {
content = readContent(uriInfo, batchPartHttpResponse.getEntity().getContent());
}
Olingo4BatchResponse batchPartResponse = new Olingo4BatchResponse(batchPartStatusLine.getStatusCode(), batchPartStatusLine.getReasonPhrase(), null,
batchPartHeaders, content);
batchResponse.add(batchPartResponse);
} else if (batchPartRequest instanceof Olingo4BatchChangeRequest) {
Olingo4BatchChangeRequest batchPartChangeRequest = (Olingo4BatchChangeRequest)batchPartRequest;
if (batchPartLineStatusCode != HttpStatusCode.NO_CONTENT.getStatusCode()) {
if (HttpStatusCode.BAD_REQUEST.getStatusCode() <= batchPartLineStatusCode
&& batchPartLineStatusCode <= AbstractFutureCallback.NETWORK_CONNECT_TIMEOUT_ERROR) {
final ContentType responseContentType = ContentType.parse(batchPartHttpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
content = odataReader.readError(response.getEntity().getContent(), responseContentType);
} else {
final UriInfo uriInfo = parseUri(edm, batchPartChangeRequest.getResourcePath()
+ (batchPartChangeRequest.getOperation() == Operation.CREATE ? CLIENT_ENTITY_FAKE_MARKER : ""),
null, serviceUri);
content = readContent(uriInfo, batchPartHttpResponse.getEntity().getContent());
}
}
Olingo4BatchResponse batchPartResponse = new Olingo4BatchResponse(batchPartStatusLine.getStatusCode(), batchPartStatusLine.getReasonPhrase(),
batchPartChangeRequest.getContentId(), batchPartHeaders, content);
batchResponse.add(batchPartResponse);
} else {
throw new ODataException("Unsupported batch part request object type: " + batchPartRequest);
}
batchRequestIndex++;
}
} catch (IOException | HttpException e) {
throw new ODataException(e);
}
return batchResponse;
}
private HttpResponse constructBatchPartHttpResponse(InputStream batchPartStream) throws IOException, HttpException {
final LineIterator lines = IOUtils.lineIterator(batchPartStream, Constants.UTF8);
final ByteArrayOutputStream headerOutputStream = new ByteArrayOutputStream();
final ByteArrayOutputStream bodyOutputStream = new ByteArrayOutputStream();
boolean startBatchPartHeader = false;
boolean startBatchPartBody = false;
// Iterate through lines in the batch part
while (lines.hasNext()) {
String line = lines.nextLine().trim();
// Ignore all lines below HTTP/1.1 line
if (line.startsWith(HttpVersion.HTTP)) {
// This is the first header line
startBatchPartHeader = true;
}
// Body starts with empty string after header lines
if (startBatchPartHeader && StringUtils.isBlank(line)) {
startBatchPartHeader = false;
startBatchPartBody = true;
}
if (startBatchPartHeader) {
// Write header to the output stream
headerOutputStream.write(line.getBytes(Constants.UTF8));
headerOutputStream.write(ODataStreamer.CRLF);
} else if (startBatchPartBody && StringUtils.isNotBlank(line)) {
// Write body to the output stream
bodyOutputStream.write(line.getBytes(Constants.UTF8));
bodyOutputStream.write(ODataStreamer.CRLF);
}
}
// Prepare for parsing headers in to the HttpResponse object
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
SessionInputBufferImpl sessionInputBuffer = new SessionInputBufferImpl(metrics, 2048);
HttpResponseFactory responseFactory = new DefaultHttpResponseFactory();
sessionInputBuffer.bind(new ByteArrayInputStream(headerOutputStream.toByteArray()));
DefaultHttpResponseParser responseParser = new DefaultHttpResponseParser(sessionInputBuffer, new BasicLineParser(), responseFactory, MessageConstraints.DEFAULT);
// Parse HTTP response and headers
HttpResponse response = responseParser.parse();
// Set body inside entity
response.setEntity(new ByteArrayEntity(bodyOutputStream.toByteArray()));
return response;
}
private Collection<String> getHeadersCollection(Header[] headers) {
Collection<String> headersCollection = new ArrayList();
for (Header header : Arrays.asList(headers)) {
headersCollection.add(header.getValue());
}
return headersCollection;
}
private Map<String, String> getHeadersValueMap(Header[] headers) {
Map<String, String> headersValueMap = new HashMap();
for (Header header : Arrays.asList(headers)) {
headersValueMap.put(header.getName(), header.getValue());
}
return headersValueMap;
}
private String createUri(String resourcePath) {
return createUri(serviceUri, resourcePath, null);
}
private String createUri(String resourcePath, String queryOptions) {
return createUri(serviceUri, resourcePath, queryOptions);
}
private String createUri(String resourceUri, String resourcePath, String queryOptions) {
final StringBuilder absolutUri = new StringBuilder(resourceUri).append(SEPARATOR).append(resourcePath);
if (queryOptions != null && !queryOptions.isEmpty()) {
absolutUri.append("?" + queryOptions);
}
return absolutUri.toString();
}
private String concatQueryParams(final Map<String, String> queryParams) {
final StringBuilder concatQuery = new StringBuilder("");
if (queryParams != null && !queryParams.isEmpty()) {
int nParams = queryParams.size();
int index = 0;
for (Map.Entry<String, String> entry : queryParams.entrySet()) {
concatQuery.append(entry.getKey()).append('=').append(entry.getValue());
if (++index < nParams) {
concatQuery.append('&');
}
}
}
return concatQuery.toString().replaceAll(" *", "%20");
}
private static UriInfo parseUri(Edm edm, String resourcePath, String queryOptions, String serviceUri) {
Parser parser = new Parser(edm, OData.newInstance());
UriInfo result;
try {
result = parser.parseUri(resourcePath, queryOptions, null, serviceUri);
} catch (Exception e) {
throw new IllegalArgumentException("parseUri (" + resourcePath + "," + queryOptions + "): " + e.getMessage(), e);
}
return result;
}
private static Map<String, String> headersToMap(final Header[] headers) {
final Map<String, String> responseHeaders = new HashMap<>();
for (Header header : headers) {
responseHeaders.put(header.getName(), header.getValue());
}
return responseHeaders;
}
public void execute(HttpUriRequest httpUriRequest, ContentType contentType, final Map<String, String> endpointHttpHeaders, FutureCallback<HttpResponse> callback) {
// add accept header when its not a form or multipart
if (!ContentType.APPLICATION_FORM_URLENCODED.equals(contentType) && !contentType.toContentTypeString().startsWith(MULTIPART_MIME_TYPE)) {
// otherwise accept what is being sent
httpUriRequest.addHeader(HttpHeaders.ACCEPT, contentType.getType().toLowerCase() + "/" + contentType.getSubtype().toLowerCase());
final String acceptCharset = contentType.getParameter(ContentType.PARAMETER_CHARSET);
if (null != acceptCharset) {
httpUriRequest.addHeader(HttpHeaders.ACCEPT_CHARSET, acceptCharset.toLowerCase());
}
}
// is something being sent?
if (httpUriRequest instanceof HttpEntityEnclosingRequestBase && httpUriRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
httpUriRequest.addHeader(HttpHeaders.CONTENT_TYPE, contentType.toString());
}
// set user specified custom headers
if (ObjectHelper.isNotEmpty(httpHeaders)) {
for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
httpUriRequest.setHeader(entry.getKey(), entry.getValue());
}
}
// set user specified endpoint headers
if (ObjectHelper.isNotEmpty(endpointHttpHeaders)) {
for (Map.Entry<String, String> entry : endpointHttpHeaders.entrySet()) {
httpUriRequest.setHeader(entry.getKey(), entry.getValue());
}
}
// add 'Accept-Charset' header to avoid BOM marker presents inside
// response stream
if (!httpUriRequest.containsHeader(HttpHeaders.ACCEPT_CHARSET)) {
httpUriRequest.addHeader(HttpHeaders.ACCEPT_CHARSET, Constants.UTF8.toLowerCase());
}
// add client protocol version if not specified
if (!httpUriRequest.containsHeader(HttpHeader.ODATA_VERSION)) {
httpUriRequest.addHeader(HttpHeader.ODATA_VERSION, ODataServiceVersion.V40.toString());
}
if (!httpUriRequest.containsHeader(HttpHeader.ODATA_MAX_VERSION)) {
httpUriRequest.addHeader(HttpHeader.ODATA_MAX_VERSION, ODataServiceVersion.V40.toString());
}
// execute request
if (client instanceof CloseableHttpAsyncClient) {
((CloseableHttpAsyncClient)client).execute(httpUriRequest, callback);
} else {
// invoke the callback methods explicitly after executing the
// request synchronously
try {
CloseableHttpResponse result = ((CloseableHttpClient)client).execute(httpUriRequest);
callback.completed(result);
} catch (IOException e) {
callback.failed(e);
}
}
}
}
| apache-2.0 |
apache/commons-imaging | src/test/java/org/apache/commons/imaging/formats/tiff/taginfos/TagInfoSBytesTest.java | 1586 | /*
* 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.imaging.formats.tiff.taginfos;
import static org.junit.jupiter.api.Assertions.assertSame;
import java.nio.ByteOrder;
import org.apache.commons.imaging.formats.tiff.constants.TiffDirectoryType;
import org.junit.jupiter.api.Test;
public class TagInfoSBytesTest{
@Test
public void testCreatesTagInfoSBytesAndCallsEncodeValue() {
final TiffDirectoryType tiffDirectoryType = TiffDirectoryType.TIFF_DIRECTORY_IFD3;
final TagInfoSBytes tagInfoSBytes = new TagInfoSBytes("", (-198), 10, tiffDirectoryType);
final ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN;
final byte[] byteArray = new byte[2];
final byte[] byteArrayTwo = tagInfoSBytes.encodeValue(byteOrder, byteArray);
assertSame(byteArrayTwo, byteArray);
}
} | apache-2.0 |
asanka88/apache-synapse | modules/transports/core/nhttp/src/main/java/org/apache/synapse/transport/nhttp/debug/ClientConnectionDebug.java | 6147 | /*
* 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.synapse.transport.nhttp.debug;
import org.apache.http.HttpRequest;
import org.apache.http.RequestLine;
import org.apache.http.nio.NHttpClientConnection;
import org.apache.synapse.transport.nhttp.Axis2HttpRequest;
import org.apache.synapse.transport.nhttp.ClientHandler;
import java.io.IOException;
/**
* A connection debug object would be accumulated during processing, but only made use of if the connection
* encounters issues during processing.
*/
public class ClientConnectionDebug extends AbstractConnectionDebug {
private long connectionCreationTime;
private long lastRequestStartTime;
private String lastRequestEPR;
private String lastRequestProtocol;
private String lastRequestHTTPMethod;
private StringBuffer previousRequestAttempts;
private long requestCompletionTime;
private long responseStartTime;
private long responseCompletionTime = -1;
private String responseLine;
private ServerConnectionDebug serverConnectionDebug;
public ClientConnectionDebug(ServerConnectionDebug serverConnectionDebug) {
super();
this.serverConnectionDebug = serverConnectionDebug;
}
public void recordRequestStartTime(NHttpClientConnection conn, Axis2HttpRequest axis2Req) {
if (conn != null) {
this.connectionCreationTime = (Long) conn.getContext().getAttribute(
ClientHandler.CONNECTION_CREATION_TIME);
try {
HttpRequest request = axis2Req.getRequest();
RequestLine requestLine = request.getRequestLine();
this.lastRequestProtocol = requestLine.getProtocolVersion().toString();
this.lastRequestHTTPMethod = requestLine.getMethod();
this.headers = request.getAllHeaders();
} catch (IOException ignore) {}
}
if (this.lastRequestStartTime != 0) {
if (previousRequestAttempts == null) {
previousRequestAttempts = new StringBuffer();
} else {
previousRequestAttempts.append(fieldSeparator);
}
previousRequestAttempts.append("Attempt-Info").append(keyValueSeparator).append("{");
previousRequestAttempts.append("Req-Start-Time").append(keyValueSeparator)
.append(format(this.lastRequestStartTime));
previousRequestAttempts.append(fieldSeparator);
previousRequestAttempts.append("Req-URL").append(keyValueSeparator)
.append(this.lastRequestEPR).append("}");
}
this.lastRequestStartTime = System.currentTimeMillis();
this.lastRequestEPR = axis2Req.getEpr().toString();
}
public void recordResponseCompletionTime() {
this.responseCompletionTime = System.currentTimeMillis();
}
public void recordRequestCompletionTime() {
this.requestCompletionTime = System.currentTimeMillis();
}
public void recordResponseStartTime(String responseLine) {
this.responseStartTime = System.currentTimeMillis();
this.responseLine = responseLine;
}
public long getLastRequestStartTime() {
return lastRequestStartTime;
}
public long getResponseCompletionTime() {
return responseCompletionTime;
}
public long getResponseStartTime() {
return responseStartTime;
}
public String dump() {
StringBuffer sb = new StringBuffer(25);
sb.append("E2S-Req-Start").append(keyValueSeparator).append(format(lastRequestStartTime));
sb.append(fieldSeparator);
sb.append("E2S-Req-End").append(keyValueSeparator).append(format(requestCompletionTime));
sb.append(fieldSeparator);
sb.append("E2S-Req-ConnCreateTime").append(keyValueSeparator)
.append(format(connectionCreationTime));
sb.append(statementSeparator);
sb.append("E2S-Req-URL").append(keyValueSeparator).append(lastRequestEPR);
sb.append(fieldSeparator);
sb.append("E2S-Req-Protocol").append(keyValueSeparator).append(lastRequestProtocol);
sb.append(fieldSeparator);
sb.append("E2S-Req-Method").append(keyValueSeparator).append(lastRequestHTTPMethod);
sb.append(statementSeparator);
if (previousRequestAttempts != null) {
sb.append("E2S-Previous-Attempts").append(keyValueSeparator)
.append(previousRequestAttempts);
sb.append(statementSeparator);
}
sb.append("S2E-Resp-Start").append(keyValueSeparator).append(format(responseStartTime));
sb.append(fieldSeparator);
sb.append("S2E-Resp-End").append(keyValueSeparator).append(responseCompletionTime != -1 ?
format(responseCompletionTime) : "NOT-COMPLETED");
sb.append(statementSeparator);
sb.append("S2E-Resp-Status").append(keyValueSeparator).append(responseLine);
if (!printNoHeaders) {
sb.append(fieldSeparator);
sb.append("S2E-Resp-Info").append(keyValueSeparator).append("{")
.append(headersToString()).append("}");
}
sb.append(statementSeparator);
return sb.toString();
}
public ServerConnectionDebug getServerConnectionDebug() {
return serverConnectionDebug;
}
} | apache-2.0 |
christian-posta/spring-boot | spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/HealthIndicatorAutoConfigurationTests.java | 17546 | /*
* Copyright 2012-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.springframework.boot.actuate.autoconfigure;
import java.util.Map;
import javax.sql.DataSource;
import org.junit.After;
import org.junit.Test;
import org.springframework.boot.actuate.health.ApplicationHealthIndicator;
import org.springframework.boot.actuate.health.DataSourceHealthIndicator;
import org.springframework.boot.actuate.health.DiskSpaceHealthIndicator;
import org.springframework.boot.actuate.health.ElasticsearchHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.actuate.health.JmsHealthIndicator;
import org.springframework.boot.actuate.health.MailHealthIndicator;
import org.springframework.boot.actuate.health.MongoHealthIndicator;
import org.springframework.boot.actuate.health.RabbitHealthIndicator;
import org.springframework.boot.actuate.health.RedisHealthIndicator;
import org.springframework.boot.actuate.health.SolrHealthIndicator;
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration;
import org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.jdbc.EmbeddedDataSourceConfiguration;
import org.springframework.boot.autoconfigure.jdbc.metadata.DataSourcePoolMetadataProvidersConfiguration;
import org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration;
import org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.EnvironmentTestUtils;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
/**
* Tests for {@link HealthIndicatorAutoConfiguration}.
*
* @author Christian Dupuis
* @author Stephane Nicoll
* @author Andy Wilkinson
*/
public class HealthIndicatorAutoConfigurationTests {
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
@After
public void close() {
if (this.context != null) {
this.context.close();
}
}
@Test
public void defaultHealthIndicator() {
this.context.register(HealthIndicatorAutoConfiguration.class,
ManagementServerProperties.class);
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.diskspace.enabled:false");
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void defaultHealthIndicatorsDisabled() {
this.context.register(HealthIndicatorAutoConfiguration.class,
ManagementServerProperties.class);
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.defaults.enabled:false");
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void defaultHealthIndicatorsDisabledWithCustomOne() {
this.context.register(CustomHealthIndicator.class,
HealthIndicatorAutoConfiguration.class, ManagementServerProperties.class);
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.defaults.enabled:false");
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertSame(this.context.getBean("customHealthIndicator"),
beans.values().iterator().next());
}
@Test
public void defaultHealthIndicatorsDisabledButOne() {
this.context.register(HealthIndicatorAutoConfiguration.class,
ManagementServerProperties.class);
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.defaults.enabled:false",
"management.health.diskspace.enabled:true");
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(DiskSpaceHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void redisHealthIndicator() {
this.context.register(RedisAutoConfiguration.class,
ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.diskspace.enabled:false");
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(RedisHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void notRedisHealthIndicator() {
this.context.register(RedisAutoConfiguration.class,
ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.redis.enabled:false",
"management.health.diskspace.enabled:false");
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void mongoHealthIndicator() {
this.context.register(MongoAutoConfiguration.class,
ManagementServerProperties.class, MongoDataAutoConfiguration.class,
HealthIndicatorAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.diskspace.enabled:false");
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(MongoHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void notMongoHealthIndicator() {
this.context.register(MongoAutoConfiguration.class,
ManagementServerProperties.class, MongoDataAutoConfiguration.class,
HealthIndicatorAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.mongo.enabled:false",
"management.health.diskspace.enabled:false");
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void combinedHealthIndicator() {
this.context.register(MongoAutoConfiguration.class, RedisAutoConfiguration.class,
MongoDataAutoConfiguration.class, SolrAutoConfiguration.class,
HealthIndicatorAutoConfiguration.class);
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(4, beans.size());
}
@Test
public void dataSourceHealthIndicator() {
this.context.register(EmbeddedDataSourceConfiguration.class,
ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.diskspace.enabled:false");
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(DataSourceHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void dataSourceHealthIndicatorWithCustomValidationQuery() {
this.context.register(PropertyPlaceholderAutoConfiguration.class,
ManagementServerProperties.class, DataSourceProperties.class,
DataSourceConfig.class,
DataSourcePoolMetadataProvidersConfiguration.class,
HealthIndicatorAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context,
"spring.datasource.validation-query:SELECT from FOOBAR",
"management.health.diskspace.enabled:false");
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
HealthIndicator healthIndicator = beans.values().iterator().next();
assertEquals(DataSourceHealthIndicator.class, healthIndicator.getClass());
DataSourceHealthIndicator dataSourceHealthIndicator = (DataSourceHealthIndicator) healthIndicator;
assertEquals("SELECT from FOOBAR", dataSourceHealthIndicator.getQuery());
}
@Test
public void notDataSourceHealthIndicator() {
this.context.register(EmbeddedDataSourceConfiguration.class,
ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.db.enabled:false",
"management.health.diskspace.enabled:false");
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void rabbitHealthIndicator() {
this.context.register(RabbitAutoConfiguration.class,
ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.diskspace.enabled:false");
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(RabbitHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void notRabbitHealthIndicator() {
this.context.register(RabbitAutoConfiguration.class,
ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.rabbit.enabled:false",
"management.health.diskspace.enabled:false");
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void solrHeathIndicator() {
this.context.register(SolrAutoConfiguration.class,
ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.diskspace.enabled:false");
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(SolrHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void notSolrHeathIndicator() {
this.context.register(SolrAutoConfiguration.class,
ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class);
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.solr.enabled:false",
"management.health.diskspace.enabled:false");
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void diskSpaceHealthIndicator() {
this.context.register(HealthIndicatorAutoConfiguration.class);
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(DiskSpaceHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void mailHealthIndicator() {
EnvironmentTestUtils.addEnvironment(this.context,
"spring.mail.host:smtp.acme.org",
"management.health.diskspace.enabled:false");
this.context.register(MailSenderAutoConfiguration.class,
ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class);
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(MailHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void notMailHealthIndicator() {
EnvironmentTestUtils.addEnvironment(this.context,
"spring.mail.host:smtp.acme.org", "management.health.mail.enabled:false",
"management.health.diskspace.enabled:false");
this.context.register(MailSenderAutoConfiguration.class,
ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class);
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void jmsHealthIndicator() {
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.diskspace.enabled:false");
this.context.register(ActiveMQAutoConfiguration.class,
ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class);
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(JmsHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void notJmsHealthIndicator() {
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.jms.enabled:false",
"management.health.diskspace.enabled:false");
this.context.register(ActiveMQAutoConfiguration.class,
ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class);
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void elasticSearchHealthIndicator() {
EnvironmentTestUtils.addEnvironment(this.context,
"spring.data.elasticsearch.properties.path.data:target/data",
"spring.data.elasticsearch.properties.path.logs:target/logs",
"management.health.diskspace.enabled:false");
this.context.register(ElasticsearchAutoConfiguration.class,
ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class);
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(ElasticsearchHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Test
public void notElasticSearchHealthIndicator() {
EnvironmentTestUtils.addEnvironment(this.context,
"management.health.elasticsearch.enabled:false",
"spring.data.elasticsearch.properties.path.data:target/data",
"spring.data.elasticsearch.properties.path.logs:target/logs",
"management.health.diskspace.enabled:false");
this.context.register(ElasticsearchAutoConfiguration.class,
ManagementServerProperties.class, HealthIndicatorAutoConfiguration.class);
this.context.refresh();
Map<String, HealthIndicator> beans = this.context
.getBeansOfType(HealthIndicator.class);
assertEquals(1, beans.size());
assertEquals(ApplicationHealthIndicator.class,
beans.values().iterator().next().getClass());
}
@Configuration
@EnableConfigurationProperties
protected static class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = DataSourceProperties.PREFIX)
public DataSource dataSource() {
return DataSourceBuilder.create()
.driverClassName("org.hsqldb.jdbc.JDBCDriver")
.url("jdbc:hsqldb:mem:test").username("sa").build();
}
}
@Configuration
protected static class CustomHealthIndicator {
@Bean
public HealthIndicator customHealthIndicator() {
return new HealthIndicator() {
@Override
public Health health() {
return Health.down().build();
}
};
}
}
}
| apache-2.0 |
lucky-code/Practice | kuaichuan2.0/app/src/main/java/com/lu/kuaichuan/wifidirect/adapter/MyGridViewAdapter.java | 3711 | package com.lu.kuaichuan.wifidirect.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.lu.kuaichuan.wifidirect.R;
import com.lu.kuaichuan.wifidirect.utils.BitmapUtils;
import com.lu.kuaichuan.wifidirect.utils.FileResLoaderUtils;
import com.lu.kuaichuan.wifidirect.utils.FileTypeUtils;
import java.util.ArrayList;
/**
* Created by admin on 2016/3/8.
*/
public class MyGridViewAdapter extends BaseAdapter {
private ArrayList<String> mNameList = new ArrayList<>();
private ArrayList<String> mPathList = new ArrayList<>();
private ArrayList<Boolean> mCheckBoxList = new ArrayList<>();
private LayoutInflater mInflater;
private Context mContext;
private int imagetViewHeight;
public MyGridViewAdapter(Context context, ArrayList<String> nameList, ArrayList<String> pathList, ArrayList<Boolean> checkBoxList, int imageViewHeigth) {
mNameList = nameList;
mPathList = pathList;
mCheckBoxList = checkBoxList;
mContext = context;
mInflater = LayoutInflater.from(mContext);
this.imagetViewHeight = (int) BitmapUtils.dipTopx(context, imageViewHeigth);
// this.imagetViewHeight = 100;
}
public ArrayList<Boolean> getmCheckBoxList() {
return this.mCheckBoxList;
}
@Override
public int getCount() {
return mNameList.size();
}
@Override
public Object getItem(int position) {
return mNameList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ItemViewTag viewTag;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.grid_view_item, null);
viewTag = new ItemViewTag((ImageView) convertView.findViewById(R.id.id_grid_view_icon_movie),
(TextView) convertView.findViewById(R.id.id_grid_view_name_movie), (CheckBox) convertView.findViewById(R.id.id_grid_view_checkbox_movie));
convertView.setTag(viewTag);
ViewGroup.LayoutParams lp = viewTag.mIcon.getLayoutParams();
lp.width = lp.height = this.imagetViewHeight;
viewTag.mIcon.setLayoutParams(lp);
} else {
viewTag = (ItemViewTag) convertView.getTag();
}
viewTag.mName.setText(mNameList.get(position));
String path = mPathList.get(position);
Object pic = FileResLoaderUtils.getPic(path);
if(pic instanceof Drawable) {
viewTag.mIcon.setImageDrawable((Drawable) pic);
}else if(pic instanceof Integer) {
viewTag.mIcon.setImageResource((Integer) pic);
}else if(pic instanceof Bitmap) {
viewTag.mIcon.setImageBitmap((Bitmap) pic);
}else {
viewTag.mIcon.setImageResource(FileTypeUtils.getDefaultFileIcon(path));
}
viewTag.mCheckBox.setChecked(mCheckBoxList.get(position));
viewTag.mCheckBox.setVisibility(mCheckBoxList.get(position) ? View.VISIBLE : View.GONE);
return convertView;
}
public class ItemViewTag {
public ImageView mIcon;
public TextView mName;
public CheckBox mCheckBox;
public ItemViewTag(ImageView icon, TextView name, CheckBox checkBox) {
mName = name;
mIcon = icon;
mCheckBox = checkBox;
}
}
}
| apache-2.0 |
jimmytheneutrino/petit | modules/converter/src/main/java/com/nortal/petit/converter/columnreader/ColumnReader.java | 825 | /**
* Copyright 2014 Nortal AS
*
* 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.nortal.petit.converter.columnreader;
import java.sql.ResultSet;
import java.sql.SQLException;
public interface ColumnReader<T> {
T getColumnValue(ResultSet rs, int index) throws SQLException;
} | apache-2.0 |
nmcl/scratch | graalvm/transactions/fork/narayana/ArjunaCore/arjuna/classes/com/arjuna/ats/arjuna/AtomicAction.java | 9975 | /*
* JBoss, Home of Professional Open Source
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
* (C) 2005-2006,
* @author JBoss Inc.
*/
/*
* Copyright (C) 1998, 1999, 2000,
*
* Arjuna Solutions Limited,
* Newcastle upon Tyne,
* Tyne and Wear,
* UK.
*
* $Id: AtomicAction.java 2342 2006-03-30 13:06:17Z $
*/
package com.arjuna.ats.arjuna;
import com.arjuna.ats.arjuna.common.Uid;
import com.arjuna.ats.arjuna.coordinator.ActionStatus;
import com.arjuna.ats.arjuna.coordinator.BasicAction;
import com.arjuna.ats.arjuna.coordinator.TransactionReaper;
import com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator;
import com.arjuna.ats.arjuna.coordinator.TxControl;
import com.arjuna.ats.arjuna.logging.tsLogger;
import com.arjuna.ats.internal.arjuna.thread.ThreadActionData;
/**
* This is a user-level transaction class, unlike BasicAction. AtomicAction
* takes care of thread-to-action scoping. This is a "one-shot" object, i.e.,
* once terminated, the instance cannot be re-used for another transaction.
*
* An instance of this class is a transaction that can be started and terminated
* (either committed or rolled back). There are also methods to allow
* participants (AbstractRecords) to be enlisted with the transaction and to
* associate/disassociate threads with the transaction.
*
* @author Mark Little (mark@arjuna.com)
* @version $Id: AtomicAction.java 2342 2006-03-30 13:06:17Z $
* @since JTS 1.0.
*/
public class AtomicAction extends TwoPhaseCoordinator
{
public static final int NO_TIMEOUT = -1;
/**
* Create a new transaction. If there is already a transaction associated
* with the thread then this new transaction will be automatically nested.
* The transaction is *not* running at this point.
*
* No timeout is associated with this transaction, i.e., it will not be
* automatically rolled back by the system.
*/
public AtomicAction ()
{
super();
}
/**
* AtomicAction constructor with a Uid. This constructor is for recreating
* an AtomicAction, typically during crash recovery.
*/
public AtomicAction (Uid objUid)
{
super(objUid);
}
/**
* Start the transaction running.
*
* If the transaction is already running or has terminated, then an error
* code will be returned. No timeout is associated with the transaction.
*
* @return <code>ActionStatus</code> indicating outcome.
*/
public int begin ()
{
return begin(AtomicAction.NO_TIMEOUT);
}
/**
* Start the transaction running.
*
* If the transaction is already running or has terminated, then an error
* code will be returned.
*
* @param timeout the timeout associated with the transaction. If the
* transaction is still active when this timeout elapses, the
* system will automatically roll it back.
*
* @return <code>ActionStatus</code> indicating outcome.
*/
public int begin (int timeout)
{
int status = super.start();
if (status == ActionStatus.RUNNING)
{
/*
* Now do thread/action tracking.
*/
ThreadActionData.pushAction(this);
_timeout = timeout;
if (_timeout == 0)
_timeout = TxControl.getDefaultTimeout();
if (_timeout > 0)
TransactionReaper.transactionReaper().insert(this, _timeout);
}
return status;
}
/**
* Commit the transaction, and have heuristic reporting. Heuristic reporting
* via the return code is enabled.
*
* @return <code>ActionStatus</code> indicating outcome.
*/
public int commit ()
{
return commit(true);
}
/**
* Commit the transaction. The report_heuristics parameter can be used to
* determine whether or not heuristic outcomes are reported.
*
* If the transaction has already terminated, or has not begun, then an
* appropriate error code will be returned.
*
* @return <code>ActionStatus</code> indicating outcome.
*/
public int commit (boolean report_heuristics)
{
int status = super.end(report_heuristics);
/*
* Now remove this thread from the action state.
*/
ThreadActionData.popAction();
TransactionReaper.transactionReaper().remove(this);
return status;
}
/**
* Abort (rollback) the transaction.
*
* If the transaction has already terminated, or has not been begun, then an
* appropriate error code will be returned.
*
* @return <code>ActionStatus</code> indicating outcome.
*/
public int abort ()
{
int status = super.cancel();
/*
* Now remove this thread from the action state.
*/
ThreadActionData.popAction();
TransactionReaper.transactionReaper().remove(this);
return status;
}
public int end (boolean report_heuristics)
{
int outcome = super.end(report_heuristics);
/*
* Now remove this thread from the reaper. Leave
* the thread-to-tx association though.
*/
TransactionReaper.transactionReaper().remove(this);
return outcome;
}
public int cancel ()
{
int outcome = super.cancel();
/*
* Now remove this thread from the reaper. Leave
* the thread-to-tx association though.
*/
TransactionReaper.transactionReaper().remove(this);
return outcome;
}
/*
* @return the timeout associated with this instance.
*/
public final int getTimeout ()
{
return _timeout;
}
/**
* The type of the class is used to locate the state of the transaction log
* in the object store.
*
* Overloads BasicAction.type()
*
* @return a string representation of the hierarchy of the class for storing
* logs in the transaction object store.
*/
public String type ()
{
return "/StateManager/BasicAction/TwoPhaseCoordinator/AtomicAction";
}
/**
* Register the current thread with the transaction. This operation is not
* affected by the state of the transaction.
*
* @return <code>true</code> if successful, <code>false</code>
* otherwise.
*/
public boolean addThread ()
{
return addThread(Thread.currentThread());
}
/**
* Register the specified thread with the transaction. This operation is not
* affected by the state of the transaction.
*
* @return <code>true</code> if successful, <code>false</code>
* otherwise.
*/
public boolean addThread (Thread t)
{
if (t != null)
{
ThreadActionData.pushAction(this);
return true;
}
return false;
}
/**
* Unregister the current thread from the transaction. This operation is not
* affected by the state of the transaction.
*
* @return <code>true</code> if successful, <code>false</code>
* otherwise.
*/
public boolean removeThread ()
{
return removeThread(Thread.currentThread());
}
/**
* Unregister the specified thread from the transaction. This operation is
* not affected by the state of the transaction.
*
* @return <code>true</code> if successful, <code>false</code>
* otherwise.
*/
public boolean removeThread (Thread t)
{
if (t != null)
{
ThreadActionData.purgeAction(this, t);
return true;
}
return false;
}
/**
* Suspend all transaction association from the invoking thread. When this
* operation returns, the thread will be associated with no transactions.
*
* If the current transaction is not an AtomicAction then this method will
* not suspend.
*
* @return a handle on the current AtomicAction (if any) so that the thread
* can later resume association if required.
*
*/
public static final AtomicAction suspend ()
{
BasicAction curr = ThreadActionData.currentAction();
if (curr != null)
{
if (curr instanceof AtomicAction)
ThreadActionData.purgeActions();
else {
tsLogger.i18NLogger.warn_ats_atomicaction_1(curr.toString());
curr = null;
}
}
return (AtomicAction) curr;
}
/**
* Resume transaction association on the current thread. If the specified
* transaction is null, then this is the same as doing a suspend. If the
* current thread is associated with transactions then those associations
* will be lost.
*
* @param act the transaction to associate. If this is a nested
* transaction, then the thread will be associated with all of
* the transactions in the hierarchy.
*
* @return <code>true</code> if association is successful,
* <code>false</code> otherwise.
*/
public static final boolean resume (AtomicAction act)
{
if (act == null)
{
suspend(); // If you ever change this, you need to change the way resume is handled in /ArjunaJTS/integration/src/main/java/com/arjuna/ats/jbossatx/BaseTransactionManagerDelegate.java
}
else
ThreadActionData.restoreActions(act);
return true;
}
/**
* Create a new transaction of the specified type.
*/
protected AtomicAction (int at)
{
super(at);
}
/**
* By default the BasicAction class only allows the termination of a
* transaction if it's the one currently associated with the thread. We
* override this here.
*
* @return <code>true</code> to indicate that this transaction can only be
* terminated by the right thread.
*/
protected boolean checkForCurrent ()
{
return true;
}
private int _timeout = NO_TIMEOUT;
}
| apache-2.0 |
patrickfav/tuwien | master/swt workspace/HTMLParser/src/org/htmlparser/nodes/TextNode.java | 6785 | // HTMLParser Library - A java-based parser for HTML
// http://htmlparser.org
// Copyright (C) 2006 Derrick Oswald
//
// Revision Control Information
//
// $URL: https://svn.sourceforge.net/svnroot/htmlparser/trunk/lexer/src/main/java/org/htmlparser/nodes/TextNode.java $
// $Author: derrickoswald $
// $Date: 2006-09-16 10:44:17 -0400 (Sat, 16 Sep 2006) $
// $Revision: 4 $
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Common Public License; either
// version 1.0 of the License, or (at your option) any later version.
//
// This library 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
// Common Public License for more details.
//
// You should have received a copy of the Common Public License
// along with this library; if not, the license is available from
// the Open Source Initiative (OSI) website:
// http://opensource.org/licenses/cpl1.0.php
package org.htmlparser.nodes;
import org.htmlparser.Text;
import org.htmlparser.lexer.Cursor;
import org.htmlparser.lexer.Page;
import org.htmlparser.util.ParserException;
import org.htmlparser.visitors.NodeVisitor;
/**
* Normal text in the HTML document is represented by this class.
*/
public class TextNode
extends
AbstractNode
implements
Text
{
/**
* The contents of the string node, or override text.
*/
protected String mText;
/**
* Constructor takes in the text string.
* @param text The string node text. For correct generation of HTML, this
* should not contain representations of tags (unless they are balanced).
*/
public TextNode (String text)
{
super (null, 0, 0);
setText (text);
}
/**
* Constructor takes in the page and beginning and ending posns.
* @param page The page this string is on.
* @param start The beginning position of the string.
* @param end The ending positiong of the string.
*/
public TextNode (Page page, int start, int end)
{
super (page, start, end);
mText = null;
}
/**
* Returns the text of the node.
* This is the same as {@link #toHtml} for this type of node.
* @return The contents of this text node.
*/
public String getText ()
{
return (toHtml ());
}
/**
* Sets the string contents of the node.
* @param text The new text for the node.
*/
public void setText (String text)
{
mText = text;
nodeBegin = 0;
nodeEnd = mText.length ();
}
/**
* Returns the text of the node.
* This is the same as {@link #toHtml} for this type of node.
* @return The contents of this text node.
*/
public String toPlainTextString ()
{
return (toHtml ());
}
/**
* Returns the text of the node.
* @param verbatim If <code>true</code> return as close to the original
* page text as possible.
* @return The contents of this text node.
*/
public String toHtml (boolean verbatim)
{
String ret;
ret = mText;
if (null == ret)
ret = mPage.getText (getStartPosition (), getEndPosition ());
return (ret);
}
/**
* Express this string node as a printable string
* This is suitable for display in a debugger or output to a printout.
* Control characters are replaced by their equivalent escape
* sequence and contents is truncated to 80 characters.
* @return A string representation of the string node.
*/
public String toString ()
{
int startpos;
int endpos;
Cursor start;
Cursor end;
char c;
StringBuffer ret;
startpos = getStartPosition ();
endpos = getEndPosition ();
ret = new StringBuffer (endpos - startpos + 20);
if (null == mText)
{
start = new Cursor (getPage (), startpos);
end = new Cursor (getPage (), endpos);
ret.append ("Txt (");
ret.append (start);
ret.append (",");
ret.append (end);
ret.append ("): ");
while (start.getPosition () < endpos)
{
try
{
c = mPage.getCharacter (start);
switch (c)
{
case '\t':
ret.append ("\\t");
break;
case '\n':
ret.append ("\\n");
break;
case '\r':
ret.append ("\\r");
break;
default:
ret.append (c);
}
}
catch (ParserException pe)
{
// not really expected, but we're only doing toString, so ignore
}
if (77 <= ret.length ())
{
ret.append ("...");
break;
}
}
}
else
{
ret.append ("Txt (");
ret.append (startpos);
ret.append (",");
ret.append (endpos);
ret.append ("): ");
for (int i = 0; i < mText.length (); i++)
{
c = mText.charAt (i);
switch (c)
{
case '\t':
ret.append ("\\t");
break;
case '\n':
ret.append ("\\n");
break;
case '\r':
ret.append ("\\r");
break;
default:
ret.append (c);
}
if (77 <= ret.length ())
{
ret.append ("...");
break;
}
}
}
return (ret.toString ());
}
/**
* Returns if the node consists of only white space.
* White space can be spaces, new lines, etc.
*/
public boolean isWhiteSpace()
{
if (mText == null || mText.trim().equals(""))
return true;
return false;
}
/**
* String visiting code.
* @param visitor The <code>NodeVisitor</code> object to invoke
* <code>visitStringNode()</code> on.
*/
public void accept (NodeVisitor visitor)
{
visitor.visitStringNode (this);
}
}
| apache-2.0 |
antoinesd/weld-core | tests-arquillian/src/test/java/org/jboss/weld/tests/el/resolver/MyBean.java | 957 | /*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.tests.el.resolver;
import javax.inject.Named;
@Named("com.acme.settings")
public class MyBean {
public String getFoo() {
return "foo";
}
}
| apache-2.0 |
prabushi/devstudio-tooling-esb | plugins/org.wso2.developerstudio.eclipse.gmf.esb.diagram/src/org/wso2/developerstudio/eclipse/gmf/esb/diagram/edit/parts/EnqueueMediatorInputConnectorEditPart.java | 11166 | package org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.parts;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Shape;
import org.eclipse.draw2d.StackLayout;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.LayoutEditPolicy;
import org.eclipse.gef.editpolicies.NonResizableEditPolicy;
import org.eclipse.gef.requests.CreateRequest;
import org.eclipse.gmf.runtime.diagram.ui.editparts.AbstractBorderItemEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.gef.ui.figures.DefaultSizeNodeFigure;
import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.swt.graphics.Color;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.AbstractMediatorInputConnectorEditPart;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.custom.EastPointerShape;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.edit.policies.EnqueueMediatorInputConnectorItemSemanticEditPolicy;
import org.wso2.developerstudio.eclipse.gmf.esb.diagram.providers.EsbElementTypes;
/**
* @generated NOT
*/
public class EnqueueMediatorInputConnectorEditPart extends AbstractMediatorInputConnectorEditPart {
/**
* @generated
*/
public static final int VISUAL_ID = 3601;
/**
* @generated
*/
protected IFigure contentPane;
/**
* @generated
*/
protected IFigure primaryShape;
/**
* @generated
*/
public EnqueueMediatorInputConnectorEditPart(View view) {
super(view);
}
/**
* @generated
*/
protected void createDefaultEditPolicies() {
super.createDefaultEditPolicies();
installEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE, getPrimaryDragEditPolicy());
installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE, new EnqueueMediatorInputConnectorItemSemanticEditPolicy());
installEditPolicy(EditPolicy.LAYOUT_ROLE, createLayoutEditPolicy());
// XXX need an SCR to runtime to have another abstract superclass that would let children add reasonable
// editpolicies
removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.CONNECTION_HANDLES_ROLE);
}
/**
* @generated
*/
protected LayoutEditPolicy createLayoutEditPolicy() {
org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy lep = new org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy() {
protected EditPolicy createChildEditPolicy(EditPart child) {
EditPolicy result = child.getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE);
if (result == null) {
result = new NonResizableEditPolicy();
}
return result;
}
protected Command getMoveChildrenCommand(Request request) {
return null;
}
protected Command getCreateCommand(CreateRequest request) {
return null;
}
};
return lep;
}
/**
* @generated
*/
protected IFigure createNodeShape() {
return primaryShape = new EastPointerFigure();
}
/**
* @generated
*/
public EastPointerFigure getPrimaryShape() {
return (EastPointerFigure) primaryShape;
}
/**
* @generated
*/
protected NodeFigure createNodePlate() {
DefaultSizeNodeFigure result = new DefaultSizeNodeFigure(12, 10);
// FIXME: workaround for #154536
result.getBounds().setSize(result.getPreferredSize());
return result;
}
/**
* Creates figure for this edit part.
*
* Body of this method does not depend on settings in generation model
* so you may safely remove <i>generated</i> tag and modify it.
*
* @generated NOT
*/
protected NodeFigure createNodeFigure() {
NodeFigure figure = createNodePlate();
figure.setLayoutManager(new StackLayout());
IFigure shape = createNodeShapeForward();
figure.add(shape);
contentPane = setupContentPane(shape);
figure_ = figure;
createNodeShapeReverse();
return figure;
}
/**
* Default implementation treats passed figure as content pane.
* Respects layout one may have set for generated figure.
*
* @param nodeShape instance of generated figure class
* @generated
*/
protected IFigure setupContentPane(IFigure nodeShape) {
return nodeShape; // use nodeShape itself as contentPane
}
/**
* @generated
*/
public IFigure getContentPane() {
if (contentPane != null) {
return contentPane;
}
return super.getContentPane();
}
/**
* @generated
*/
protected void setForegroundColor(Color color) {
if (primaryShape != null) {
primaryShape.setForegroundColor(color);
}
}
/**
* @generated
*/
protected void setBackgroundColor(Color color) {
if (primaryShape != null) {
primaryShape.setBackgroundColor(color);
}
}
/**
* @generated
*/
protected void setLineWidth(int width) {
if (primaryShape instanceof Shape) {
((Shape) primaryShape).setLineWidth(width);
}
}
/**
* @generated
*/
protected void setLineType(int style) {
if (primaryShape instanceof Shape) {
((Shape) primaryShape).setLineStyle(style);
}
}
/**
* @generated
*/
public List<IElementType> getMARelTypesOnTarget() {
ArrayList<IElementType> types = new ArrayList<IElementType>(1);
types.add(EsbElementTypes.EsbLink_4001);
return types;
}
/**
* @generated
*/
public List<IElementType> getMATypesForSource(IElementType relationshipType) {
LinkedList<IElementType> types = new LinkedList<IElementType>();
if (relationshipType == EsbElementTypes.EsbLink_4001) {
types.add(EsbElementTypes.ProxyOutputConnector_3002);
types.add(EsbElementTypes.PropertyMediatorOutputConnector_3034);
types.add(EsbElementTypes.PropertyGroupMediatorOutputConnector_3790);
types.add(EsbElementTypes.ThrottleMediatorOutputConnector_3122);
types.add(EsbElementTypes.ThrottleMediatorOnAcceptOutputConnector_3581);
types.add(EsbElementTypes.ThrottleMediatorOnRejectOutputConnector_3582);
types.add(EsbElementTypes.FilterMediatorOutputConnector_3534);
types.add(EsbElementTypes.FilterMediatorPassOutputConnector_3011);
types.add(EsbElementTypes.FilterMediatorFailOutputConnector_3012);
types.add(EsbElementTypes.LogMediatorOutputConnector_3019);
types.add(EsbElementTypes.EnrichMediatorOutputConnector_3037);
types.add(EsbElementTypes.XSLTMediatorOutputConnector_3040);
types.add(EsbElementTypes.SwitchCaseBranchOutputConnector_3043);
types.add(EsbElementTypes.SwitchDefaultBranchOutputConnector_3044);
types.add(EsbElementTypes.SwitchMediatorOutputConnector_3499);
types.add(EsbElementTypes.SequenceOutputConnector_3050);
types.add(EsbElementTypes.EventMediatorOutputConnector_3053);
types.add(EsbElementTypes.EntitlementMediatorOutputConnector_3056);
types.add(EsbElementTypes.ClassMediatorOutputConnector_3059);
types.add(EsbElementTypes.SpringMediatorOutputConnector_3062);
types.add(EsbElementTypes.ScriptMediatorOutputConnector_3065);
types.add(EsbElementTypes.FaultMediatorOutputConnector_3068);
types.add(EsbElementTypes.XQueryMediatorOutputConnector_3071);
types.add(EsbElementTypes.CommandMediatorOutputConnector_3074);
types.add(EsbElementTypes.DBLookupMediatorOutputConnector_3077);
types.add(EsbElementTypes.DBReportMediatorOutputConnector_3080);
types.add(EsbElementTypes.SmooksMediatorOutputConnector_3083);
types.add(EsbElementTypes.SendMediatorOutputConnector_3086);
types.add(EsbElementTypes.SendMediatorEndpointOutputConnector_3539);
types.add(EsbElementTypes.DefaultEndPointOutputConnector_3022);
types.add(EsbElementTypes.AddressEndPointOutputConnector_3031);
types.add(EsbElementTypes.FailoverEndPointOutputConnector_3090);
types.add(EsbElementTypes.FailoverEndPointWestOutputConnector_3097);
types.add(EsbElementTypes.WSDLEndPointOutputConnector_3093);
types.add(EsbElementTypes.LoadBalanceEndPointOutputConnector_3096);
types.add(EsbElementTypes.LoadBalanceEndPointWestOutputConnector_3098);
types.add(EsbElementTypes.HeaderMediatorOutputConnector_3101);
types.add(EsbElementTypes.CloneMediatorOutputConnector_3104);
types.add(EsbElementTypes.CloneMediatorTargetOutputConnector_3133);
types.add(EsbElementTypes.CacheMediatorOutputConnector_3107);
types.add(EsbElementTypes.IterateMediatorOutputConnector_3110);
types.add(EsbElementTypes.CalloutMediatorOutputConnector_3116);
types.add(EsbElementTypes.TransactionMediatorOutputConnector_3119);
types.add(EsbElementTypes.RMSequenceMediatorOutputConnector_3125);
types.add(EsbElementTypes.RuleMediatorOutputConnector_3128);
types.add(EsbElementTypes.OAuthMediatorOutputConnector_3131);
types.add(EsbElementTypes.AggregateMediatorOutputConnector_3113);
types.add(EsbElementTypes.AggregateMediatorOnCompleteOutputConnector_3132);
types.add(EsbElementTypes.StoreMediatorOutputConnector_3590);
types.add(EsbElementTypes.BuilderMediatorOutputConector_3593);
types.add(EsbElementTypes.CallTemplateMediatorOutputConnector_3596);
types.add(EsbElementTypes.PayloadFactoryMediatorOutputConnector_3599);
types.add(EsbElementTypes.EnqueueMediatorOutputConnector_3602);
types.add(EsbElementTypes.MessageOutputConnector_3047);
types.add(EsbElementTypes.MergeNodeOutputConnector_3016);
types.add(EsbElementTypes.JsonTransformMediatorOutputConnector_3793);
}
return types;
}
/**
* @generated
*/
public class EastPointerFigure extends EastPointerShape {
/**
* @generated
*/
public EastPointerFigure() {
this.setBackgroundColor(THIS_BACK);
this.setPreferredSize(new Dimension(getMapMode().DPtoLP(12), getMapMode().DPtoLP(10)));
}
}
/**
* @generated
*/
static final Color THIS_BACK = new Color(null, 50, 50, 50);
}
| apache-2.0 |
Flipkart/elasticsearch | src/main/java/org/elasticsearch/rest/action/admin/cluster/repositories/get/RestGetRepositoriesAction.java | 3286 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.rest.action.admin.cluster.repositories.get;
import org.elasticsearch.action.admin.cluster.repositories.get.GetRepositoriesRequest;
import org.elasticsearch.action.admin.cluster.repositories.get.GetRepositoriesResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.RepositoriesMetaData;
import org.elasticsearch.cluster.metadata.RepositoryMetaData;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.*;
import org.elasticsearch.rest.action.support.RestBuilderListener;
import static org.elasticsearch.client.Requests.getRepositoryRequest;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestStatus.OK;
/**
* Returns repository information
*/
public class RestGetRepositoriesAction extends BaseRestHandler {
@Inject
public RestGetRepositoriesAction(Settings settings, RestController controller, Client client) {
super(settings, controller, client);
controller.registerHandler(GET, "/_snapshot", this);
controller.registerHandler(GET, "/_snapshot/{repository}", this);
}
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
final String[] repositories = request.paramAsStringArray("repository", Strings.EMPTY_ARRAY);
GetRepositoriesRequest getRepositoriesRequest = getRepositoryRequest(repositories);
getRepositoriesRequest.masterNodeTimeout(request.paramAsTime("master_timeout", getRepositoriesRequest.masterNodeTimeout()));
getRepositoriesRequest.local(request.paramAsBoolean("local", getRepositoriesRequest.local()));
client.admin().cluster().getRepositories(getRepositoriesRequest, new RestBuilderListener<GetRepositoriesResponse>(channel) {
@Override
public RestResponse buildResponse(GetRepositoriesResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
for (RepositoryMetaData repositoryMetaData : response.repositories()) {
RepositoriesMetaData.toXContent(repositoryMetaData, builder, request);
}
builder.endObject();
return new BytesRestResponse(OK, builder);
}
});
}
}
| apache-2.0 |
lhyqie/rtree | src/test/java/com/github/davidmoten/rtree/GreekEarthquakes.java | 2411 | package com.github.davidmoten.rtree;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.zip.GZIPInputStream;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;
import rx.observables.StringObservable;
import com.github.davidmoten.rtree.geometry.Geometries;
import com.github.davidmoten.rtree.geometry.Point;
public class GreekEarthquakes {
static Observable<Entry<Object, Point>> entries() {
Observable<String> source = Observable.using(new Func0<InputStream>() {
@Override
public InputStream call() {
try {
return new GZIPInputStream(GreekEarthquakes.class
.getResourceAsStream("/greek-earthquakes-1964-2000.txt.gz"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}, new Func1<InputStream, Observable<String>>() {
@Override
public Observable<String> call(InputStream is) {
return StringObservable.from(new InputStreamReader(is));
}
}, new Action1<InputStream>() {
@Override
public void call(InputStream is) {
try {
is.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
return StringObservable.split(source, "\n").flatMap(
new Func1<String, Observable<Entry<Object, Point>>>() {
@Override
public Observable<Entry<Object, Point>> call(String line) {
if (line.trim().length() > 0) {
String[] items = line.split(" ");
double lat = Double.parseDouble(items[0]);
double lon = Double.parseDouble(items[1]);
return Observable.just(Entry.entry(new Object(),
Geometries.point(lat, lon)));
} else
return Observable.empty();
}
});
}
static List<Entry<Object, Point>> entriesList() {
return entries().toList().toBlocking().single();
}
}
| apache-2.0 |
rosmo/aurora | src/test/java/org/apache/aurora/scheduler/events/PubsubEventModuleTest.java | 4254 | /**
* 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.apache.aurora.scheduler.events;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.Executor;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import org.apache.aurora.GuavaUtils;
import org.apache.aurora.common.stats.StatsProvider;
import org.apache.aurora.common.testing.easymock.EasyMockTest;
import org.apache.aurora.scheduler.AppStartup;
import org.apache.aurora.scheduler.SchedulerServicesModule;
import org.apache.aurora.scheduler.app.LifecycleModule;
import org.apache.aurora.scheduler.async.AsyncModule.AsyncExecutor;
import org.apache.aurora.scheduler.filter.SchedulingFilter;
import org.apache.aurora.scheduler.testing.FakeStatsProvider;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import static org.easymock.EasyMock.anyString;
import static org.easymock.EasyMock.eq;
import static org.junit.Assert.assertEquals;
public class PubsubEventModuleTest extends EasyMockTest {
private FakeStatsProvider statsProvider;
private Logger logger;
private UncaughtExceptionHandler exceptionHandler;
private SchedulingFilter schedulingFilter;
@Before
public void setUp() {
statsProvider = new FakeStatsProvider();
logger = createMock(Logger.class);
exceptionHandler = createMock(UncaughtExceptionHandler.class);
schedulingFilter = createMock(SchedulingFilter.class);
}
@Test
public void testHandlesDeadEvent() {
logger.warning(String.format(PubsubEventModule.DEAD_EVENT_MESSAGE, "hello"));
control.replay();
getInjector().getInstance(EventBus.class).post("hello");
}
@Test
public void testPubsubExceptionTracking() throws Exception {
logger.log(eq(Level.SEVERE), anyString(), EasyMock.<Throwable>anyObject());
control.replay();
Injector injector = getInjector(
new AbstractModule() {
@Override
protected void configure() {
PubsubEventModule.bindSubscriber(binder(), ThrowingSubscriber.class);
}
});
injector.getInstance(Key.get(GuavaUtils.ServiceManagerIface.class, AppStartup.class))
.startAsync().awaitHealthy();
assertEquals(0L, statsProvider.getLongValue(PubsubEventModule.EXCEPTIONS_STAT));
injector.getInstance(EventBus.class).post("hello");
assertEquals(1L, statsProvider.getLongValue(PubsubEventModule.EXCEPTIONS_STAT));
}
static class ThrowingSubscriber implements PubsubEvent.EventSubscriber {
@Subscribe
public void receiveString(String value) {
throw new UnsupportedOperationException();
}
}
public Injector getInjector(Module... additionalModules) {
return Guice.createInjector(
new LifecycleModule(),
new PubsubEventModule(logger),
new SchedulerServicesModule(),
new AbstractModule() {
@Override
protected void configure() {
bind(Executor.class).annotatedWith(AsyncExecutor.class)
.toInstance(MoreExecutors.sameThreadExecutor());
bind(UncaughtExceptionHandler.class).toInstance(exceptionHandler);
bind(StatsProvider.class).toInstance(statsProvider);
PubsubEventModule.bindSchedulingFilterDelegate(binder()).toInstance(schedulingFilter);
for (Module module : additionalModules) {
install(module);
}
}
});
}
}
| apache-2.0 |
wyg1990/Mallet | src/main/java/com/intel/mallet/TpcdsTool.java | 3375 | /**
* 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.intel.mallet;
import java.util.logging.Logger;
import java.io.File;
import java.io.IOException;
public class TpcdsTool {
private static final Logger logger = Logger.getLogger(TpcdsTool.class.getName());
public static String[] generateStreamSqlFile(int numberOfStreams) throws MalletException {
Conf conf = Conf.getConf();
// Build cmd string
// /*WORKAROUND*/
// String templateDirectory = conf.getBaseDirectory() + "/query_templates";
// It seems the dsqgen tool has problem with long path time, so workaround here is
// that the tool is under the tool directory of the program base directory.
String templateDirectory = "../query_templates";
if (conf.isQuickRunMode()) {
templateDirectory += "/quickrun";
}
String templateListFile = templateDirectory + "/templates.lst";
String outputDirectory = conf.getTempDirectory();
String cmd = "./dsqgen -INPUT " + templateListFile + " -DIRECTORY " + templateDirectory +
" -OUTPUT_DIR " + outputDirectory + " -DIALECT hive -STREAMS " +
numberOfStreams + " -SCALE " + conf.getScale();
if (conf.isSingleQueryMode()) {
cmd += " -TEMPLATE query" + conf.getQueryId() + ".tpl";
}
// Invoke the TPC-DS tool to generate queries from templates
logger.info("Invoke TPC-DS tool to generate queries from templates:");
logger.info(" " + cmd);
Process toolProcess;
try {
toolProcess = Runtime.getRuntime().exec(cmd, null, new File(conf.getTpcDsToolDirectory()));
} catch (IOException e) {
throw new MalletException("Failed to invoke TPC-DS tool.", e);
}
// Wait for the termination of the tool process
try {
toolProcess.waitFor();
} catch (InterruptedException e) {
}
// Check if the tool process has any error
if(toolProcess.exitValue() != 0) {
throw new MalletException("TPC-DS tool exited with error.");
}
// return the SQL file names for each stream
String[] sqlFileNames = new String[numberOfStreams];
for(int i = 0; i < numberOfStreams; i++) {
String sqlFileName = outputDirectory + "/query_" + i + ".sql";
sqlFileNames[i] = sqlFileName;
// Make sure the file exists
if (!(new File(sqlFileName)).exists()) {
throw new MalletException("TPC-DS tool succeeded, but can't find " + sqlFileName);
}
}
return sqlFileNames;
}
public static void generateRefreshDataSets() throws MalletException {
Conf conf = Conf.getConf();
// TODO
}
}
| apache-2.0 |